text:
package org.apache.tinkerpop.gremlin.process.traversal;

import org.apache.tinkerpop.gremlin.LoadGraphWith;
import org.apache.tinkerpop.gremlin.process.AbstractGremlinProcessTest;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalInterruptedException;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.UnaryOperator;

import static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.GRATEFUL;
import static org.junit.Assert.assertThat;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
@RunWith(Parameterized.class)
public class TraversalInterruptionTest extends AbstractGremlinProcessTest {
    private static final Logger logger = LoggerFactory.getLogger(TraversalInterruptionTest.class);

    @Parameterized.Parameters(name = "expectInterruption({0})")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {"g_V", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.V(), (UnaryOperator<GraphTraversal<?,?>>) t -> t},
                {"g_V_out", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.V(), (UnaryOperator<GraphTraversal<?,?>>) t -> t.out()},
                {"g_V_outE", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.V(), (UnaryOperator<GraphTraversal<?,?>>) t -> t.outE()},
                {"g_V_in", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.V(), (UnaryOperator<GraphTraversal<?,?>>) t -> t.in()},
                {"g_V_inE", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.V(), (UnaryOperator<GraphTraversal<?,?>>) t -> t.inE()},
                {"g_V_properties", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.V(), (UnaryOperator<GraphTraversal<?,?>>) t -> t.properties()},
                {"g_E", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.E(), (UnaryOperator<GraphTraversal<?,?>>) t -> t},
                {"g_E_outV", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.E(), (UnaryOperator<GraphTraversal<?,?>>) t -> t.outV()},
                {"g_E_inV", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.E(), (UnaryOperator<GraphTraversal<?,?>>) t -> t.inV()},
                {"g_E_properties", (Function<GraphTraversalSource, GraphTraversal<?,?>>) g -> g.E(), (UnaryOperator<GraphTraversal<?,?>>) t -> t.properties()},
        });
    }

    @Parameterized.Parameter(value = 0)
    public String name;

    @Parameterized.Parameter(value = 1)
    public Function<GraphTraversalSource,GraphTraversal<?,?>> traversalBeforePause;

    @Parameterized.Parameter(value = 2)
    public UnaryOperator<GraphTraversal<?,?>> traversalAfterPause;

    @Test
    @LoadGraphWith(GRATEFUL)
    public void shouldRespectThreadInterruptionInVertexStep() throws Exception {
        final AtomicBoolean exceptionThrown = new AtomicBoolean(false);
        final CountDownLatch startedIterating = new CountDownLatch(1);
        final Thread t = new Thread(() -> {
            final Traversal traversal = traversalAfterPause.apply(traversalBeforePause.apply(g).sideEffect(traverser -> {
                // let the first iteration flow through
                if (startedIterating.getCount() == 0) {
                    // ensure that the whole traversal doesn't iterate out before we get a chance to interrupt
                    // the next iteration should stop so we can force the interrupt to be handled by VertexStep
                    try {
                        Thread.sleep(3000);
                    } catch (Exception ignored) {
                        // make sure that the interrupt propagates in case the interrupt occurs during sleep.
                        // this should ensure VertexStep gets to try to throw the TraversalInterruptedException
                        Thread.currentThread().interrupt();
                    }
                } else {
                    startedIterating.countDown();
                }
            }));
            try {
                traversal.iterate();
            } catch (Exception ex) {
                exceptionThrown.set(ex instanceof TraversalInterruptedException);

                try {
                    traversal.close();
                } catch (Exception iex) {
                    logger.error("Error closing traversal after interruption", iex);
                }
            }

        }, name);

        t.start();

        // total time for test should not exceed 5 seconds - this prevents the test from just hanging and allows
        // it to finish with failure
        assertThat(startedIterating.await(5000, TimeUnit.MILLISECONDS), CoreMatchers.is(true));

        t.interrupt();
        t.join();

        // ensure that some but not all of the traversal was iterated and that the right exception was tossed
        assertThat(exceptionThrown.get(), CoreMatchers.is(true));
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <title>Fastnav plugins for Carew</title>

    <meta name="description" content="">
    <meta name="author" content="bacardi55">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

          <link rel="stylesheet" href="./css/bootstrap.min.css">
      <link rel="stylesheet" href="./css/bootstrap-responsive.min.css">
      <link rel="stylesheet" href="./css/main.css">

                bacardi55's blog

About

My projects

Plugins carew

                                    Bacardi55

 My home

 My projects

 My Github

 My lab

 My twitter

Fastnav plugins for Carew

FastNav plugin

Summary

My second plugin for carew is a « Fast Navigation » plugin.

This simple plugin help you create links to the previous and the next blog post of the current post.

You can see it in action at the bottom of each blog post on my blog

How to install it

A package is available on packagist in order to make it very simple for you to install.

All you have to do is to edit your composer.json file to add this requirement:

"bacardi55/carew-plugin-fastnav": "1.*dev"

Then, php composer.php update or php composer.php install depending on your case.

How to use it

Edit the carew config.yml file to enable the extension:

engine:
    …
    extensions:
        …
        - Carew\Plugin\FastNav\FastNavExtension
        …

Then, in your twig blog post template file, you can use the following variables:

The previous post link: carew.document.metadatas.fastNav.prev.link

The previous post title: carew.document.metadatas.fastNav.prev.title

The next post link: carew.document.metadatas.fastNav.next.link

The next post title: carew.document.metadatas.fastNav.next.title

Here is a full example of how this plugin is used on my blog:

{% if carew.document.metadatas.fastNav is not null %}
  <div class="fastNav">
    {% if carew.document.metadatas.fastNav.prev.link %}
      <div class="prev pull-left">
        <a href="{{ carew.document.metadatas.fastNav.prev.link }}">
          ← {{ carew.document.metadatas.fastNav.prev.title }}
        </a>
      </div>
    {% endif %}
    {% if carew.document.metadatas.fastNav.next.link %}
      <div class="next pull-right">
        <a href="{{ carew.document.metadatas.fastNav.next.link }}">
          {{ carew.document.metadatas.fastNav.next.title }} →
        </a>
      </div>
    {% endif %}
  </div>
{% endif %}

Source code

You can find the code on github here

The package can be found here on packagist.

Friends blog

rustx

chuck

Last tweets

      My lasts tweets

Tags

                  php (17)

                  vim (5)

                  xdebug (1)

                  sfForm (1)

                  twig (3)

                  mailcatcher (1)

                  news (3)

                  jocs (2)

                  pocs (2)

                  disqus (2)

                  nginx (3)

                  carew (5)

                  angularjs (1)

                  mutt (1)

                  silex (3)

                  wenizit (1)

                  tips (4)

                  ctags (1)

                  drupal (2)

                  sshfs (1)

                  github (1)

                  gpb (1)

                  css (1)

                  twig extension (1)

                  dualscreen (1)

                  xrandr (1)

                  bash (1)

                  vhost (1)

                  yaml (1)

                  apachesolr (1)

                  RSS (1)

            In case of any remarks or questions, please use the github tracker :)

            ©

                  bacardi55

                        2014

                with help from Carew

