text:
#region License

// Copyright (C) Tomáš Pažourek, 2014
// All rights reserved.
//
// Distributed under MIT license as a part of project Colourful.
// https://github.com/tompazourek/Colourful

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Colourful.Conversion;
using NUnit.Framework;
using DataRow = Colourful.Tests.ColorCheckerCalculatorData.Row;

namespace Colourful.Tests
{
    [TestFixture]
    public class ColorCheckerCalculatorTest
    {
        private readonly DataRow[] TestData;
        private readonly ColourfulConverter _converter;

        public ColorCheckerCalculatorTest()
        {
            TestData = ColorCheckerCalculatorData.GetData().ToArray();
            _converter = new ColourfulConverter
                {
                    WhitePoint = Illuminants.C,
                    TargetRGBWorkingSpace = RGBWorkingSpaces.sRGB,
                    TargetLabWhitePoint = Illuminants.C,
                    TargetLuvWhitePoint = Illuminants.C,
                    ChromaticAdaptation = new VonKriesChromaticAdaptation()
                };
        }

        private void RethrowException(AssertionException ex, DataRow row)
        {
            throw new AssertionException(string.Format("[{0}]\n{1}", row.Name, ex.Message), ex);
        }

        [TestCaseSource("TestData")]
        public void Convert_Lab_to_XYZ(DataRow row)
        {
            var inputLab = row.GetLabColor();
            var expectedXYZ = row.GetXYZColor();
            var actualXYZ = _converter.ToXYZ(inputLab);
            try
            {
                Assert.That(actualXYZ, Is.EqualTo(expectedXYZ)
                    .Using(new ColorVectorComparer(new DoubleDeltaComparer(0.000001))));
            }
            catch (AssertionException ex) { RethrowException(ex, row); }
        }

        [TestCaseSource("TestData")]
        public void Convert_Lab_to_RGB(DataRow row)
        {
            var inputLab = row.GetLabColor();
            var expectedRGB = row.GetRGBColor();
            var actualRGB = _converter.ToRGB(inputLab);
            try
            {
                Assert.That(actualRGB, Is.EqualTo(expectedRGB)
                    .Using(new ColorVectorComparer(new DoubleDeltaComparer(0.00912))));
            }
            catch (AssertionException ex) { RethrowException(ex, row); }
        }

        [TestCaseSource("TestData")]
        public void Convert_Lab_to_xyY(DataRow row)
        {
            var inputLab = row.GetLabColor();
            var expectedxyY = row.GetxyYColor();
            var actualxyY = _converter.ToxyY(inputLab);
            try
            {
                Assert.That(actualxyY, Is.EqualTo(expectedxyY)
                    .Using(new ColorVectorComparer(new DoubleDeltaComparer(0.000001))));
            }
            catch (AssertionException ex) { RethrowException(ex, row); }
        }

        [TestCaseSource("TestData")]
        public void Convert_Lab_to_LChab(DataRow row)
        {
            var inputLab = row.GetLabColor();
            var expectedLChab = row.GetLChabColor();
            var actualLChab = _converter.ToLChab(inputLab);
            try
            {
                Assert.That(actualLChab, Is.EqualTo(expectedLChab)
                    .Using(new ColorVectorComparer(new DoubleDeltaComparer(0.00017))));
            }
            catch (AssertionException ex) { RethrowException(ex, row); }
        }

        [TestCaseSource("TestData")]
        public void Convert_Lab_to_LChuv(DataRow row)
        {
            var inputLab = row.GetLabColor();
            var expectedLChuv = row.GetLChuvColor();
            var actualLChuv = _converter.ToLChuv(inputLab);
            try
            {
                Assert.That(actualLChuv, Is.EqualTo(expectedLChuv)
                    .Using(new ColorVectorComparer(new DoubleDeltaComparer(0.00022))));
            }
            catch (AssertionException ex) { RethrowException(ex, row); }
        }

        [TestCaseSource("TestData")]
        public void Convert_Lab_to_Luv(DataRow row)
        {
            var inputLab = row.GetLabColor();
            var expectedLuv = row.GetLuvColor();
            var actualLuv = _converter.ToLuv(inputLab);
            try
            {
                Assert.That(actualLuv, Is.EqualTo(expectedLuv)
                    .Using(new ColorVectorComparer(new DoubleDeltaComparer(0.00000105))));
            }
            catch (AssertionException ex) { RethrowException(ex, row); }
        }
    }
}


text:
package org.pac4j.springframework.security.util;

import org.pac4j.core.authorization.authorizer.Authorizer;
import org.pac4j.core.authorization.authorizer.IsFullyAuthenticatedAuthorizer;
import org.pac4j.core.authorization.authorizer.IsRememberedAuthorizer;
import org.pac4j.core.exception.HttpAction;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.profile.ProfileHelper;
import org.pac4j.springframework.security.authentication.Pac4jAuthenticationToken;
import org.pac4j.springframework.security.authentication.Pac4jRememberMeAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

/**
 * Helper for Spring Security.
 *
 * @author Jerome Leleu
 * @since 2.0.0
 */
public final class SpringSecurityHelper {

    private final static Authorizer<CommonProfile> IS_REMEMBERED_AUTHORIZER = new IsRememberedAuthorizer<>();

    private final static Authorizer<CommonProfile> IS_FULLY_AUTHENTICATED_AUTHORIZER = new IsFullyAuthenticatedAuthorizer<>();

    /**
     * Build a list of authorities from a map of profiles.
     *
     * @param profiles a map of profiles
     * @return a list of authorities
     */
    public static List<GrantedAuthority> buildAuthorities(final LinkedHashMap<String, CommonProfile> profiles) {
        final List<GrantedAuthority> authorities = new ArrayList<>();
        final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles);
        for (final CommonProfile profile : listProfiles) {
            final Set<String> roles = profile.getRoles();
            for (final String role : roles) {
                authorities.add(new SimpleGrantedAuthority(role));
            }
        }
        return authorities;
    }

    /**
     * Populate the authenticated user profiles in the Spring Security context.
     *
     * @param profiles the linked hashmap of profiles
     */
    public static void populateAuthentication(final LinkedHashMap<String, CommonProfile> profiles) {
        if (profiles != null && profiles.size() > 0) {
            final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles);
            try {
                if (IS_FULLY_AUTHENTICATED_AUTHORIZER.isAuthorized(null, listProfiles)) {
                    SecurityContextHolder.getContext().setAuthentication(new Pac4jAuthenticationToken(profiles));
                } else if (IS_REMEMBERED_AUTHORIZER.isAuthorized(null, listProfiles)) {
                    SecurityContextHolder.getContext().setAuthentication(new Pac4jRememberMeAuthenticationToken(profiles));
                }
            } catch (final HttpAction e) {
                throw new TechnicalException(e);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require File.dirname(__FILE__) + '/../lib/git-process/new_fb'
require 'GitRepoHelper'
include GitProc

describe NewFeatureBranch do
  include GitRepoHelper

  before(:each) do
    create_files(%w(.gitignore))
    gitlib.commit('initial')
  end

  after(:each) do
    rm_rf(gitlib.workdir)
  end

  def create_process(dir, opts = {})
    opts[:branch_name] = 'test_branch'
    NewFeatureBranch.new(dir, opts)
  end

  def log_level
    Logger::ERROR
  end

  it 'should create the named branch against origin/master' do
    clone_repo do |gl|
      gp = create_process(gl)
      gl.checkout('other_branch', :new_branch => 'master')
      change_file_and_commit('a', '', gl)
      change_file_and_commit('b', '', gl)
      new_branch = gp.runner

      new_branch.name.should == 'test_branch'
      new_branch.sha.should == gl.branches['origin/master'].sha
    end
  end

  it 'should bring committed changes on _parking_ over to the new branch' do
    clone_repo do |gl|
      gl.checkout('_parking_', :new_branch => 'master')
      change_file_and_commit('a', '', gl)
      change_file_and_commit('b', '', gl)

      gp = create_process(gl)
      new_branch = gp.runner

      new_branch.name.should == 'test_branch'
      Dir.chdir(gl.workdir) do |_|
        File.exists?('a').should be true
        File.exists?('b').should be true
      end

      gl.config['branch.test_branch.remote'].should == 'origin'
      gl.config['branch.test_branch.merge'].should == 'refs/heads/master'

      gl.fetch
      gl.branches.parking.should be_nil
      new_branch.sha.should_not == gl.branches['origin/master'].sha
    end

  end

  it 'should move new branch over to the integration branch' do
    clone_repo do |gl|
      gl.checkout('_parking_', :new_branch => 'master')
      change_file_and_commit('a', '', gitlib)
      change_file_and_commit('b', '', gitlib)

      gl.fetch
      gp = create_process(gl)
      new_branch = gp.runner

      new_branch.name.should == 'test_branch'
      Dir.chdir(gitlib.workdir) do |_|
        File.exists?('a').should be true
        File.exists?('b').should be true
      end

      gl.config["branch.test_branch.remote"].should == 'origin'
      gl.config["branch.test_branch.merge"].should == 'refs/heads/master'

      gl.fetch
      gl.branches.parking.should be_nil
      new_branch.sha.should == gl.branches['origin/master'].sha
    end

  end

  it 'should use "integration_branch" instead of "remote_master_branch"' do
    change_file_and_commit('a', '')

    new_branch = gitprocess.runner

    new_branch.name.should == 'test_branch'
  end

  it 'should bring new/uncommitted changes on _parking_ over to the new branch' do
    gitlib.branch('origin/master', :base_branch => 'master')
    gitlib.checkout('_parking_', :new_branch => 'master')
    change_file_and_commit('a', '')
    change_file_and_add('b', '')
    change_file('c', '')

    new_branch = gitprocess.runner

    new_branch.name.should == 'test_branch'
    Dir.chdir(gitlib.workdir) do |_|
      File.exists?('a').should be true
      File.exists?('b').should be true
      File.exists?('c').should be true
    end

    gitlib.branches.parking.should be_nil
  end

end


text:
module Bunto
  class Converter < Plugin
    # Public: Get or set the highlighter prefix. When an argument is specified,
    # the prefix will be set. If no argument is specified, the current prefix
    # will be returned.
    #
    # highlighter_prefix - The String prefix (default: nil).
    #
    # Returns the String prefix.
    def self.highlighter_prefix(highlighter_prefix = nil)
      if !defined?(@highlighter_prefix) || !highlighter_prefix.nil?
        @highlighter_prefix = highlighter_prefix
      end
      @highlighter_prefix
    end

    # Public: Get or set the highlighter suffix. When an argument is specified,
    # the suffix will be set. If no argument is specified, the current suffix
    # will be returned.
    #
    # highlighter_suffix - The String suffix (default: nil).
    #
    # Returns the String suffix.
    def self.highlighter_suffix(highlighter_suffix = nil)
      if !defined?(@highlighter_suffix) || !highlighter_suffix.nil?
        @highlighter_suffix = highlighter_suffix
      end
      @highlighter_suffix
    end

    # Initialize the converter.
    #
    # Returns an initialized Converter.
    def initialize(config = {})
      @config = config
    end

    # Get the highlighter prefix.
    #
    # Returns the String prefix.
    def highlighter_prefix
      self.class.highlighter_prefix
    end

    # Get the highlighter suffix.
    #
    # Returns the String suffix.
    def highlighter_suffix
      self.class.highlighter_suffix
    end
  end
end


text:
CKEDITOR.plugins.setLang("specialchar", "fa", {
    euro: "نشان یورو",
    lsquo: "علامت نقل قول تکی چپ",
    rsquo: "علامت نقل قول تکی راست",
    ldquo: "علامت دوتایی نقل قول چپ",
    rdquo: "علامت دوتایی نقل قول راست",
    ndash: "خط تیره En",
    mdash: "خط تیره Em",
    iexcl: "علامت گذاری به عنوان علامت تعجب وارونه",
    cent: "نشان سنت",
    pound: "نشان پوند",
    curren: "نشان ارز",
    yen: "نشان ین",
    brvbar: "نوار شکسته",
    sect: "نشان بخش",
    uml: "Diaeresis",
    copy: "نشان کپی رایت",
    ordf: "Feminine ordinal indicator",
    laquo: "Left-pointing double angle quotation mark",
    not: "علامت ثبت نشده",
    reg: "علامت ثبت شده",
    macr: "Macron",
    deg: "نشان درجه",
    sup2: "بالانویس دو",
    sup3: "بالانویس سه",
    acute: "لهجه غلیظ",
    micro: "نشان مایکرو",
    para: "Pilcrow sign",
    middot: "نقطه میانی",
    cedil: "Cedilla",
    sup1: "Superscript one",
    ordm: "Masculine ordinal indicator",
    raquo: "نشان زاویه‌دار دوتایی نقل قول راست چین",
    frac14: "Vulgar fraction one quarter",
    frac12: "Vulgar fraction one half",
    frac34: "Vulgar fraction three quarters",
    iquest: "Inverted question mark",
    Agrave: "Latin capital letter A with grave accent",
    Aacute: "Latin capital letter A with acute accent",
    Acirc: "Latin capital letter A with circumflex",
    Atilde: "Latin capital letter A with tilde",
    Auml: "Latin capital letter A with diaeresis",
    Aring: "Latin capital letter A with ring above",
    AElig: "Latin Capital letter Æ",
    Ccedil: "Latin capital letter C with cedilla",
    Egrave: "Latin capital letter E with grave accent",
    Eacute: "Latin capital letter E with acute accent",
    Ecirc: "Latin capital letter E with circumflex",
    Euml: "Latin capital letter E with diaeresis",
    Igrave: "Latin capital letter I with grave accent",
    Iacute: "Latin capital letter I with acute accent",
    Icirc: "Latin capital letter I with circumflex",
    Iuml: "Latin capital letter I with diaeresis",
    ETH: "Latin capital letter Eth",
    Ntilde: "Latin capital letter N with tilde",
    Ograve: "Latin capital letter O with grave accent",
    Oacute: "Latin capital letter O with acute accent",
    Ocirc: "Latin capital letter O with circumflex",
    Otilde: "Latin capital letter O with tilde",
    Ouml: "Latin capital letter O with diaeresis",
    times: "Multiplication sign",
    Oslash: "Latin capital letter O with stroke",
    Ugrave: "Latin capital letter U with grave accent",
    Uacute: "Latin capital letter U with acute accent",
    Ucirc: "Latin capital letter U with circumflex",
    Uuml: "Latin capital letter U with diaeresis",
    Yacute: "Latin capital letter Y with acute accent",
    THORN: "Latin capital letter Thorn",
    szlig: "Latin small letter sharp s",
    agrave: "Latin small letter a with grave accent",
    aacute: "Latin small letter a with acute accent",
    acirc: "Latin small letter a with circumflex",
    atilde: "Latin small letter a with tilde",
    auml: "Latin small letter a with diaeresis",
    aring: "Latin small letter a with ring above",
    aelig: "Latin small letter æ",
    ccedil: "Latin small letter c with cedilla",
    egrave: "Latin small letter e with grave accent",
    eacute: "Latin small letter e with acute accent",
    ecirc: "Latin small letter e with circumflex",
    euml: "Latin small letter e with diaeresis",
    igrave: "Latin small letter i with grave accent",
    iacute: "Latin small letter i with acute accent",
    icirc: "Latin small letter i with circumflex",
    iuml: "Latin small letter i with diaeresis",
    eth: "Latin small letter eth",
    ntilde: "Latin small letter n with tilde",
    ograve: "Latin small letter o with grave accent",
    oacute: "Latin small letter o with acute accent",
    ocirc: "Latin small letter o with circumflex",
    otilde: "Latin small letter o with tilde",
    ouml: "Latin small letter o with diaeresis",
    divide: "Division sign",
    oslash: "Latin small letter o with stroke",
    ugrave: "Latin small letter u with grave accent",
    uacute: "Latin small letter u with acute accent",
    ucirc: "Latin small letter u with circumflex",
    uuml: "Latin small letter u with diaeresis",
    yacute: "Latin small letter y with acute accent",
    thorn: "Latin small letter thorn",
    yuml: "Latin small letter y with diaeresis",
    OElig: "Latin capital ligature OE",
    oelig: "Latin small ligature oe",
    372: "Latin capital letter W with circumflex",
    374: "Latin capital letter Y with circumflex",
    373: "Latin small letter w with circumflex",
    375: "Latin small letter y with circumflex",
    sbquo: "Single low-9 quotation mark",
    8219: "Single high-reversed-9 quotation mark",
    bdquo: "Double low-9 quotation mark",
    hellip: "Horizontal ellipsis",
    trade: "Trade mark sign",
    9658: "Black right-pointing pointer",
    bull: "Bullet",
    rarr: "Rightwards arrow",
    rArr: "Rightwards double arrow",
    hArr: "جهت‌نمای دوتایی چپ به راست",
    diams: "Black diamond suit",
    asymp: "تقریبا برابر با"
});


text:
const Gadget = require('mongoose').model('Gadget')
const Comment = require('mongoose').model('Comment')
function validateCommentForm (payload) {
  const errors = {}
  let isFormValid = true
  let message = ''
  if (!payload ||
  typeof payload.content !== 'string' ||
  payload.content.length < 10) {
    isFormValid = false
    errors.content = 'Comment message must be at least 10 symbols.'
  }

  return {
    success: isFormValid,
    message,
    errors
  }
}
module.exports = {
  create: (req, res) => {
    const commentBody = req.body
    const commentAuthor = req.user
    const gadgetid = req.params.id
    Gadget
      .findById(gadgetid)
      .then(gadget => {
        if (!gadget) {
          return res.status(200).json({
            success: false,
            message: 'Gadget does not exists!'
          })
        }
        const validationResult = validateCommentForm(commentBody)
        if (!validationResult.success) {
          return res.status(200).json({
            success: false,
            message: validationResult.message,
            errors: validationResult.errors
          })
        }
        Comment.create({
          content: commentBody.content,
          author: commentAuthor.firstName,
          gadgetId: gadget._id,
          userId: commentAuthor._id
        })
        .then(comment => {
          gadget.comments.push(comment)
          gadget.save().then(() => {
            res.status(200).json({
              success: true,
              message: 'Comment added successfully.',
              comment
            })
          }).catch((err) => {
            res.status(200).json({
              success: false,
              errors: err
            })
          })
        })
      }).catch(() => {
        res.status(200).json({
          success: false,
          message: 'Content is required.',
          errors: 'Content is required.'
        })
      })
  },
  deleteGet (req, res) {
    const commentId = req.params.id
    Comment
    .findById(commentId)
    .then(comment => {
      if (!comment) {
        return res.status(200).json({
          success: false,
          message: 'Comment does not exists!'
        })
      }
      res.status(200).json({
        success: true,
        message: 'Comment fetched',
        comment
      })
    })
    .catch(() => {
      res.status(200).json({
        success: false,
        message: 'Content is required.',
        errors: 'Content is required.'
      })
    })
  },
  deletePost (req, res) {
    const commentId = req.params.id
    Comment
    .findByIdAndRemove(commentId)
    .then(deletedComment => {
      if (!deletedComment) {
        return res.status(200).json({
          success: false,
          message: 'Comment does not exists!'
        })
      }
      res.status(200).json({
        success: true,
        message: 'Comment deleted successfully',
        deletedComment
      })
    }).catch(err => {
      console.log(err)
      res.status(200).json({
        success: false,
        message: '',
        errors: '' // TODO: change message and error
      })
    })
  },
  editGet (req, res) {
    const commentId = req.params.id
    Comment
      .findById(commentId)
      .then(comment => {
        if (!comment) {
          return res.status(200).json({
            success: false,
            message: 'Comment does not exists!'
          })
        }
        res.status(200).json({
          success: true,
          comment
        })
      }).catch(err => {
        console.log(err)
        res.status(200).json({
          success: false,
          message: '',
          errors: '' // TODO: change message and error
        })
      })
  },
  editPost (req, res) {
    const commentId = req.params.id
    const commentBody = req.body
    const validationResult = validateCommentForm(commentBody)
    if (!validationResult.success) {
      return res.status(200).json({
        success: false,
        message: validationResult.message,
        errors: validationResult.errors
      })
    }
    const commentContent = commentBody.content
    Comment
      .findByIdAndUpdate(commentId, {
        $set: {
          content: commentContent
        }
      }).then(editedComment => {
        return res.status(200).json({
          success: true,
          message: 'Comment edited successfully.',
          editedComment
        })
      }).catch(err => {
        console.log(err)
        res.status(200).json({
          success: false,
          message: '',
          errors: '' // TODO: change message and error
        })
      })
  }
}


text:
import styles from './Btn.css';

import React, { Component, PropTypes } from 'react';

export default class Btn extends Component {
  render() {
    const {
      href,
      type,
      variant,
      fullWidth,
      className,
      disabled,
      onClick,
      children,
      active,
      cta,
    } = this.props;

    const classNames = [
      styles.root,
      styles[type],
      styles[variant],
      variant ? styles[variant] : null,
      fullWidth ? styles.fullWidth : null,
      active ? styles.active : null,
      cta ? styles.cta : null,
      className,
    ].join(' ');

    return (
      href ?
      {children}
      :
      <button onClick={onClick} disabled={disabled} className={classNames}>
        {children}
      </button>
    );
  }
}

Btn.propTypes = {
  type: PropTypes.oneOf([
    'primary',
    'secondary',
    'danger',
    'white',
  ]),
  variant: PropTypes.oneOf([
    'hollow',
    'clean',
  ]),

  onClick: PropTypes.func,
  href: PropTypes.string,
  disabled: PropTypes.bool,

  children: PropTypes.any,
  fullWidth: PropTypes.bool,
  className: PropTypes.string,
  active: PropTypes.bool,
  cta: PropTypes.bool,
};


text:
package org.finos.waltz.web.endpoints.api;

import org.finos.waltz.service.changelog.ChangeLogService;
import org.finos.waltz.web.endpoints.Endpoint;
import org.finos.waltz.model.EntityKind;
import org.finos.waltz.model.EntityReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spark.Request;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Optional;

import static org.finos.waltz.common.DateTimeUtilities.toSqlDate;
import static org.finos.waltz.web.WebUtilities.*;
import static org.finos.waltz.web.endpoints.EndpointUtilities.getForList;
import static org.finos.waltz.web.endpoints.EndpointUtilities.postForList;
import static org.finos.waltz.common.Checks.checkNotNull;

@Service
public class ChangeLogEndpoint implements Endpoint {

    private static final String BASE_URL = mkPath("api", "change-log");

    private final ChangeLogService service;

    @Autowired
    public ChangeLogEndpoint(ChangeLogService changeLogService) {
        checkNotNull(changeLogService, "changeLogService must not be null");
        this.service = changeLogService;
    }

    @Override
    public void register() {

        getForList(
                mkPath(BASE_URL, "user", ":userId"),
                (request, response) -> service.findByUser(request.params("userId"), getLimit(request)));

        postForList(
                mkPath(BASE_URL, "summaries", ":kind"),
                (request, response) -> service.findCountByDateForParentKindBySelector(
                        getKind(request),
                        readIdSelectionOptionsFromBody(request),
                        getLimit(request)));

        getForList(
                mkPath(BASE_URL, ":kind", ":id"),
                (request, response) -> {
                    EntityReference ref = getEntityReference(request);
                    Optional<java.util.Date> dateParam = getDateParam(request);
                    Optional<Integer> limitParam = getLimit(request);

                    if (ref.kind() == EntityKind.PERSON) {
                        return service.findByPersonReference(ref, dateParam, limitParam);
                    } else {
                        return service.findByParentReference(ref, dateParam, limitParam);
                    }
                });

        getForList(
                mkPath(BASE_URL, ":kind", ":id", "date-range"),
                (request, response) -> {
                    EntityReference ref = getEntityReference(request);
                    java.sql.Date startDate = getStartDate(request);
                    java.sql.Date endDate = getEndDate(request);
                    Optional<Integer> limitParam = getLimit(request);

                    if (ref.kind() == EntityKind.PERSON) {
                        return service.findByPersonReferenceForDateRange(ref, startDate, endDate, limitParam);
                    } else {
                        return service.findByParentReferenceForDateRange(ref, startDate, endDate, limitParam);
                    }
                });

        getForList(
                mkPath(BASE_URL, ":kind", ":id", "unattested"),
                (request, response) -> {
                    EntityReference ref = getEntityReference(request);
                    return service.findUnattestedChanges(ref);
                });

    }

    private java.sql.Date getStartDate(Request request) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return toSqlDate(formatter.parse(request.queryParams("startDate")));
    }

    private java.sql.Date getEndDate(Request request) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return toSqlDate(formatter.parse(request.queryParams("endDate")));
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace SimpleCoreApi.Controllers
{
    [Route("api/[controller]")]
    public class UsersController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        [HttpGet]
        public IActionResult Get()
        {
            return Ok(db.Users);
        }

        [HttpGet("{id}")]
        public User Get(int id)
        {
            return db.Users.SingleOrDefault(x => x.Id == id);
        }

        [HttpPost]
        public void Post([FromBody]User user)
        {
            db.Users.Add(user);
            db.SaveChanges();
        }

        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            var user = db.Users.SingleOrDefault(x => x.Id == id);
            if (true)
            {
                db.Users.Remove(user);
                db.SaveChanges();
            }
        }
    }
}