redpajama_set_name: RedPajamaGithub


text:
=begin rdoc
=Description
The JobSet model is an active record representation of the job_sets table in the database.
It uses active record to define association methods with the Job, and Patient models.
It also creates a convenience method for creating a job set using a patient_id and
a username.

This is also the class which generates the token to give to the patient and the single
use patient identifier.
=end
class JobSet < ActiveRecord::Base

  ALPHABET = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"
  ACCESS_CODE_LEN = 9
  TOKEN_LENGTH = 8

  self.primary_key = "job_set_id"
  has_many :jobs, :dependent => :destroy
  belongs_to :patient
  belongs_to :user, :foreign_key => :user_id

  attr_accessor :use_rsna_id, :salt, :token, :send_components
  attr_accessible :use_rsna_id, :send_to_site, :patient_password, :patient_password_confirmation, :patient_id, :user_id, :email_address, :modified_date, :delay_in_hrs, :send_on_complete, :access_code, :phone_number

  # Call back method used to set the single use patient id
  before_create do
    self.id = self.class.next_id
    if self.logic_type == :rsna_id
      self.single_use_patient_id = self.patient.rsna_id
      self.access_code = self.rsna_id_access_code
      self.send_components = {:access_code => self.access_code, :email_address => self.email_address, :formatted_dob => self.formatted_dob}
    elsif self.logic_type == :standard
      self.single_use_patient_id = trans_hash_gen()
      self.access_code = self.send_components[:access_code]
      self.patient.update_attribute(:rsna_id,self.single_use_patient_id)
    elsif self.logic_type == :send_to_site
      self.single_use_patient_id = trans_hash_gen()
      self.access_code = self.send_components[:access_code]
    end
  end

  # Checks the configurations table for a site_id
  # if not site_id is found it defaults to "0001" but does not memoize
  def self.site_id
    if @site_id
      @site_id
    else
      configured_site_id = EdgeConfiguration.find_by_key(:site_id)
      @site_id = configured_site_id.value if configured_site_id
      @site_id || "0001"
    end
  end

  # Checks to see if the confirmation password and password match before saving
  # to the database.
  def validate
    #if self.patient_password != self.patient_password_confirmation
    #  errors.add(:patient_password, "and password confirmation do not match")
    #end
  end

  # Creates a JobSet record using the patient_id and username supplied in the arguments
  def self.simple_create(patient_id, username)
    user = User.find_by_user_login(username)
    self.create({:patient_id => patient_id, :user_id => user.id})
  end

  def logic_type
    if self.send_to_site
      :send_to_site
    elsif self.use_rsna_id
      if self.rsna_id_access_code
        :rsna_id
      else
        :standard
      end
    else
      :standard
    end
  end

  protected
  # Triggers and returns the next value in the primary key sequence
  def self.next_id
    begin
      JobSet.find_by_sql("SELECT nextval('job_sets_job_set_id_seq') as value").first.value
    rescue
      raise "Failed to advance the job_sets_job_set_id_seq"
    end
  end

  def user_access_code_gen()
    if @access_code
      @access_code
    else
      hash = Digest::SHA256.hexdigest(SecureRandom.random_bytes(64)).to_i(16)
      gen_digits = []
      d = hash
      for i in 1...ACCESS_CODE_LEN
        d,r = d.divmod(ALPHABET.length)
        gen_digits << r
      end
      check_char = ALPHABET[gen_digits.each_with_index.map {|x, i| x * (i.even? ? 1 : 2)}.reduce(:+) % ALPHABET.length]
      code_str = ""
      for d in gen_digits
        code_str << ALPHABET[d]
      end
      code_str << check_char
      @access_code = code_str
    end
  end

  def rsna_id_access_code
    @matching_js ||= self.patient.job_sets.where({:single_use_patient_id => self.patient.rsna_id}).first
    if @matching_js and @matching_js.access_code
      @matching_js.access_code
    else
      nil
    end
  end

  def formatted_dob
    @formatted_dob ||= self.patient.dob.strftime("%Y%m%d")
  end

  # generates the transaction token
  def trans_hash_gen

    self.send_components = {:formatted_dob => formatted_dob, :access_code => self.user_access_code_gen}

    return Digest::SHA256.hexdigest(self.send_components.values.join("")) # hashes in ruby >= 1.9 are ordered in the order keys are added
  end

  # Checks the configurations table for a delay_in_hrs
  # if no delay_in_hrs is found it defaults to the column default value
  def self.delay_in_hrs
    default_delay_in_hrs = self.columns_hash['delay_in_hrs'].default
    configured_delay_in_hrs = EdgeConfiguration.find_by_key("delay_in_hrs")
    delay_in_hrs = configured_delay_in_hrs.value if configured_delay_in_hrs
    delay_in_hrs || default_delay_in_hrs
  end