text:
import unittest
import thread
import time
import BaseHTTPServer

from tempfile import mkdtemp
import shutil

from rdflib.term import URIRef
from rdflib.namespace import RDF
from rdflib.graph import Graph
from rdflib.py3compat import b

import rdflib.plugin

class GraphTestCase(unittest.TestCase):
    store_name = 'default'
    tmppath = None

    def setUp(self):
        self.graph = Graph(store=self.store_name)
        self.tmppath = mkdtemp()
        self.graph.open(self.tmppath)

        self.michel = URIRef(u'michel')
        self.tarek = URIRef(u'tarek')
        self.bob = URIRef(u'bob')
        self.likes = URIRef(u'likes')
        self.hates = URIRef(u'hates')
        self.pizza = URIRef(u'pizza')
        self.cheese = URIRef(u'cheese')

    def tearDown(self):
        self.graph.close()
        shutil.rmtree(self.tmppath)

    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        self.graph.add((tarek, likes, pizza))
        self.graph.add((tarek, likes, cheese))
        self.graph.add((michel, likes, pizza))
        self.graph.add((michel, likes, cheese))
        self.graph.add((bob, likes, cheese))
        self.graph.add((bob, hates, pizza))
        self.graph.add((bob, hates, michel)) # gasp!

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        self.graph.remove((tarek, likes, pizza))
        self.graph.remove((tarek, likes, cheese))
        self.graph.remove((michel, likes, pizza))
        self.graph.remove((michel, likes, cheese))
        self.graph.remove((bob, likes, cheese))
        self.graph.remove((bob, hates, pizza))
        self.graph.remove((bob, hates, michel)) # gasp!

    def testAdd(self):
        self.addStuff()

    def testRemove(self):
        self.addStuff()
        self.removeStuff()

    def testTriples(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        asserte = self.assertEquals
        triples = self.graph.triples
        Any = None

        self.addStuff()

        # unbound subjects
        asserte(len(list(triples((Any, likes, pizza)))), 2)
        asserte(len(list(triples((Any, hates, pizza)))), 1)
        asserte(len(list(triples((Any, likes, cheese)))), 3)
        asserte(len(list(triples((Any, hates, cheese)))), 0)

        # unbound objects
        asserte(len(list(triples((michel, likes, Any)))), 2)
        asserte(len(list(triples((tarek, likes, Any)))), 2)
        asserte(len(list(triples((bob, hates, Any)))), 2)
        asserte(len(list(triples((bob, likes, Any)))), 1)

        # unbound predicates
        asserte(len(list(triples((michel, Any, cheese)))), 1)
        asserte(len(list(triples((tarek, Any, cheese)))), 1)
        asserte(len(list(triples((bob, Any, pizza)))), 1)
        asserte(len(list(triples((bob, Any, michel)))), 1)

        # unbound subject, objects
        asserte(len(list(triples((Any, hates, Any)))), 2)
        asserte(len(list(triples((Any, likes, Any)))), 5)

        # unbound predicates, objects
        asserte(len(list(triples((michel, Any, Any)))), 2)
        asserte(len(list(triples((bob, Any, Any)))), 3)
        asserte(len(list(triples((tarek, Any, Any)))), 2)

        # unbound subjects, predicates
        asserte(len(list(triples((Any, Any, pizza)))), 3)
        asserte(len(list(triples((Any, Any, cheese)))), 3)
        asserte(len(list(triples((Any, Any, michel)))), 1)

        # all unbound
        asserte(len(list(triples((Any, Any, Any)))), 7)
        self.removeStuff()
        asserte(len(list(triples((Any, Any, Any)))), 0)

    def testStatementNode(self):
        graph = self.graph

        from rdflib.term import Statement
        c = URIRef("http://example.org/foo#c")
        r = URIRef("http://example.org/foo#r")
        s = Statement((self.michel, self.likes, self.pizza), c)
        graph.add((s, RDF.value, r))
        self.assertEquals(r, graph.value(s, RDF.value))
        self.assertEquals(s, graph.value(predicate=RDF.value, object=r))

    def testGraphValue(self):
        from rdflib.graph import GraphValue

        graph = self.graph

        alice = URIRef("alice")
        bob = URIRef("bob")
        pizza = URIRef("pizza")
        cheese = URIRef("cheese")

        g1 = Graph()
        g1.add((alice, RDF.value, pizza))
        g1.add((bob, RDF.value, cheese))
        g1.add((bob, RDF.value, pizza))

        g2 = Graph()
        g2.add((bob, RDF.value, pizza))
        g2.add((bob, RDF.value, cheese))
        g2.add((alice, RDF.value, pizza))

        gv1 = GraphValue(store=graph.store, graph=g1)
        gv2 = GraphValue(store=graph.store, graph=g2)
        graph.add((gv1, RDF.value, gv2))
        v = graph.value(gv1)
        #print type(v)
        self.assertEquals(gv2, v)
        #print list(gv2)
        #print gv2.identifier
        graph.remove((gv1, RDF.value, gv2))

    def testConnected(self):
        graph = self.graph
        self.addStuff()
        self.assertEquals(True, graph.connected())

        jeroen = URIRef("jeroen")
        unconnected = URIRef("unconnected")

        graph.add((jeroen,self.likes,unconnected))

        self.assertEquals(False, graph.connected())

    def testSub(self):
        g1=Graph()
        g2=Graph()

        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        g1.add((tarek, likes, pizza))
        g1.add((bob, likes, cheese))

        g2.add((bob, likes, cheese))

        g3=g1-g2

        self.assertEquals(len(g3), 1)
        self.assertEquals((tarek, likes, pizza) in g3, True)
        self.assertEquals((tarek, likes, cheese) in g3, False)

        self.assertEquals((bob, likes, cheese) in g3, False)

        g1-=g2

        self.assertEquals(len(g1), 1)
        self.assertEquals((tarek, likes, pizza) in g1, True)
        self.assertEquals((tarek, likes, cheese) in g1, False)

        self.assertEquals((bob, likes, cheese) in g1, False)

    def testGraphAdd(self):
        g1=Graph()
        g2=Graph()

        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        g1.add((tarek, likes, pizza))

        g2.add((bob, likes, cheese))

        g3=g1+g2

        self.assertEquals(len(g3), 2)
        self.assertEquals((tarek, likes, pizza) in g3, True)
        self.assertEquals((tarek, likes, cheese) in g3, False)

        self.assertEquals((bob, likes, cheese) in g3, True)

        g1+=g2

        self.assertEquals(len(g1), 2)
        self.assertEquals((tarek, likes, pizza) in g1, True)
        self.assertEquals((tarek, likes, cheese) in g1, False)

        self.assertEquals((bob, likes, cheese) in g1, True)

    def testGraphIntersection(self):
        g1=Graph()
        g2=Graph()

        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese

        g1.add((tarek, likes, pizza))
        g1.add((michel, likes, cheese))

        g2.add((bob, likes, cheese))
        g2.add((michel, likes, cheese))

        g3=g1*g2

        self.assertEquals(len(g3), 1)
        self.assertEquals((tarek, likes, pizza) in g3, False)
        self.assertEquals((tarek, likes, cheese) in g3, False)

        self.assertEquals((bob, likes, cheese) in g3, False)

        self.assertEquals((michel, likes, cheese) in g3, True)

        g1*=g2

        self.assertEquals(len(g1), 1)

        self.assertEquals((tarek, likes, pizza) in g1, False)
        self.assertEquals((tarek, likes, cheese) in g1, False)

        self.assertEquals((bob, likes, cheese) in g1, False)

        self.assertEquals((michel, likes, cheese) in g1, True)

    def testFinalNewline(self):
        """
        http://code.google.com/p/rdflib/issues/detail?id=5
        """
        import sys
        import platform
        if getattr(sys, 'pypy_version_info', None) or platform.system() == 'Java':
            from nose import SkipTest
            raise SkipTest(
                'Testing under pypy and Jython2.5 fails to detect that ' + \
                'IOMemory is a context_aware store')

        failed = set()
        for p in rdflib.plugin.plugins(None, rdflib.plugin.Serializer):
            if p.name is not 'nquads':
                v = self.graph.serialize(format=p.name)
                lines = v.split(b("\n"))
                if b("\n") not in v or (lines[-1]!=b('')):
                    failed.add(p.name)
        self.assertEqual(len(failed), 0, "No final newline for formats: '%s'" % failed)

    def testConNeg(self):
        thread.start_new_thread(runHttpServer, tuple())
        # hang on a second while server starts
        time.sleep(1)
        self.graph.parse("http://localhost:12345/foo", format="xml")
        self.graph.parse("http://localhost:12345/foo", format="n3")
        self.graph.parse("http://localhost:12345/foo", format="nt")

xmltestdoc="""<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns="http://example.org/"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
>
  <rdf:Description rdf:about="http://example.org/a">
    <b rdf:resource="http://example.org/c"/>
  </rdf:Description>
</rdf:RDF>
"""

n3testdoc="""@prefix : <http://example.org/> .

:a :b :c .
"""

nttestdoc="<http://example.org/a> <http://example.org/b> <http://example.org/c> .\n"

class TestHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):

        self.send_response(200, "OK")
        # fun fun fun parsing accept header.

        acs=self.headers["Accept"].split(",")
        acq=[x.split(";") for x in acs if ";" in x]
        acn=[(x,"q=1") for x in acs if ";" not in x]
        acs=[(x[0], float(x[1].strip()[2:])) for x in acq+acn]
        ac=sorted(acs, key=lambda x: x[1])
        ct=ac[-1]

        if "application/rdf+xml" in ct:
            rct="application/rdf+xml"
            content=xmltestdoc
        elif "text/n3" in ct:
            rct="text/n3"
            content=n3testdoc
        elif "text/plain" in ct:
            rct="text/plain"
            content=nttestdoc

        self.send_header("Content-type",rct)
        self.end_headers()
        self.wfile.write(content.encode('utf-8'))

    def log_message(self, *args):
        pass

def runHttpServer(server_class=BaseHTTPServer.HTTPServer,
        handler_class=TestHTTPHandler):
    """Start a server than can handle 3 requests :)"""
    server_address = ('localhost', 12345)
    httpd = server_class(server_address, handler_class)

    httpd.handle_request()
    httpd.handle_request()
    httpd.handle_request()

if __name__ == '__main__':
    unittest.main()


text:
package org.xml3d.converter.x3d;

import java.io.*;

import javax.xml.transform.TransformerException;

import org.xml3d.converter.Converter;

/**
 * X3DConverter converts X3D files to XML3D or XML3D embedded in XHTML by means
 * of XSLT transformations. The outcome is embedded in
 * HTML which allows to regard instantly the result with
 * a XML3D enabled browser. In spite of this, the result
 * is stored in a .xml file per default. However, other
 * filenames can be enforced in {@link X3DConverter#run(String, File)}.
 *
 * @author Kristian Sons
 * @author Benjamin Friedrich
 * @version 1.0  08/2010
 */
public final class X3DConverter extends Converter
{
	private static final String XSL_FILE = "x3d2xml3d_m4.xsl";

	/**
	 * Constructor of X3DConverter
	 */
	public X3DConverter()
	{
		super(XSL_FILE);
	}

	/**
	 * Converts the given X3D file to XML3D or to XML3D embedded
	 * in XHTML. In doing so, the name of the transformed file is
	 * the name of the input file with the corresponding suffix
	 * ".xml3d" or ".xhtml" instead of ".x3d".
	 *
	 * @param  x3dFile
	 * 				file to be transformed to xml3d
	 * @param  inHTML
	 * 				indicates whether the output is pure XML3D or
	 * 				XML3D embedded in XHTML
	 *
	 * @throws TransformerException
	 * 				if a problem during the XSLT transformation occurs
	 */
	public void run(final String inputFile, final boolean inHTML) throws TransformerException
	{
		final String outputFile = inputFile.replaceFirst(".x3d$", inHTML ? ".xhtml": ".xml3d");
		this.run(inputFile, new File(outputFile), inHTML);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @throws IllegalArgumentException
	 * 				if the X3D file does not end with suffix .x3d
	 */
	@Override
	protected void checkInputFile(final String inputFile)
	{
		super.checkInputFile(inputFile);

		if(! inputFile.endsWith(".x3d"))
		{
			throw new IllegalArgumentException("Invalid suffix of the X3D input file " +
											   inputFile +
											   ". Expected: .x3d");
		}
	}
}


text:
require 'uri'
require 'net/http'
require 'json'
require 'openssl'
require 'base64'

env_sdk_failure_notif_endpoint = ARGV[0]
env_sdk_failure_notif_endpoint_hmac_key = ARGV[1]
github_run_id = ARGV[2]

if !env_sdk_failure_notif_endpoint || !env_sdk_failure_notif_endpoint_hmac_key
  puts "Three environment variables required: `SDK_FAILURE_NOTIFICATION_ENDPOINT` and `SDK_FAILURE_NOTIFICATION_ENDPOINT_HMAC_KEY`"
  exit 102
end

if !github_run_id
  puts "github_run_id not found"
  exit 102
end

uri = URI(env_sdk_failure_notif_endpoint)
hmac_key = Base64.decode64(env_sdk_failure_notif_endpoint_hmac_key)

http = Net::HTTP.new(uri.host, uri.port).tap do |http|
  http.use_ssl = true
end
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')

params = {
  project: "RUN_MOBILESDK",
}

params[:summary] = "stripe-android E2E test failed"
params[:description] = "Please ACK this ticket and investigate the failure. See https://github.com/stripe/stripe-android/actions/runs/#{github_run_id}"

req.body = params.to_json

# Auth
digest = OpenSSL::Digest.new('sha256')
header_data = OpenSSL::HMAC.digest(digest, hmac_key, req.body)
header_data_64 = Base64.strict_encode64(header_data)
req.add_field 'X-TM-Signature', header_data_64

res = http.request(req)


text:
/* This is script-generated code (for the most part).  */
/* See dataObjCopy.h for a description of this API call.*/

#include "dataObjCopy.h"
#include "rodsLog.h"
#include "objMetaOpr.h"
#include "collection.h"
#include "specColl.h"
#include "dataObjOpen.h"
#include "dataObjCreate.h"
#include "dataObjRepl.h"
#include "regDataObj.h"
#include "rsGlobalExtern.h"
#include "rcGlobalExtern.h"
#include "getRemoteZoneResc.h"

int
rsDataObjCopy250 (rsComm_t *rsComm, dataObjCopyInp_t *dataObjCopyInp,
transStat_t **transStat)
{
    int status;
    transferStat_t *transferStat = NULL;

    status = rsDataObjCopy (rsComm, dataObjCopyInp, &transferStat);

    if (transStat != NULL && status >= 0 && transferStat != NULL) {
        *transStat = (transStat_t *) malloc (sizeof (transStat_t));
        (*transStat)->numThreads = transferStat->numThreads;
        (*transStat)->bytesWritten = transferStat->bytesWritten;
        free (transferStat);
    }
    return status;
}

int
rsDataObjCopy (rsComm_t *rsComm, dataObjCopyInp_t *dataObjCopyInp,
transferStat_t **transStat)
{
    dataObjInp_t *srcDataObjInp, *destDataObjInp;
    int srcL1descInx, destL1descInx;
    int status;
    int existFlag;
    uint createMode;
    int remoteFlag;
    rodsServerHost_t *rodsServerHost;
    specCollCache_t *specCollCache = NULL;

    srcDataObjInp = &dataObjCopyInp->srcDataObjInp;
    destDataObjInp = &dataObjCopyInp->destDataObjInp;

    resolveLinkedPath (rsComm, srcDataObjInp->objPath, &specCollCache,
      &srcDataObjInp->condInput);
    resolveLinkedPath (rsComm, destDataObjInp->objPath, &specCollCache,
      &destDataObjInp->condInput);
    remoteFlag = getAndConnRemoteZoneForCopy (rsComm, dataObjCopyInp,
      &rodsServerHost);

    if (remoteFlag < 0) {
        return (remoteFlag);
    } else if (remoteFlag == REMOTE_HOST) {
        status = _rcDataObjCopy (rodsServerHost->conn, dataObjCopyInp,
	  transStat);
	return status;
    }

#if 0
    *transStat = malloc (sizeof (transferStat_t));
    memset (*transStat, 0, sizeof (transferStat_t));
#endif

    if (strcmp (srcDataObjInp->objPath, destDataObjInp->objPath) == 0) {
        rodsLog (LOG_ERROR,
          "rsDataObjCopy: same src and dest objPath %s not allowed",
	  srcDataObjInp->objPath);
	return (USER_INPUT_PATH_ERR);
    }

    addKeyVal (&srcDataObjInp->condInput, PHYOPEN_BY_SIZE_KW, "");
    srcL1descInx = rsDataObjOpen (rsComm, srcDataObjInp);

    if (srcL1descInx < 0)
        return srcL1descInx;

    /* have to set L1desc[srcL1descInx].dataSize because open set this to -1 */
    destDataObjInp->dataSize = L1desc[srcL1descInx].dataSize =
     L1desc[srcL1descInx].dataObjInfo->dataSize;

    createMode = atoi (L1desc[srcL1descInx].dataObjInfo->dataMode);
    if (createMode >= 0100)
	destDataObjInp->createMode = createMode;
    L1desc[srcL1descInx].oprType = COPY_SRC;

    if (L1desc[srcL1descInx].l3descInx <= 2) {
        /* dataSingleBuf */
        addKeyVal (&destDataObjInp->condInput, NO_OPEN_FLAG_KW, "");
    }

#ifdef FILESYSTEM_META
    /* copy file metadata if the source object has it */
    copyFilesystemMetadata(&(L1desc[srcL1descInx].dataObjInfo->condInput),
                            &destDataObjInp->condInput);
#endif

    destL1descInx = rsDataObjCreate (rsComm, destDataObjInp);
    if (destL1descInx == CAT_UNKNOWN_COLLECTION) {
        /* collection does not exist. make one */
        char parColl[MAX_NAME_LEN], child[MAX_NAME_LEN];
        splitPathByKey (destDataObjInp->objPath, parColl, child, '/');
        rsMkCollR (rsComm, "/", parColl);
	destL1descInx = rsDataObjCreate (rsComm, destDataObjInp);
    }

    if (destL1descInx < 0) {
	return (destL1descInx);
    }

    if (L1desc[destL1descInx].replStatus == NEWLY_CREATED_COPY) {
	existFlag = 0;
    } else {
	existFlag = 1;
    }

    L1desc[destL1descInx].oprType = COPY_DEST;

    L1desc[destL1descInx].srcL1descInx = srcL1descInx;

    rstrcpy (L1desc[destL1descInx].dataObjInfo->dataType,

    L1desc[srcL1descInx].dataObjInfo->dataType, NAME_LEN);
    /* set dataSize for verification in _rsDataObjClose */

    L1desc[destL1descInx].dataSize =
      L1desc[srcL1descInx].dataObjInfo->dataSize;

#if 0
    (*transStat)->bytesWritten = L1desc[srcL1descInx].dataObjInfo->dataSize;
#endif

    status = _rsDataObjCopy (rsComm, destL1descInx, existFlag, transStat);

#if 0
    if (status >= 0) {
        (*transStat)->numThreads = destDataObjInp->numThreads;
    }
#endif

    return (status);
}

int
_rsDataObjCopy (rsComm_t *rsComm, int destL1descInx, int existFlag,
transferStat_t **transStat)
{
    dataObjInp_t *srcDataObjInp, *destDataObjInp;
    openedDataObjInp_t dataObjCloseInp;
    dataObjInfo_t *srcDataObjInfo, *destDataObjInfo;
    int srcL1descInx;
    int status, status2;
    char *destRescName, *srcRescName;

    destDataObjInp = L1desc[destL1descInx].dataObjInp;
    destDataObjInfo = L1desc[destL1descInx].dataObjInfo;
    srcL1descInx = L1desc[destL1descInx].srcL1descInx;

    srcDataObjInp = L1desc[srcL1descInx].dataObjInp;
    srcDataObjInfo = L1desc[srcL1descInx].dataObjInfo;

    // JMC mods
    // cppcheck will still complain of redundant check(s), safe to ignore
    if (destDataObjInp == NULL) {
        rodsLog( LOG_ERROR, "_rsDataObjCopy: :: destDataObjInp is NULL" );
		return SYS_INTERNAL_NULL_INPUT_ERR;
	}
    if (destDataObjInfo == NULL) {
        rodsLog( LOG_ERROR, "_rsDataObjCopy: :: destDataObjInfo is NULL" );
		return SYS_INTERNAL_NULL_INPUT_ERR;
	}
    if (srcDataObjInp == NULL) {
        rodsLog( LOG_ERROR, "_rsDataObjCopy: :: srcDataObjInp is NULL" );
		return SYS_INTERNAL_NULL_INPUT_ERR;
	}
    if (srcDataObjInfo == NULL) {
        rodsLog( LOG_ERROR, "_rsDataObjCopy: :: srcDataObjInfo is NULL" );
		return SYS_INTERNAL_NULL_INPUT_ERR;
	}
    // end JMC mods

    if (L1desc[srcL1descInx].l3descInx <= 2) {
        /* no physical file was opened */
        status = l3DataCopySingleBuf (rsComm, destL1descInx);
	/* has not been registered yet because of NO_OPEN_FLAG_KW */
	if (status >= 0 && existFlag == 0 &&
	  destDataObjInfo->specColl == NULL &&
	  L1desc[destL1descInx].remoteZoneHost == NULL) {
	    /* If the dest is in remote zone, register in _rsDataObjClose
	     * there */
            status = svrRegDataObj (rsComm, destDataObjInfo);
	    if (status == CAT_UNKNOWN_COLLECTION) {
		/* collection does not exist. make one */
		char parColl[MAX_NAME_LEN], child[MAX_NAME_LEN];
		splitPathByKey (destDataObjInfo->objPath, parColl, child, '/');
		rsMkCollR (rsComm, "/", parColl);
		status = svrRegDataObj (rsComm, destDataObjInfo);
	    }
	    if (status < 0) {
                rodsLog (LOG_NOTICE,
                  "_rsDataObjCopy: svrRegDataObj for %s failed, status = %d",
                  destDataObjInfo->objPath, status);
                return (status);
	    }
	}
    } else {
        if (destDataObjInfo != NULL && destDataObjInfo->rescInfo != NULL)
            destRescName = destDataObjInfo->rescInfo->rescName;
        else
            destRescName = NULL;

        if (srcDataObjInfo != NULL && srcDataObjInfo->rescInfo != NULL)
            srcRescName = srcDataObjInfo->rescInfo->rescName;
        else
            srcRescName = NULL;

        destDataObjInp->numThreads = getNumThreads (rsComm,
	 srcDataObjInfo->dataSize, destDataObjInp->numThreads, NULL,
	 destRescName, srcRescName);
	srcDataObjInp->numThreads = destDataObjInp->numThreads;
#if 0
        /* XXXX can't handle numThreads == 0 && size > MAX_SZ_FOR_SINGLE_BUF */
        if (destDataObjInp->numThreads == 0 &&
          srcDataObjInfo->dataSize > MAX_SZ_FOR_SINGLE_BUF) {
	    destDataObjInp->numThreads = 1;
        }
#endif
        status = dataObjCopy (rsComm, destL1descInx);
    }

    memset (&dataObjCloseInp, 0, sizeof (dataObjCloseInp));

    dataObjCloseInp.l1descInx = destL1descInx;
    if (status >= 0) {
        *transStat = (transferStat_t*)malloc (sizeof (transferStat_t));
        memset (*transStat, 0, sizeof (transferStat_t));
        (*transStat)->bytesWritten = srcDataObjInfo->dataSize;
        (*transStat)->numThreads = destDataObjInp->numThreads;
        dataObjCloseInp.bytesWritten = srcDataObjInfo->dataSize;
    }

    status2 = rsDataObjClose (rsComm, &dataObjCloseInp);

    if (status) return (status);
    return(status2);
}


text:
'use strict';

// Regex to find dimensions and extract width and multiplier (where included)
// Resulting array contains [full match, width, multiplier]
const dimRegex = /\.w([0-9]+)\.h(?:[0-9]+)\.(?:([1-2])x\.)?/;

/**
 * Extract the width of a mediaplay image given the image URL.
 * @param {string} url
 * @returns {Object} extracted width
 */
module.exports = function (url) {
  var matches,
    multiplier = 1;

  if (url && url !== '') {
    matches = url.match(dimRegex);

    if (matches && matches.length) {
      // Multiplier
      if (matches[2]) {
        multiplier = parseInt(matches[2], 10);
      }

      // Width * multiplier
      return parseInt(matches[1], 10) * multiplier;
    }
  }

  return null;
};

module.exports.example = {
  code: '{{ extractImgWidth feedImgUrl }}',
  result: '1420'
};


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.diirt</groupId>
        <artifactId>pvmanager-all</artifactId>
        <version>3.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>datasource-extra</artifactId>
    <name>org.diirt.datasource.extra</name>
    <description>Temporary home for experimental features.</description>
    <dependencies>
      <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>datasource-test</artifactId>
        <version>${project.version}</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>datasource-vtype</artifactId>
        <version>${project.version}</version>
      </dependency>
    </dependencies>
</project>


text:
package cz.polankam.jjcron.common;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * General implementation of {@link CrontabTimeUnit} interface which should be
 * sufficient for most of time unit in crontab aka. second, minutes, hours, etc.
 * It includes minimal and maximal value which can unit have and also period
 * with which specified unit operates.
 *
 * @author Neloop
 */
public class CrontabTimeGeneralUnit implements CrontabTimeUnit, Serializable {