end


text:
import os
import pprint
import shutil
import sys

from tiltbrush import tilt

def destroy(filename):
  try:
    os.unlink(filename)
  except OSError:
    pass

def increment_timestamp(stroke, increment):
  """Adds *increment* to all control points in stroke."""
  timestamp_idx = stroke.cp_ext_lookup['timestamp']
  for cp in stroke.controlpoints:
    cp.extension[timestamp_idx] += increment

def merge_metadata_from_tilt(tilt_dest, tilt_source):
  """Merges data from tilt_source into tilt_dest:
  - BrushIndex
  - ModelIndex
  - ImageIndex"""
  with tilt_dest.mutable_metadata() as md:
    to_append = set(tilt_source.metadata['BrushIndex']) - set(md['BrushIndex'])
    md['BrushIndex'].extend(sorted(to_append))

  if 'ImageIndex' in tilt_source.metadata:
    tilt_dest.metadata['ImageIndex'] = tilt_dest.metadata.get('ImageIndex', []) + \
                                       tilt_source.metadata['ImageIndex']

  if 'ModelIndex' in tilt_source.metadata:
    tilt_dest.metadata['ModelIndex'] = tilt_dest.metadata.get('ModelIndex', []) + \
                                       tilt_source.metadata['ModelIndex']

def concatenate(file_1, file_2, file_out):
  """Concatenate two .tilt files.
  file_out may be the same as one of the input files."""
  file_tmp = file_out + "__tmp"
  destroy(file_tmp)
  shutil.copyfile(file_1, file_tmp)
  tilt_out = tilt.Tilt(file_tmp)
  tilt_2 = tilt.Tilt(file_2)

  merge_metadata_from_tilt(tilt_out, tilt_2)

  tilt_out._guid_to_idx = dict(
    (guid, index)
    for (index, guid) in enumerate(tilt_out.metadata['BrushIndex']))

  final_stroke = tilt_out.sketch.strokes[-1]
  final_timestamp = final_stroke.get_cp_extension(final_stroke.controlpoints[-1], 'timestamp')
  timestamp_offset = final_timestamp + .03

  for stroke in tilt_2.sketch.strokes:
    copy = stroke.clone()

    # Convert brush index to one that works for tilt_out
    stroke_guid = tilt_2.metadata['BrushIndex'][stroke.brush_idx]
    copy.brush_idx = tilt_out._guid_to_idx[stroke_guid]
    tilt_out.sketch.strokes.append(copy)

    # Adjust timestamps to keep stroke times from overlapping.
    increment_timestamp(stroke, timestamp_offset)

  tilt_out.write_sketch()
  destroy(file_out)
  os.rename(file_tmp, file_out)