    /**
     * Minimal value which can be in single value, list of values or in period.
     */
    protected final int minValue;
    /**
     * Maximal value which can be in single value, list of values or in period.
     */
    protected final int maxValue;
    /**
     * Period with which this unit operates.
     */
    protected final int period;

    /**
     * Textual description of unit extracted from column in crontab.
     */
    protected final String unitStr;
    /**
     * Structure parsed and constructed from unitStr. Which stores
     * all needed info about time unit.
     */
    protected final CrontabTimeValue unit;

    /**
     * Cached information about value change in last delay computation.
     * Accessible through isChanged() method.
     */
    protected boolean valueChanged;

    /**
     * Initialization of this structure, unit parsing and checking is performed.
     *
     * @param unit textual description of unit
     * @param minValue minimal value of unit
     * @param maxValue maximal value of unit
     * @param period period of unit
     * @param parser implementation of parser which is able to extract needed
     * information from given unit
     * @throws FormatException if unit cannot be parsed
     */
    public CrontabTimeGeneralUnit(String unit, int minValue, int maxValue,
            int period, CrontabTimeValueParser parser)
            throws FormatException {
        this.unitStr = unit;
        this.minValue = minValue;
        this.maxValue = maxValue;
        this.period = period;
        valueChanged = false;

        this.unit = parser.parse(unitStr);

        checkValue();
    }

    /**
     * Check if given value is valid according to minimal and maximal values.
     *
     * @param value checked value
     * @throws FormatException if value is not valid
     */
    private void isValueValid(int value) throws FormatException {
        if (value < minValue || value > maxValue) {
            throw new FormatException(
                    "CrontabTimeUnit value is not valid number");
        }
    }

    /**
     * Check parsed {@link CrontabTimeValue} structure for proper valid values.
     *
     * @throws FormatException if value did not pass check
     */
    private void checkValue() throws FormatException {
        switch (unit.valueType) {
            case ASTERISK:
                // nothing to do here
                break;
            case PERIOD:
                isValueValid(unit.values.get(0));
                if (unit.values.get(0) == 0
                        || period % (unit.values.get(0)) != 0) {
                    throw new FormatException(
                            "GeneralUnit period value is not divisible");
                }
                break;
            case LIST:
                for (Integer number : unit.values) {
                    isValueValid(number);
                }
                break;
        }
    }

    @Override
    public boolean isChanged() {
        return valueChanged;
    }

    @Override
    public int delay(LocalDateTime current, int currentValue,
            boolean previousChanged) {
        int result;
        valueChanged = previousChanged;

        switch (unit.valueType) {
            case PERIOD:
                int remainder = currentValue % unit.values.get(0);
                if (previousChanged && remainder == 0) {
                    result = 0;
                } else {
                    result = unit.values.get(0) - remainder;
                }
                valueChanged = true;
                break;
            case LIST:
                result = period; // minimum from list of values
                for (Integer val : unit.values) {
                    if (previousChanged && currentValue == val) {
                        result = 0;
                    } else {
                        int toMinuteL = period - currentValue;
                        int minTemp = (toMinuteL + val) % period;
                        if (minTemp > 0 && minTemp < result) {
                            result = minTemp;
                        }
                    }
                }
                valueChanged = true;
                break;
            default: // asterisk
                if (previousChanged) {
                    result = 0;
                } else {
                    result = 1;
                }
                valueChanged = true;
                break;
        }

        return result;
    }

    @Override
    public CrontabTimeValue value() {
        return unit;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null || !(other instanceof CrontabTimeGeneralUnit)) {
            return false;
        }

        CrontabTimeGeneralUnit cast = (CrontabTimeGeneralUnit) other;
        return cast.minValue == minValue && cast.maxValue == maxValue
                && cast.period == period && cast.unit.equals(unit);
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 89 * hash + this.minValue;
        hash = 89 * hash + this.maxValue;
        hash = 89 * hash + this.period;
        hash = 89 * hash + Objects.hashCode(this.unit);
        return hash;
    }
}


text:
module.exports.User = require("./user.js")();
module.exports.Link = require("./link.js")();


text:
package config

import (
	"bytes"
	"io/ioutil"
	"os"
	"testing"

	"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
	clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
)

type getClustersTest struct {
	config   clientcmdapi.Config
	expected string
}

func TestGetClusters(t *testing.T) {
	conf := clientcmdapi.Config{
		Clusters: map[string]*clientcmdapi.Cluster{
			"minikube": {Server: "https://192.168.0.99"},
		},
	}
	test := getClustersTest{
		config: conf,
		expected: `NAME
minikube
`,
	}

	test.run(t)
}

func TestGetClustersEmpty(t *testing.T) {
	test := getClustersTest{
		config:   clientcmdapi.Config{},
		expected: "NAME\n",
	}

	test.run(t)
}

func (test getClustersTest) run(t *testing.T) {
	fakeKubeFile, _ := ioutil.TempFile("", "")
	defer os.Remove(fakeKubeFile.Name())
	err := clientcmd.WriteToFile(test.config, fakeKubeFile.Name())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	pathOptions := clientcmd.NewDefaultPathOptions()
	pathOptions.GlobalFile = fakeKubeFile.Name()
	pathOptions.EnvVar = ""
	buf := bytes.NewBuffer([]byte{})
	cmd := NewCmdConfigGetClusters(buf, pathOptions)
	if err := cmd.Execute(); err != nil {
		t.Fatalf("unexpected error executing command: %v", err)
	}
	if len(test.expected) != 0 {
		if buf.String() != test.expected {
			t.Errorf("expected %v, but got %v", test.expected, buf.String())
		}
		return
	}
}