def main():
  import argparse
  parser = argparse.ArgumentParser(
    usage='%(prog)s -f FILE1 -f FILE2 ... -o OUTPUT_FILE'
  )
  parser.add_argument('-f', dest='files', metavar='FILE', action='append',
                      required=True,
                      help='A file to concatenate. May pass multiple times')
  parser.add_argument('-o', metavar='OUTPUT_FILE', dest='output_file',
                      required=True,
                      help='The name of the output file')
  args = parser.parse_args()
  if len(args.files) < 2:
    parser.error("Pass at least two files")

  concatenate(args.files[0], args.files[1], args.output_file)
  for filename in args.files[2:]:
    concatenate(args.output_file, filename, args.output_file)
  print "Wrote", args.output_file

if __name__ == '__main__':
  main()


text:
<?php use_helper('Bootflat'); ?>

<form class="xform-horizontal form-signin" action="<?php echo url_for('security/login') ?>"  method="POST">

<?php

if( $form->hasGlobalErrors() ):
		?>

<button class="close" aria-hidden="true" data-dismiss="alert" type="button">×</button>
Oh snap!
<?php echo $form->renderGlobalErrors(); ?>

		<?php

	endif; ?>

				<?php foreach(array($form['username'], $form['passwd']) as $sfFormFieldObj): ?>
					<?php printAsBootstrapForm($form, $sfFormFieldObj); ?>
				<?php endforeach; ?>

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>

</form>


text:
// card.java
package com.andrewswan.lostcities.domain;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * One of the 60 cards in the deck
 *
 * @author Andrew
 */
public class Card implements Comparable<Card> {

	// Constants
	protected static final Log LOGGER = LogFactory.getLog(Card.class);

	/**
	 * Returns the display name of a card with the given suit and value
	 *
	 * @param suit can't be null
	 * @param value can't be null
	 * @return a non-blank display name
	 */
	public static String getDisplayName(final Suit suit, final FaceValue value) {
		return suit.getName() + " " + value.getDisplayName();
	}

	// Instance properties
	private final FaceValue value;
	private final Suit suit;

	/**
	 * Constructor
	 *
	 * @param suit the suit to which this card belongs; can't be null
	 * @param value the face value of this card; can't be null
	 */
	public Card(final Suit suit, final FaceValue value) {
		if (suit == null) {
			throw new IllegalArgumentException("Suit can't be null");
		}
		if (value == null) {
			throw new IllegalArgumentException("Value can't be null");
		}
		this.suit = suit;
		this.value = value;
	}

//	/**
//	 * Indicates whether the only valid play of this card is to discard it
//	 *
//	 * @param exped the active player's expedition in this card's suit; can't be
//	 *   null, must be of the same suit
//	 * @return false if the card can be added to the given expedition
//	 */
//	public boolean mustDiscard(Expedition exped) {
//		if (exped == null) {
//			throw new IllegalArgumentException("Expedition can't be null");
//		}
//		if (exped.isEmpty()) {
//			// Any card is playable into an empty expedition
//			return false;
//		}
//		// The expedition has one or more cards in it; check the top value
//		exped.getTopCard();
//
//		// Check what card we are trying to play
//		Integer pointValue = this.value.getPoints();
//
//		if (pointValue < 3) {
//			pointValue = 0; // Make all investment cards equal
//		}
//
//		// Check the highest card played so far to this suit's expedition
//		int topExpedValue = exped.getTopCard();
//
//		// If top card is an Investment, or if exped is empty
//		if (topExpedValue < 3 || exped.isEmpty()) {
//			topExpedValue = 0; // Make all investment cards equal
//		}
//		LOGGER.debug("Top value for the exped is " + topExpedValue);
//
//		// Check if it can go in expedition or must be discarded
//		return pointValue < topExpedValue;
//	}

	/**
	 * Returns the point value of this card
	 *
	 * @return null if it's an investment card
	 */
	public Integer getPointValue() {
		return this.value.getPoints();
	}

	/**
	 * Returns this card's suit
	 *
	 * @return a non-null suit
	 */
	public Suit getSuit() {
		return this.suit;
	}

	/**
	 * Indicates whether this card is an investment card, in other words has no
	 * face value of its own
	 *
	 * @return see above
	 */
	public boolean isInvestmentCard() {
		return value.isInvestmentCard();
	}

	/**
	 * Indicates whether this card is lower than the given card
	 *
	 * @param otherCard the card to which this card is being compared; can be
	 *   null
	 * @return true if it's from a "lower" suit"
	 */
	public boolean isLowerValueThan(final Card otherCard) {
		if (otherCard == null) {
			return false;
		}
		return compareTo(otherCard) < 0;
	}