text:
namespace llvm {
  class BitVector;
}

namespace clang {
  class AnalysisDeclContext;
  class CFGBlock;
  class Preprocessor;
}

//===----------------------------------------------------------------------===//
// API.
//===----------------------------------------------------------------------===//

namespace clang {
namespace reachable_code {

/// Classifications of unreachable code.
enum UnreachableKind {
  UK_Return,
  UK_Break,
  UK_Loop_Increment,
  UK_Other
};

class Callback {
  virtual void anchor();
public:
  virtual ~Callback() {}
  virtual void HandleUnreachable(UnreachableKind UK,
                                 SourceLocation L,
                                 SourceRange ConditionVal,
                                 SourceRange R1,
                                 SourceRange R2) = 0;
};

/// ScanReachableFromBlock - Mark all blocks reachable from Start.
/// Returns the total number of blocks that were marked reachable.
unsigned ScanReachableFromBlock(const CFGBlock *Start,
                                llvm::BitVector &Reachable);

void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP,
                         Callback &CB);

}} // end namespace clang::reachable_code

#endif


text:
set -o pipefail
set -o nounset
set -o errexit

: ${DRY_RUN:=true}
XENON_LOCAL_REPO=$(git rev-parse --show-toplevel)

cd $XENON_LOCAL_REPO

if [ "${COMMIT:-}" == "" ]; then
  echo "Must specify COMMIT to create branch and tag from"
  exit 1
else
  echo "Cutting release from:"
fi

if ! git show --shortstat ${COMMIT} 2> /dev/null ; then
  echo "Commit ${COMMIT} not found: either a typo or you should fetch first"
  exit 1
fi
echo

RELEASE_VERSION=$(git show ${COMMIT}:pom.xml | head -10 | grep '<version>' | sed 's/^.*>\(.*\)<.*$/\1/')

if echo ${RELEASE_VERSION} | grep -- '-SNAPSHOT$' > /dev/null; then
  echo "RELEASE_VERSION found in ${COMMIT} must be a release version, found ${RELEASE_VERSION}"
  exit 1
fi

RELEASE_BRANCH_NAME=v${RELEASE_VERSION}
RELEASE_TAG_NAME=${RELEASE_BRANCH_NAME}-release

# create gerrit branch
echo "Creating branch ${RELEASE_BRANCH_NAME}"
if [ "$DRY_RUN" == "true" ]; then
  echo Would execute:
  echo ssh -p 29418 review.ec.eng.vmware.com gerrit create-branch xenon ${RELEASE_BRANCH_NAME} ${COMMIT}
else
  ssh -p 29418 review.ec.eng.vmware.com gerrit create-branch xenon ${RELEASE_BRANCH_NAME} ${COMMIT}
fi

echo
# create annotated tag
echo "Creating tag ${RELEASE_TAG_NAME}"
if [ "$DRY_RUN" == "true" ]; then
  echo Would execute:
  echo git tag -am "Tagging ${RELEASE_BRANCH_NAME}" ${RELEASE_TAG_NAME} ${COMMIT}
  echo git push origin ${RELEASE_TAG_NAME} HEAD:refs/heads/${RELEASE_BRANCH_NAME}
else
  git tag -am "Tagging ${RELEASE_BRANCH_NAME}" ${RELEASE_TAG_NAME} ${COMMIT}
  git push origin ${RELEASE_TAG_NAME} HEAD:refs/heads/${RELEASE_BRANCH_NAME}
fi


text:
package androidx.core.app;

import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX;