	@Override
	public boolean equals(final Object obj) {
		if (obj == this) {
			return true;
		}
		if (!(obj instanceof Card)) {
			return false;
		}
		return EqualsBuilder.reflectionEquals(this, obj);
	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

	@Override
	public String toString() {
		// For debugging
		return getDisplayName();
	}

	/**
	 * Returns this card's face value
	 *
	 * @return a non-null value (the point value might be
	 *   null though)
	 */
	public FaceValue getFaceValue() {
		return value;
	}

	public int compareTo(final Card otherCard) {
		if (this.suit.equals(otherCard.suit)) {
			// Same suit, so compare face values
			return this.value.compareTo(otherCard.value);
		}
		// Different suits; compare the suits
		return this.suit.compareTo(otherCard.suit);
	}

	/**
	 * Returns this card's display name
	 *
	 * @return a non-blank name
	 */
	public String getDisplayName() {
		return getDisplayName(this.suit, this.value);
	}
}


text:
using BulletSharp;
using BulletSharp.Math;

namespace BspDemo
{
    public abstract class BspConverter
    {
        public void ConvertBsp(BspLoader bspLoader, float scaling)
        {
            Vector3 playerStart = new Vector3(0, 0, 100);
            if (bspLoader.FindVectorByName("info_player_start", ref playerStart) == false)
            {
                bspLoader.FindVectorByName("info_player_deathmatch", ref playerStart);
            }
            playerStart[2] += 20.0f; //start a bit higher
            playerStart *= scaling;

            foreach (BspLeaf leaf in bspLoader.Leaves)
            {
                bool isValidBrush = false;

                for (int b = 0; b < leaf.NumLeafBrushes; b++)
                {
                    AlignedVector3Array planeEquations = new AlignedVector3Array();

                    int brushID = bspLoader.LeafBrushes[leaf.FirstLeafBrush + b];
                    BspBrush brush = bspLoader.Brushes[brushID];

                    if (brush.ShaderNum != -1)
                    {
                        ContentFlags flags = bspLoader.IsVbsp ? (ContentFlags)brush.ShaderNum : bspLoader.Shaders[brush.ShaderNum].ContentFlags;
                        if ((flags & ContentFlags.Solid) == ContentFlags.Solid)
                        {
                            brush.ShaderNum = -1;

                            for (int p = 0; p < brush.NumSides; p++)
                            {
                                int sideid = brush.FirstSide + p;

                                BspBrushSide brushside = bspLoader.BrushSides[sideid];
                                int planeid = brushside.PlaneNum;
                                BspPlane plane = bspLoader.Planes[planeid];
                                Vector4 planeEq = new Vector4(plane.Normal, scaling * -plane.Distance);
                                planeEquations.Add(planeEq);
                                isValidBrush = true;
                            }
                            if (isValidBrush)
                            {
                                AlignedVector3Array vertices = new AlignedVector3Array();
                                GeometryUtil.GetVerticesFromPlaneEquations(planeEquations, vertices);

                                const bool isEntity = false;
                                Vector3 entityTarget = Vector3.Zero;
                                AddConvexVerticesCollider(vertices, isEntity, entityTarget);
                            }
                        }
                    }
                }
            }
            /*
            foreach (BspEntity entity in bspLoader.Entities)
            {
                if (entity.ClassName == "trigger_push")
                {
                }
            }
            */
        }