import android.app.Activity;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.SparseIntArray;
import android.view.Window;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * This class can be used to record and return data about per-frame durations. It returns those
 * results in an array per metric type, with the results indicating how many samples were
 * recorded for each duration value. The details of the durations data are described in
 * {@link #getMetrics()}.
 *

 * For more information on the various metrics tracked, see the documentation for the
 * FrameMetrics
 *  API added in API 24 as well as the
 * GPU Profiling
 * guide.
 */
public class FrameMetricsAggregator {

    /**
     * The index in the metrics array where the data for {@link #TOTAL_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int TOTAL_INDEX          = 0;
    /**
     * The index in the metrics array where the data for {@link #INPUT_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int INPUT_INDEX          = 1;
    /**
     * The index in the metrics array where the data for {@link #LAYOUT_MEASURE_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int LAYOUT_MEASURE_INDEX = 2;
    /**
     * The index in the metrics array where the data for {@link #DRAW_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int DRAW_INDEX           = 3;
    /**
     * The index in the metrics array where the data for {@link #SYNC_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int SYNC_INDEX           = 4;
    /**
     * The index in the metrics array where the data for {@link #SYNC_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int COMMAND_INDEX        = 5;
    /**
     * The index in the metrics array where the data for {@link #COMMAND_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int SWAP_INDEX           = 6;
    /**
     * The index in the metrics array where the data for {@link #DELAY_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int DELAY_INDEX          = 7;
    /**
     * The index in the metrics array where the data for {@link #ANIMATION_DURATION}
     * is stored.
     * @see #getMetrics()
     */
    public static final int ANIMATION_INDEX      = 8;
    private static final int LAST_INDEX          = 8;

    /**
     * A flag indicating that the metrics should track the total duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int TOTAL_DURATION          = 1 << TOTAL_INDEX;
    /**
     * A flag indicating that the metrics should track the input duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int INPUT_DURATION          = 1 << INPUT_INDEX;
    /**
     * A flag indicating that the metrics should track the layout duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int LAYOUT_MEASURE_DURATION = 1 << LAYOUT_MEASURE_INDEX;
    /**
     * A flag indicating that the metrics should track the draw duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int DRAW_DURATION           = 1 << DRAW_INDEX;
    /**
     * A flag indicating that the metrics should track the sync duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int SYNC_DURATION           = 1 << SYNC_INDEX;
    /**
     * A flag indicating that the metrics should track the command duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int COMMAND_DURATION        = 1 << COMMAND_INDEX;
    /**
     * A flag indicating that the metrics should track the swap duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int SWAP_DURATION           = 1 << SWAP_INDEX;
    /**
     * A flag indicating that the metrics should track the delay duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int DELAY_DURATION          = 1 << DELAY_INDEX;
    /**
     * A flag indicating that the metrics should track the animation duration. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate all of the metrics that should be tracked for that activity.
     */
    public static final int ANIMATION_DURATION      = 1 << ANIMATION_INDEX;
    /**
     * A flag indicating that the metrics should track all durations. This is
     * a shorthand for OR'ing all of the duration flags. This
     * flag may be OR'd with the other flags here when calling {@link #FrameMetricsAggregator(int)}
     * to indicate the metrics that should be tracked for that activity.
     */
    public static final int EVERY_DURATION          = 0x1ff;

    private final FrameMetricsBaseImpl mInstance;

    /** @hide */
    @RestrictTo(LIBRARY_GROUP_PREFIX)
    @Retention(RetentionPolicy.SOURCE)
    @IntDef(
            flag = true,
            value = {
                    TOTAL_DURATION,
                    INPUT_DURATION,
                    LAYOUT_MEASURE_DURATION,
                    DRAW_DURATION,
                    SYNC_DURATION,
                    COMMAND_DURATION,
                    SWAP_DURATION,
                    DELAY_DURATION,
                    ANIMATION_DURATION,
                    EVERY_DURATION
            })
    public @interface MetricType {}

    /**
     * Constructs a FrameMetricsAggregator object that will track {@link #TOTAL_DURATION}
     * metrics. If more fine-grained metrics are needed, use {@link #FrameMetricsAggregator(int)}
     * instead.
     */
    public FrameMetricsAggregator() {
        this(TOTAL_DURATION);
    }

    /**
     * Constructs a FrameMetricsAggregator object that will track the metrics specified bty
     * {@code metricTypeFlags}, which is a value derived by OR'ing together metrics constants
     * such as {@link #TOTAL_DURATION} to specify all metrics that should be tracked. For example,
     * {@code TOTAL_DURATION | DRAW_DURATION} will track both the total and draw durations
     * for every frame.
     *
     * @param metricTypeFlags A bitwise collection of flags indicating which metrics should
     * be recorded.
     */
    public FrameMetricsAggregator(@MetricType int metricTypeFlags) {
        if (Build.VERSION.SDK_INT >= 24) {
            mInstance = new FrameMetricsApi24Impl(metricTypeFlags);
        } else {
            mInstance = new FrameMetricsBaseImpl();
        }
    }

    /**
     * Starts recording frame metrics for the given activity.
     *
     * @param activity The Activity object which will have its metrics measured.
     */
    public void add(@NonNull Activity activity) {
        mInstance.add(activity);
    }

    /**
     * Stops recording metrics for {@code activity} and returns the collected metrics so far.
     * Recording will continue if there are still other activities being tracked. Calling
     * remove() does not reset the metrics array; you must call {@link #reset()} to clear the
     * data.
     *
     * @param activity The Activity to stop tracking metrics for.
     * @return An array whose index refers to the type of metric stored in that item's
     * SparseIntArray object, e.g., data for {@code TOTAL_DURATION} is stored in
     * the {@code [TOTAL_INDEX]} item.
     * @see #getMetrics()
     */
    @Nullable
    public SparseIntArray[] remove(@NonNull Activity activity) {
        return mInstance.remove(activity);
    }

    /**
     * Stops recording metrics for all Activities currently being tracked. Like {@link
     * #remove(Activity)}, this method returns the currently-collected metrics. Calling
     * stop() does not reset the metrics array; you must call {@link #reset()} to clear the
     * data.
     *
     * @return An array whose index refers to the type of metric stored in that item's
     * SparseIntArray object, e.g., data for {@code TOTAL_DURATION} is stored in
     * the {@code [TOTAL_INDEX]} item.
     * @see #remove(Activity)
     * @see #getMetrics()
     */
    @Nullable
    public SparseIntArray[] stop() {
        return mInstance.stop();
    }

    /**
     * Resets the metrics data and returns the currently-collected metrics.
     *
     * @return An array whose index refers to the type of metric stored in that item's
     * SparseIntArray object, e.g., data for {@code TOTAL_DURATION} is stored in
     * the {@code [TOTAL_INDEX]} item.
     * @see #getMetrics()
     */
    @Nullable
    public SparseIntArray[] reset() {
        return mInstance.reset();
    }

    /**
     * Returns the currently-collected metrics in an array of SparseIntArray objects.
     * The index of the array indicates which metric's data is stored in that
     * SparseIntArray object. For example, results for total duration will be in
     * the {@code [TOTAL_INDEX]} item.
     *

     * The return value may be null if no metrics were tracked. This is especially true on releases
     * earlier than API 24, as the FrameMetrics system does not exist on these earlier release.
     * If the return value is not null, any of the objects at a given index in the array
     * may still be null, which indicates that data was not being tracked for that type of metric.
     * For example, if the FrameMetricsAggregator was created with a call to
     * {@code new FrameMetricsAggregator(TOTAL_DURATION | DRAW_DURATION)}, then the SparseIntArray
     * at index {@code INPUT_INDEX} will be null.
     *

     * For a given non-null SparseIntArray, the results stored are the number of samples at
     * each millisecond value (rounded). For example, if a data sample consisted of total
     * durations of 5.1ms, 5.8ms, 6.1ms, and 8.2ms, the SparseIntArray at {@code [TOTAL_DURATION]}
     * would have key-value pairs (5, 1), (6, 2), (8, 1).
     *
     * @return An array whose index refers to the type of metric stored in that item's
     * SparseIntArray object, e.g., data for {@code TOTAL_DURATION} is stored in
     * the {@code [TOTAL_INDEX]} item.
     */
    @Nullable
    public SparseIntArray[] getMetrics() {
        return mInstance.getMetrics();
    }

    /**
     * Base implementation noops everything - there's no data to return on pre-API24 releases.
     */
    private static class FrameMetricsBaseImpl {

        FrameMetricsBaseImpl() {
        }

        public void add(Activity activity) {
        }

        public SparseIntArray[] remove(Activity activity) {
            return null;
        }

        public SparseIntArray[] stop() {
            return null;
        }

        public SparseIntArray[] getMetrics() {
            return null;
        }

        public SparseIntArray[] reset() {
            return null;
        }
    }

    @RequiresApi(24)
    private static class FrameMetricsApi24Impl extends FrameMetricsBaseImpl {

        private static final int NANOS_PER_MS = 1000000;
        // rounding value adds half a millisecond, for rounding to nearest ms
        private static final int NANOS_ROUNDING_VALUE = NANOS_PER_MS / 2;
        int mTrackingFlags;
        SparseIntArray[] mMetrics = new SparseIntArray[LAST_INDEX + 1];
        private final ArrayList<WeakReference<Activity>> mActivities = new ArrayList<>();
        private static HandlerThread sHandlerThread = null;
        private static Handler sHandler = null;

        FrameMetricsApi24Impl(int trackingFlags) {
            mTrackingFlags = trackingFlags;
        }

        Window.OnFrameMetricsAvailableListener mListener =
                new Window.OnFrameMetricsAvailableListener() {
            @Override
            public void onFrameMetricsAvailable(Window window,
                    android.view.FrameMetrics frameMetrics, int dropCountSinceLastInvocation) {
                if ((mTrackingFlags & TOTAL_DURATION) != 0) {
                    addDurationItem(mMetrics[TOTAL_INDEX],
                            frameMetrics.getMetric(android.view.FrameMetrics.TOTAL_DURATION));
                }
                if ((mTrackingFlags & INPUT_DURATION) != 0) {
                    addDurationItem(mMetrics[INPUT_INDEX],
                            frameMetrics.getMetric(
                                    android.view.FrameMetrics.INPUT_HANDLING_DURATION));
                }
                if ((mTrackingFlags & LAYOUT_MEASURE_DURATION) != 0) {
                    addDurationItem(mMetrics[LAYOUT_MEASURE_INDEX],
                            frameMetrics.getMetric(
                                    android.view.FrameMetrics.LAYOUT_MEASURE_DURATION));
                }
                if ((mTrackingFlags & DRAW_DURATION) != 0) {
                    addDurationItem(mMetrics[DRAW_INDEX],
                            frameMetrics.getMetric(android.view.FrameMetrics.DRAW_DURATION));
                }
                if ((mTrackingFlags & SYNC_DURATION) != 0) {
                    addDurationItem(mMetrics[SYNC_INDEX],
                            frameMetrics.getMetric(android.view.FrameMetrics.SYNC_DURATION));
                }
                if ((mTrackingFlags & SWAP_DURATION) != 0) {
                    addDurationItem(mMetrics[SWAP_INDEX],
                            frameMetrics.getMetric(
                                    android.view.FrameMetrics.SWAP_BUFFERS_DURATION));
                }
                if ((mTrackingFlags & COMMAND_DURATION) != 0) {
                    addDurationItem(mMetrics[COMMAND_INDEX],
                            frameMetrics.getMetric(
                                    android.view.FrameMetrics.COMMAND_ISSUE_DURATION));
                }
                if ((mTrackingFlags & DELAY_DURATION) != 0) {
                    addDurationItem(mMetrics[DELAY_INDEX],
                            frameMetrics.getMetric(
                                    android.view.FrameMetrics.UNKNOWN_DELAY_DURATION));
                }
                if ((mTrackingFlags & ANIMATION_DURATION) != 0) {
                    addDurationItem(mMetrics[ANIMATION_INDEX],
                            frameMetrics.getMetric(
                                    android.view.FrameMetrics.ANIMATION_DURATION));
                }
            }
        };

        void addDurationItem(SparseIntArray buckets, long duration) {
            if (buckets != null) {
                int durationMs = (int) ((duration + NANOS_ROUNDING_VALUE) / NANOS_PER_MS);
                if (duration >= 0) {
                    // ignore values < 0; something must have gone wrong
                    int oldValue = buckets.get(durationMs);
                    buckets.put(durationMs, (oldValue + 1));
                }
            }
        }

        @Override
        public void add(Activity activity) {
            if (sHandlerThread == null) {
                sHandlerThread = new HandlerThread("FrameMetricsAggregator");
                sHandlerThread.start();
                sHandler = new Handler(sHandlerThread.getLooper());
            }
            for (int i = 0; i <= LAST_INDEX; ++i) {
                if (mMetrics[i] == null && (mTrackingFlags & (1 << i)) != 0) {
                    mMetrics[i] = new SparseIntArray();
                }
            }
            activity.getWindow().addOnFrameMetricsAvailableListener(mListener, sHandler);
            mActivities.add(new WeakReference<>(activity));
        }

        @Override
        public SparseIntArray[] remove(Activity activity) {
            for (WeakReference<Activity> activityRef : mActivities) {
                if (activityRef.get() == activity) {
                    mActivities.remove(activityRef);
                    break;
                }
            }
            activity.getWindow().removeOnFrameMetricsAvailableListener(mListener);
            return mMetrics;
        }

        @Override
        public SparseIntArray[] stop() {
            int size = mActivities.size();
            for (int i = size - 1; i >= 0; i--) {
                WeakReference<Activity> ref = mActivities.get(i);
                Activity activity = ref.get();
                if (ref.get() != null) {
                    activity.getWindow().removeOnFrameMetricsAvailableListener(mListener);
                    mActivities.remove(i);
                }
            }
            return mMetrics;
        }

        @Override
        public SparseIntArray[] getMetrics() {
            return mMetrics;
        }

        @Override
        public SparseIntArray[] reset() {
            SparseIntArray[] returnVal = mMetrics;
            mMetrics = new SparseIntArray[LAST_INDEX + 1];
            return returnVal;
        }

    }

}


text:
angular.module('ngGridster', []);

angular.module('ngGridster').directive('gridster', [
    function () {
        return {
            restrict: 'E',
            template: '

',
            transclude: true,
            replace: true,
            controller: function () {
                gr = null;
                return {
                    init: function (elem, options) {
                        ul = $(elem);
                        gr = ul.gridster(angular.extend({
                          widget_selector: 'gridster-item'
                        }, options)).data('gridster');
                    },
                    addItem: function (elm)  {
                        gr.add_widget(elm);
                    },
                    removeItem: function (elm) {
                        gr.remove_widget(elm);
                    }
                };
            },
            link: function (scope, elem, attrs, controller) {
              var options = scope.$eval(attrs.options);
              controller.init(elem, options);
            }
        };
    }
]);

angular.module('ngGridster').directive('gridsterItem', [
    function () {
        return {
            restrict: 'EA',
            require: '^gridster',
            link: function (scope, elm, attrs, controller) {
                controller.addItem(elm);
                elm.bind('$destroy', function () {
                    controller.removeItem(elm);
                });
            }
        };
    }
]);