        public abstract void AddConvexVerticesCollider(AlignedVector3Array vertices, bool isEntity, Vector3 entityTargetLocation);
    }
}


text:
from .colorentry import ColorPropertyEditor
from .tkvarentry import TkVarPropertyEditor
from .imageentry import ImagePropertyEditor
from .propertyeditor import EntryPropertyEditor, SpinboxPropertyEditor
from .propertyeditor import TextPropertyEditor, ChoicePropertyEditor
from .propertyeditor import CheckbuttonPropertyEditor
from .whentry import WHPropertyEditor
from .dynamicpropeditor import DynamicPropertyEditor
from .fontentry import FontPropertyEditor


text:
subdir=src/backend/access/transam
top_builddir=../../../../..

TARGETS=xact

# Objects from backend, which don't need to be mocked but need to be linked.
xact_REAL_OBJS=\
	$(top_srcdir)/src/backend/access/hash/hashfunc.o \
	$(top_srcdir)/src/backend/bootstrap/bootparse.o \
	$(top_srcdir)/src/backend/nodes/bitmapset.o \
	$(top_srcdir)/src/backend/lib/stringinfo.o \
	$(top_srcdir)/src/backend/nodes/equalfuncs.o \
	$(top_srcdir)/src/backend/nodes/list.o \
	$(top_srcdir)/src/backend/parser/gram.o \
	$(top_srcdir)/src/backend/regex/regcomp.o \
	$(top_srcdir)/src/backend/regex/regerror.o \
	$(top_srcdir)/src/backend/regex/regexec.o \
	$(top_srcdir)/src/backend/regex/regfree.o \
	$(top_srcdir)/src/backend/storage/page/itemptr.o \
	$(top_srcdir)/src/backend/utils/adt/datum.o \
	$(top_srcdir)/src/backend/utils/adt/like.o \
	$(top_srcdir)/src/backend/utils/hash/dynahash.o \
	$(top_srcdir)/src/backend/utils/hash/hashfn.o \
	$(top_srcdir)/src/backend/utils/misc/guc.o \
	$(top_srcdir)/src/backend/utils/init/globals.o \
	$(top_srcdir)/src/port/strlcpy.o \
	$(top_srcdir)/src/port/path.o \
	$(top_srcdir)/src/port/pgstrcasecmp.o \
	$(top_srcdir)/src/port/qsort.o \
	$(top_srcdir)/src/port/thread.o \
	$(top_srcdir)/src/timezone/localtime.o \
	$(top_srcdir)/src/timezone/pgtz.o \
	$(top_srcdir)/src/backend/access/transam/transam.o \
	$(top_srcdir)/src/backend/utils/time/tqual.o

include ../../../../Makefile.mock


text:
'use strict';

module.exports = function(grunt) {

// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks

var getIndexFile = function (src) {
    return grunt.file.read(src);
};

var log = grunt.log.write;

grunt.registerMultiTask('file_reader', 'Inroduction plugin', function() {
    // var indexFileSrc = this.data.source;

    grunt.file.write('index.jsx', '<oleg></oleg>');
    // grunt.log.write(getIndexFile(indexFileSrc));
    // var keys = Object.keys(this);

    // keys.forEach(function (key) {
    //     log(key + '\n');
    // });

    log(this.data.dest[0]);

    // Merge task-specific and/or target-specific options with these defaults.
    // var options = this.options({
    //   punctuation: '.',
    //   separator: ', '
    // });

    // // Iterate over all specified file groups.
    // this.files.forEach(function(f) {
    //   // Concat specified files.
    //   var src = f.src.filter(function(filepath) {
    //     // Warn on and remove invalid source files (if nonull was set).
    //     if (!grunt.file.exists(filepath)) {
    //       grunt.log.warn('Source file "' + filepath + '" not found.');
    //       return false;
    //     } else {
    //       return true;
    //     }
    //   }).map(function(filepath) {
    //     // Read file source.
    //     return grunt.file.read(filepath);
    //   }).join(grunt.util.normalizelf(options.separator));

    //   // Handle options.
    //   src += options.punctuation;

    //   // Write the destination file.
    //   grunt.file.write(f.dest, src);

    //   // Print a success message.
    //   grunt.log.writeln('File "' + f.dest + '" created.');
    // });
    });

};


text:
#include <iostream>

#include <gtest/gtest.h>
#include "caffe2/core/context.h"
#include "caffe2/core/flags.h"
#include "caffe2/core/operator.h"

CAFFE2_DECLARE_string(caffe_test_root);

namespace caffe2 {

template <class DataT>
static void AddScalarInput(
    const DataT& value,
    const string& name,
    Workspace* ws,
    bool isEmpty = false) {
  Blob* blob = ws->CreateBlob(name);
  auto* tensor = blob->GetMutable<TensorCPU>();
  if (!isEmpty) {
    tensor->Resize(vector<TIndex>{1});
    *(tensor->mutable_data<DataT>()) = value;
  } else {
    tensor->Resize(vector<TIndex>{0});
    tensor->mutable_data<DataT>();
  }
  return;
}

// Test case for BooleanUnmask operator
//  mask1:   [ false ]
//  values1: [ ]
//  mask2:   [ true ]
//  values2: [ 1.0 ]
//
//  Expected Output: [ 1.0 ]
TEST(BooleanUnmaskTest, Test) {
  Workspace ws;
  OperatorDef def;

  def.set_name("test");
  def.set_type("BooleanUnmask");

  def.add_input("mask1");
  def.add_input("values1");
  def.add_input("mask2");
  def.add_input("values2");

  def.add_output("unmasked_data");

  AddScalarInput(false, "mask1", &ws);
  AddScalarInput(float(), "values1", &ws, true);
  AddScalarInput(true, "mask2", &ws);
  AddScalarInput(1.0f, "values2", &ws);

  unique_ptr<OperatorBase> op(CreateOperator(def, &ws));
  EXPECT_NE(nullptr, op.get());

  EXPECT_TRUE(op->Run());

  Blob* unmasked_data_blob = ws.GetBlob("unmasked_data");
  EXPECT_NE(nullptr, unmasked_data_blob);

  auto& unmasked_data = unmasked_data_blob->Get<TensorCPU>();
  EXPECT_EQ(unmasked_data.size(), 1);

  CHECK_EQ(unmasked_data.data<float>()[0], 1.0f);
}

} // namespace caffe2


text:
Plugin.define "NoticeBoardPro" do
author "Brendan Coles <bcoles@gmail.com>" # 2011-05-19
version "0.1"
description "NoticeBoardPro is an online, web-based, notice board system"
website "http://www.noticeboardpro.com/"

# Google results as at 2011-05-19 #
# 5 for inurl:viewAll.php?startnum
# 7 for +noticeboard "View All Items" "View Items by Category"
# 4 for inurl:viewAllOutline.php

# Dorks #
dorks [
'"noticeboard" "View All Items" "View Items by Category"'
]

# Matches #
matches [

# Version Detection # copyright footer
{ :version=>/
Version ([\d\.]+) -/ },

# Register link
{ :text=>'[Register]' },

# Log in link
{ :text=>'[Sign In]' },

]

end


text:
package org.apache.kafka.streams.processor.internals.metrics;

import org.apache.kafka.common.metrics.Gauge;
import org.apache.kafka.common.metrics.Sensor;
import org.apache.kafka.common.metrics.Sensor.RecordingLevel;
import org.apache.kafka.streams.processor.internals.StreamThreadTotalBlockedTime;
import org.junit.Test;

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Collections;
import java.util.Map;
import org.mockito.ArgumentCaptor;

import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.LATENCY_SUFFIX;
import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.RATE_SUFFIX;
import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.ROLLUP_VALUE;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class ThreadMetricsTest {

    private static final String THREAD_ID = "thread-id";
    private static final String THREAD_LEVEL_GROUP = "stream-thread-metrics";
    private static final String TASK_LEVEL_GROUP = "stream-task-metrics";

    private final Sensor expectedSensor = mock(Sensor.class);
    private final StreamsMetricsImpl streamsMetrics = mock(StreamsMetricsImpl.class);
    private final Map<String, String> tagMap = Collections.singletonMap("hello", "world");

    @Test
    public void shouldGetProcessRatioSensor() {
        final String operation = "process-ratio";
        final String ratioDescription = "The fraction of time the thread spent on processing active tasks";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addValueMetricToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            ratioDescription
        );

        final Sensor sensor = ThreadMetrics.processRatioSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetProcessRecordsSensor() {
        final String operation = "process-records";
        final String avgDescription = "The average number of records processed within an iteration";
        final String maxDescription = "The maximum number of records processed within an iteration";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addAvgAndMaxToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            avgDescription,
            maxDescription
        );

        final Sensor sensor = ThreadMetrics.processRecordsSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetProcessLatencySensor() {
        final String operationLatency = "process" + LATENCY_SUFFIX;
        final String avgLatencyDescription = "The average process latency";
        final String maxLatencyDescription = "The maximum process latency";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operationLatency, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addAvgAndMaxToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operationLatency,
            avgLatencyDescription,
            maxLatencyDescription
        );

        final Sensor sensor = ThreadMetrics.processLatencySensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetProcessRateSensor() {
        final String operation = "process";
        final String operationRate = "process" + RATE_SUFFIX;
        final String totalDescription = "The total number of calls to process";
        final String rateDescription = "The average per-second number of calls to process";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operationRate, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addRateOfSumAndSumMetricsToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            rateDescription,
            totalDescription
        );

        final Sensor sensor = ThreadMetrics.processRateSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetPollRatioSensor() {
        final String operation = "poll-ratio";
        final String ratioDescription = "The fraction of time the thread spent on polling records from consumer";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addValueMetricToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            ratioDescription
        );

        final Sensor sensor = ThreadMetrics.pollRatioSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetPollRecordsSensor() {
        final String operation = "poll-records";
        final String avgDescription = "The average number of records polled from consumer within an iteration";
        final String maxDescription = "The maximum number of records polled from consumer within an iteration";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addAvgAndMaxToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            avgDescription,
            maxDescription
        );

        final Sensor sensor = ThreadMetrics.pollRecordsSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetPollSensor() {
        final String operation = "poll";
        final String operationLatency = operation + StreamsMetricsImpl.LATENCY_SUFFIX;
        final String totalDescription = "The total number of calls to poll";
        final String rateDescription = "The average per-second number of calls to poll";
        final String avgLatencyDescription = "The average poll latency";
        final String maxLatencyDescription = "The maximum poll latency";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addInvocationRateAndCountToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            rateDescription,
            totalDescription
        );
        StreamsMetricsImpl.addAvgAndMaxToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operationLatency,
            avgLatencyDescription,
            maxLatencyDescription
        );

        final Sensor sensor = ThreadMetrics.pollSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetCommitSensor() {
        final String operation = "commit";
        final String operationLatency = operation + StreamsMetricsImpl.LATENCY_SUFFIX;
        final String totalDescription = "The total number of calls to commit";
        final String rateDescription = "The average per-second number of calls to commit";
        final String avgLatencyDescription = "The average commit latency";
        final String maxLatencyDescription = "The maximum commit latency";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addInvocationRateAndCountToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            rateDescription,
            totalDescription
        );
        StreamsMetricsImpl.addAvgAndMaxToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operationLatency,
            avgLatencyDescription,
            maxLatencyDescription);

        final Sensor sensor = ThreadMetrics.commitSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetCommitRatioSensor() {
        final String operation = "commit-ratio";
        final String ratioDescription = "The fraction of time the thread spent on committing all tasks";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addValueMetricToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            ratioDescription
        );

        final Sensor sensor = ThreadMetrics.commitRatioSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetCommitOverTasksSensor() {
        final String operation = "commit";
        final String totalDescription =
            "The total number of calls to commit over all tasks assigned to one stream thread";
        final String rateDescription =
            "The average per-second number of calls to commit over all tasks assigned to one stream thread";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.DEBUG)).thenReturn(expectedSensor);
        when(streamsMetrics.taskLevelTagMap(THREAD_ID, ROLLUP_VALUE)).thenReturn(tagMap);
        StreamsMetricsImpl.addInvocationRateAndCountToSensor(
            expectedSensor,
            TASK_LEVEL_GROUP,
            tagMap,
            operation,
            rateDescription,
            totalDescription
        );

        final Sensor sensor = ThreadMetrics.commitOverTasksSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetPunctuateSensor() {
        final String operation = "punctuate";
        final String operationLatency = operation + StreamsMetricsImpl.LATENCY_SUFFIX;
        final String totalDescription = "The total number of calls to punctuate";
        final String rateDescription = "The average per-second number of calls to punctuate";
        final String avgLatencyDescription = "The average punctuate latency";
        final String maxLatencyDescription = "The maximum punctuate latency";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addInvocationRateAndCountToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            rateDescription,
            totalDescription
        );
        StreamsMetricsImpl.addAvgAndMaxToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operationLatency,
            avgLatencyDescription,
            maxLatencyDescription
        );

        final Sensor sensor = ThreadMetrics.punctuateSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetPunctuateRatioSensor() {
        final String operation = "punctuate-ratio";
        final String ratioDescription = "The fraction of time the thread spent on punctuating active tasks";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addValueMetricToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            ratioDescription
        );

        final Sensor sensor = ThreadMetrics.punctuateRatioSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetSkipRecordSensor() {
        final String operation = "skipped-records";
        final String totalDescription = "The total number of skipped records";
        final String rateDescription = "The average per-second number of skipped records";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO))
                .thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addInvocationRateAndCountToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            rateDescription,
            totalDescription
        );

        final Sensor sensor = ThreadMetrics.skipRecordSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetCreateTaskSensor() {
        final String operation = "task-created";
        final String totalDescription = "The total number of newly created tasks";
        final String rateDescription = "The average per-second number of newly created tasks";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);

        StreamsMetricsImpl.addInvocationRateAndCountToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            rateDescription,
            totalDescription
        );

        final Sensor sensor = ThreadMetrics.createTaskSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldGetCloseTaskSensor() {
        final String operation = "task-closed";
        final String totalDescription = "The total number of closed tasks";
        final String rateDescription = "The average per-second number of closed tasks";
        when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor);
        when(streamsMetrics.threadLevelTagMap(THREAD_ID)).thenReturn(tagMap);
        StreamsMetricsImpl.addInvocationRateAndCountToSensor(
            expectedSensor,
            THREAD_LEVEL_GROUP,
            tagMap,
            operation,
            rateDescription,
            totalDescription
        );

        final Sensor sensor = ThreadMetrics.closeTaskSensor(THREAD_ID, streamsMetrics);

        assertThat(sensor, is(expectedSensor));
    }

    @Test
    public void shouldAddThreadStartTimeMetric() {
        // Given:
        final long startTime = 123L;

        // When:
        ThreadMetrics.addThreadStartTimeMetric(
            "bongo",
            streamsMetrics,
            startTime
        );

        // Then:
        verify(streamsMetrics).addThreadLevelImmutableMetric(
            "thread-start-time",
            "The time that the thread was started",
            "bongo",
            startTime
        );
    }

    @Test
    public void shouldAddTotalBlockedTimeMetric() {
        // Given:
        final double startTime = 123.45;
        final StreamThreadTotalBlockedTime blockedTime = mock(StreamThreadTotalBlockedTime.class);
        when(blockedTime.compute()).thenReturn(startTime);

        // When:
        ThreadMetrics.addThreadBlockedTimeMetric(
            "burger",
            blockedTime,
            streamsMetrics
        );

        // Then:
        final ArgumentCaptor<Gauge<Double>> captor = gaugeCaptor();
        verify(streamsMetrics).addThreadLevelMutableMetric(
            eq("blocked-time-ns-total"),
            eq("The total time the thread spent blocked on kafka in nanoseconds"),
            eq("burger"),
            captor.capture()
        );
        assertThat(captor.getValue().value(null, 678L), is(startTime));
    }

    @SuppressWarnings("unchecked")
    private ArgumentCaptor<Gauge<Double>> gaugeCaptor() {
        return ArgumentCaptor.forClass(Gauge.class);
    }
}


text:
<!doctype html>
<html>
<head>
  <title>Test for kemia.ring.RingFinder</title>
</head>
<body>
<script src="http://localhost:9810/compile?id=ring_finder_test&mode=raw"></script>

</body>
</html>