text:
package com.fedevela.thread;

//http://arashmd.blogspot.mx/2013/07/java-thread-example.html

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

class Parameter {// Parameter class for passing required data to threads and
					// between classes
	public static final Color backColor = Color.black;// set the background
														// color, white and
														// black are cool enough
														// :D
	public static int minDrawTime = 33;// the minimum time square drawer should
										// wait after each drawing process
	public Graphics2D g;// graphic that associated to each vertical portion, for
						// drawing easier
	public int width, height;// indicated the width and height of eahc portion

	Parameter(Graphics2D g, int width, int height) {
		this.g = g;
		this.width = width;
		this.height = height;
	}
}

/**
 * by Arash M. Dehghani arashmd.blogspot.com
 */
public class MatrixThread implements Runnable {// Runnable implemented, this is
												// the drawing thread
	public static void main(String[] args) throws Exception {
		new MatrixThread();
	}

	JLabel lab; // Label for showing the target image
	// just some string at the top of the target image, would be your name :D
	String message = "by Arash M. Dehghani (arashmd.blogspot.com) , wheel the mouse for changing the drawing speed, click to exit";
	int levelCount = 24;// number of vertical portion, change and see the
						// effects (big ones doesn't make sense)
	int capSpace;// the space reminded (unusable) at the right and left sides
	BufferedImage img;// the target image that shows the target
	Graphics2D g;// the graphic associated the the img variable(target image)

	// number of times(frame) that drawing thread needs to refresh the target
	// image in a second
	// the higher value will effects(improve) the animation smoothness and would
	// cause the vertical-synchronization also needs more power
	// the lower value needs less power, decrease the animation smoothness and
	// would cause the glitching
	int fps = 60;// do not set less than 30 and and high values

	BufferedImage[] images;// arrays of portion images
	int screenWidth, screenHeight;// the width and height of the screen

	MatrixThread() throws Exception {
		GraphicsDevice vc;
		JFrame f = new JFrame("Matrix by Arash");
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		Toolkit tk = Toolkit.getDefaultToolkit();
		// hide the cursor
		f.setCursor(f.getToolkit().createCustomCursor(
				new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB),
				new Point(0, 0), "null"));
		screenWidth = tk.getScreenSize().width;// get the screen size
		screenHeight = tk.getScreenSize().height;
		img = new BufferedImage(screenWidth, screenHeight,
				BufferedImage.TYPE_INT_ARGB);// init the target image as screen
												// size
		lab = new JLabel(new ImageIcon(img), JLabel.CENTER);// init label and
															// pass the target
															// image to it as
															// showing parameter
		f.getContentPane().add(lab);
		g = img.createGraphics();
		vc = ge.getDefaultScreenDevice();
		f.setUndecorated(true);
		f.setResizable(false);
		vc.setFullScreenWindow(f);// set the application as full screen
		lab.addMouseListener(new MouseListener() {
			@Override
			public void mouseReleased(MouseEvent arg0) {
			}

			@Override
			public void mousePressed(MouseEvent arg0) {
			}

			@Override
			public void mouseExited(MouseEvent arg0) {
			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
			}

			@Override
			public void mouseClicked(MouseEvent arg0) {
				System.exit(0);
			}// exit the by a click
		});
		// listening for mouse wheel for decreasing and increasing the
		// fade-out/fade-in operation
		lab.addMouseWheelListener(new MouseWheelListener() {
			@Override
			public void mouseWheelMoved(MouseWheelEvent arg0) {
				if (arg0.getWheelRotation() == -1) {
					if (Parameter.minDrawTime > 30) {
						Parameter.minDrawTime -= 10;
					}
				} else {
					if (Parameter.minDrawTime < 60) {
						Parameter.minDrawTime += 10;
					}
				}
			}
		});
		images = new BufferedImage[levelCount];// init the portion images array
		// calculate the remind(unusable) space at right/left sides in target
		// image
		capSpace = (int) (tk.getScreenSize().getWidth() % levelCount) / 2;
		// calculate how many pixel is required for each portion image
		int width = (int) Math
				.floor(tk.getScreenSize().getWidth() / levelCount);
		for (int i = 0; i < levelCount; i++) {// in as for loop init portion
												// image array images
			images[i] = new BufferedImage(width, tk.getScreenSize().height,
					BufferedImage.TYPE_4BYTE_ABGR);
			Parameter p = new Parameter(images[i].createGraphics(), width,
					tk.getScreenSize().height);
			new Thread(new VerticalPortion(p)).start();// starts a portion as a
														// thread
		}
		Font font = new Font("courier new", Font.BOLD, 16);// the font for
															// showing the
															// message at the
															// top screen
		g.setFont(font);
		new Thread(this).start();// starts this thread(drawing thread)
	}

	@Override
	public void run() {// drawing thread start
		while (true) {
			g.setColor(Parameter.backColor);// set the color as it should be
			g.fillRect(0, 0, screenWidth, screenHeight);// purge the screen
			for (int i = 0; i < images.length; i++) {// draw each portion to the
														// target img
				g.drawImage(images[i], (images[i].getWidth() * i)
						+ ((i == 0) ? capSpace : 0), 0, lab);
			}
			g.setColor(Color.gray);// set the color to draw the message, could
									// be anything
			g.drawString(message, 20, 20);
			lab.repaint();// force the label to refresh (refresh the image in
							// fact)
			try {
				Thread.sleep(1000 / fps);// wait for a while
			} catch (InterruptedException e) {
			}
		}
	}// drawing thread end
}

class VerticalPortion implements Runnable {
	Parameter p;
	Thread[] trds;
	int verticalSpaceCap;// remind (unusable) space in top and bottom of the
							// screen

	public VerticalPortion(Parameter p) {
		this.p = p;
		trds = new Thread[(int) Math.floor(p.height / p.width)];// calculate how
																// many possible
																// square would
																// this portion
																// have
		verticalSpaceCap = p.height % p.width;// calculate the unusable space
		p.g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);// enable antialias, it draws
													// components smoother
	}

	@Override
	public void run() {
		for (int i = 0; i < trds.length; i++) {
			Parameter px = new Parameter(p.g, p.width, p.height);
			trds[i] = new Thread(new SmallSquare(px, i * p.width
					+ (verticalSpaceCap / 2)));// one thread for one small
												// square handler
			trds[i].start();// start the thread
		}
	}
}

class SmallSquare implements Runnable {
	Parameter p;
	// two 4 length array that contains the RGBA of both background color and
	// color square should be drawn by
	byte[] color, hcolor = new byte[4];
	int topSpaceCap;// indicates how many pixel from top should this thread skip
	int margin; // spaces should be skip at each edge of square
	int j;// index for saving the last alpha value
	int waitTime;// time this thread should wait after each drawing
	int shapeSize;// the target shape size
	int increaseWidth;// the increment size for each square layer
	int colorDiff = 10;// the value that effects each iteration color, could be
						// more(more differences) or less

	public SmallSquare(Parameter p, int topSpaceCap) {
		this.p = p;
		this.topSpaceCap = topSpaceCap;
		margin = (int) (p.width * 0.05);
		// split the randomized color into a 4 byte array as ARGB
		this.color = ByteBuffer.allocate(4)
				.putInt((int) (Math.random() * Integer.MIN_VALUE)).array();
		hcolor[0] = (byte) 0;
		hcolor[1] = (byte) Parameter.backColor.getRed();
		hcolor[2] = (byte) Parameter.backColor.getGreen();
		hcolor[3] = (byte) Parameter.backColor.getBlue();
		// Initialize the target full-transparent square size
		shapeSize = (p.width) - (margin * 2);
		// initialize how many pixel should increase for the next layers
		increaseWidth = (int) ((shapeSize - (shapeSize * 0.6)) / 10);
	}

	@Override
	public void run() {
		while (true) {
			waitTime = (int) (Math.random() * Parameter.minDrawTime * 3);// get
																			// a
																			// random
																			// wait
																			// time
																			// in
																			// each
																			// iteration
			if (waitTime < Parameter.minDrawTime) {
				waitTime = Parameter.minDrawTime;
			}
			int diff = (int) (Math.random() * colorDiff) + 1;
			int ndiff = (diff % 2 == 0) ? diff : diff * -1;
			color[1] = ((color[1] & 0XFF) + colorDiff < 255 && (color[1] & 0XFF)
					- colorDiff > 0) ? (byte) ((color[1] & 0xFF) + ndiff)
					: (((color[1] & 0xFF) + colorDiff > 255) ? (byte) ((color[1] & 0xFF) - diff)
							: (byte) ((color[1] & 0xFF) + diff));

			color[2] = ((color[2] & 0XFF) + colorDiff < 255 && (color[2] & 0XFF)
					- colorDiff > 0) ? (byte) ((color[2] & 0xFF) + ndiff)
					: (((color[2] & 0xFF) + colorDiff > 255) ? (byte) ((color[2] & 0xFF) - diff)
							: (byte) ((color[2] & 0xFF) + diff));

			color[3] = ((color[3] & 0XFF) + colorDiff < 255 && (color[3] & 0XFF)
					- colorDiff > 0) ? (byte) ((color[3] & 0xFF) + ndiff)
					: (((color[3] & 0xFF) + colorDiff > 255) ? (byte) ((color[3] & 0xFF) - diff)
							: (byte) ((color[3] & 0xFF) + diff));

			// fade-in method 0, comment the method 1 if you wan to use this
			/*
			 * for(int i=0;i<10;i++){ if(i==9){color[0]=(byte) 255;}
			 * else{color[0]=(byte) (i*10);} synchronized (p.g){
			 * if(i==9){p.g.setColor(new
			 * Color(color[1]&0xFF,color[2]&0xFF,color[
			 * 3]&0xFF,color[0]&0xFF).brighter());} else{p.g.setColor(new
			 * Color(color[1]&0xFF,color[2]&0xFF,color[3]&0xFF,color[0]&0xFF));}
			 * p
			 * .g.fillRoundRect(margin+(i*increaseWidth),margin+(i*increaseWidth
			 * )+this.topSpaceCap,
			 * shapeSize-(i*increaseWidth*2),shapeSize-(i*increaseWidth*2),j,j);
			 * } try {Thread.sleep(waitTime);} catch (InterruptedException e) {}
			 * }
			 */// fade-in method 0

			// fade in method 1
			for (int i = 10; i > 0; i--) {
				color[0] = (byte) (i * 5);// sets the alpha for each layer of
											// the square

				/*
				 * this synchronized block is required, because in a portion,
				 * there are(could be) more than 1 thread.so because the portion
				 * image is shared belong to every thread, each thread need to
				 * lock the graphic objectand draw it's image, if there is no
				 * synchronized method, this is possible that thread 1 draw its
				 * line bythe color that thread 2 has been specified, just omit
				 * the synchronized block and see the difference!
				 */
				synchronized (p.g) {// [0]
					// drawing brighter color for the center square
					if (i == 10) {
						p.g.setColor(new Color(color[1] & 0xFF,
								color[2] & 0xFF, color[3] & 0xFF, 255)
								.brighter().brighter().brighter());
					} else {
						p.g.setColor(new Color(color[1] & 0xFF,
								color[2] & 0xFF, color[3] & 0xFF,
								color[0] & 0xFF));
					}
					p.g.fillRoundRect(margin + (i * increaseWidth), margin
							+ (i * increaseWidth) + this.topSpaceCap, shapeSize
							- (i * increaseWidth * 2), shapeSize
							- (i * increaseWidth * 2), (10 - i) * 2,
							(10 - i) * 2);
				}
				try {
					Thread.sleep(waitTime);
				} catch (InterruptedException e) {
				}
			}// fade-in method 1

			// fade-out
			for (int i = 0; i < 50; i++) {
				hcolor[0] = (byte) (i * 5.1);
				synchronized (p.g) {
					p.g.setColor(new Color(hcolor[1] & 0xFF, hcolor[2] & 0xFF,
							hcolor[3] & 0xFF, hcolor[0] & 0xFF));
					p.g.fillRect(margin, margin + this.topSpaceCap, shapeSize,
							shapeSize);
				}
				try {
					Thread.sleep(waitTime);
				} catch (InterruptedException e) {
				}
			}// fade-out

		}
	}
}


text:
`tf.contrib.data` API
=====================

NOTE: The `tf.contrib.data` module has been deprecated. Use `tf.data` instead,
or `tf.data.experimental` for the experimental transformations previously hosted
in this module. We are continuing to support existing code using the
`tf.contrib.data` APIs in the current version of TensorFlow, but will eventually
remove support. The non-experimental `tf.data` APIs are subject to backwards
compatibility guarantees.

Porting your code to `tf.data`
------------------------------

The `tf.contrib.data.Dataset` class has been renamed to `tf.data.Dataset`, and
the `tf.contrib.data.Iterator` class has been renamed to `tf.data.Iterator`.
Most code can be ported by removing `.contrib` from the names of the classes.
However, there are some small differences, which are outlined below.

The arguments accepted by the `Dataset.map()` transformation have changed:

* `dataset.map(..., num_threads=T)` is now `dataset.map(num_parallel_calls=T)`.
* `dataset.map(..., output_buffer_size=B)` is now
  `dataset.map(...).prefetch(B)`.

Some transformations have been removed from `tf.data.Dataset`, and you must
instead apply them using `Dataset.apply()` transformation. The full list of
changes is as follows:

* `dataset.dense_to_sparse_batch(...)` is now
  `dataset.apply(tf.data.experimental.dense_to_sparse_batch(...)`.
* `dataset.enumerate(...)` is now
  `dataset.apply(tf.data.experimental.enumerate_dataset(...))`.
* `dataset.group_by_window(...)` is now
  `dataset.apply(tf.data.experimental.group_by_window(...))`.
* `dataset.ignore_errors()` is now
  `dataset.apply(tf.data.experimental.ignore_errors())`.
* `dataset.unbatch()` is now `dataset.apply(tf.contrib.data.unbatch())`.

The `Dataset.make_dataset_resource()` and `Iterator.dispose_op()` methods have
been removed from the API. Please open a GitHub issue if you have a need for
either of these.

redpajama_set_name: RedPajamaGithub


text:
require 'helper.rb'

class TestJsRequire < Test::Unit::TestCase

  def setup
    @fixtures_dir = File.join(File.dirname(__FILE__), "fixtures")
  end

  def assert_requires(file, javascripts, stylesheets = [])
    @jsrequire = JsRequire.new
    data = @jsrequire.resolve_dependencies(File.join(@fixtures_dir + "/javascripts", file))

    expect = [file, javascripts].flatten.map { |js| File.expand_path(js, @fixtures_dir + "/javascripts") }.sort
    assert_equal expect, data[:javascripts].sort
    assert_equal stylesheets, data[:stylesheets]
  end

  context "#resolve_dependencies" do

    should "return the basic hash with empty results" do
      @jsrequire = JsRequire.new
      data = @jsrequire.resolve_dependencies([])

      assert !data.include?(:bernd)

      assert data.include?(:javascripts)
      assert data.include?(:stylesheets)
    end

    should "require nothing" do
      assert_requires("norequire.js", [])
    end

    should "require recursive dependencies" do
      file = File.join(@fixtures_dir, "javascripts/a.js")

      @jsrequire = JsRequire.new File.join(@fixtures_dir, "different-place")
      data = @jsrequire.resolve_dependencies(file)

      expect = ["javascripts/norequire.js", "different-place/b.js", "javascripts/a.js"].map { |js| File.expand_path(js, @fixtures_dir) }
      assert_equal expect, data[:javascripts]
    end

    should "require recursive dependencies in right order" do
      files = ["different-place/b.js", "javascripts/c.js"].map { |f| File.join(@fixtures_dir, f) }

      @jsrequire = JsRequire.new File.join(@fixtures_dir, "different-place")
      data = @jsrequire.resolve_dependencies(files)

      expect = ["javascripts/norequire.js", "different-place/b.js", "javascripts/a.js", "javascripts/c.js"].map { |js| File.expand_path(js, @fixtures_dir) }
      assert_equal expect, data[:javascripts]
    end

    should "require one css file" do
      assert_requires("requirecss.js", [], ["style.css"])
    end

    should "resolve dependencies from loadpath with source file from different place" do
      loadpath = File.join(@fixtures_dir, "javascripts")
      @jsrequire = JsRequire.new(loadpath)

      source_file = File.join(@fixtures_dir, "different-place/b.js")
      dep = @jsrequire.resolve_dependencies(source_file)

      files = ["javascripts/norequire.js", "different-place/b.js"].map { |f| File.expand_path(f, @fixtures_dir) }
      assert_equal files, dep[:javascripts]
    end

    should "not be able to resolve dependent files because of missing loadpath" do
      @jsrequire = JsRequire.new
      source_file = File.join(@fixtures_dir, "different-place/b.js")
      required_file_found = true

      begin
        dep = @jsrequire.resolve_dependencies(source_file)
      rescue JsRequire::FileNotFoundInLoadpath
        required_file_found = false
      end

      assert !required_file_found, "load of required files should fail"
    end

    should "throw an exception when requiring a non existing file" do
      assert_raises JsRequire::FileNotFoundInLoadpath do
        assert_requires("require_non_existing_file.js", [])
      end
    end

    should "be able to require a file via namespaces" do
      assert_requires("require_namespaced_file.js", "namespace/a.js")
    end

    should "be able to require a file via relative namespaces" do
      assert_requires("require_relative_namespaced_file.js", ["relative_namespace/a.js", "relative_namespace/b.js", "relative_namespace/sub/a.js"])
    end

    should "be able to require a file with dots in filename" do
      assert_requires("require_filename_with_dot.js", "file.with.dot.js")
    end

    should "be able to require namespaced files starting with 'js'" do
      assert_requires("require_filename_with_js.js", "namespace/json_reader.js")
    end

    should "check loadpaths" do
      additional_loadpath = File.join(@fixtures_dir, "different-place")
      extracted_loadpath = File.join(@fixtures_dir, "javascripts")
      files = ["norequire.js", "requirecss.js"].map { |f| File.join(extracted_loadpath, f) }
      @jsrequire = JsRequire.new(additional_loadpath)
      @jsrequire.resolve_dependencies(files)

      extracted_loadpaths = [File.expand_path(extracted_loadpath)]
      assert_equal extracted_loadpaths, @jsrequire.instance_eval("@extract_loadpaths")

      additional_loadpaths = [File.expand_path(additional_loadpath)]
      assert_equal additional_loadpaths, @jsrequire.instance_eval("@additional_loadpaths")
    end

    should "work with CoffeeScript files, too" do
      assert_requires("i_can_cook.coffee", ["coffee/other.coffee", "coffee/tea.js", "coffee/coke.coffee"])
    end

  end

  context "helper methods" do

    should "#web_path_helper" do
      loadpath = File.join(@fixtures_dir, "javascripts")
      @jsrequire = JsRequire.new(loadpath)

      source_file = File.join(@fixtures_dir, "different-place/b.js")
      dep = @jsrequire.resolve_dependencies(source_file)

      absolute_files = ["javascripts/norequire.js", "different-place/b.js"].map { |f| File.expand_path(f, @fixtures_dir) }
      assert_equal absolute_files, dep[:javascripts]

      relative_files = ["/javascripts/norequire.js", "/different-place/b.js"]
      assert_equal relative_files, JsRequire::web_path_helper(dep[:javascripts], @fixtures_dir)

      relative_files = ["/javascripts/norequire.js", "/different-place/b.js"]
      assert_equal relative_files, JsRequire::web_path_helper(dep[:javascripts], [@fixtures_dir])

      other_relative_files = ["/bernd/norequire.js", "/baerbel/b.js"]
      assert_equal other_relative_files, JsRequire::web_path_helper(dep[:javascripts], {
        File.join(@fixtures_dir, "javascripts") => "/bernd",
        File.join(@fixtures_dir, "different-place") => "/baerbel"
      })
    end

    should "#namespace_helper" do
      js = ["/platform/public/javascripts/si/module/Hastenichtgesehen.js", "/platform/public/javascripts/si/desktop/Wurstwaren.js", "/platform/public/javascripts/si/applet/GeradNeu.js"]
      ns = ["si.applet", "si.desktop", "si.module"]

      assert_equal ns, JsRequire::namespace_helper(js, "si")
    end

  end

end


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

#ifndef BASE_NUMERICS_SAFE_MATH_H_
#define BASE_NUMERICS_SAFE_MATH_H_

#include <stddef.h>

#include <limits>
#include <type_traits>

#include "base/numerics/safe_math_impl.h"

namespace base {
namespace internal {

// CheckedNumeric<> implements all the logic and operators for detecting integer
// boundary conditions such as overflow, underflow, and invalid conversions.
// The CheckedNumeric type implicitly converts from floating point and integer
// data types, and contains overloads for basic arithmetic operations (i.e.: +,
// -, *, / for all types and %, <<, >>, &, |, ^ for integers). Type promotions
// are a slightly modified version of the standard C arithmetic rules with the
// two differences being that there is no default promotion to int and bitwise
// logical operations always return an unsigned of the wider type.
//
// You may also use one of the variadic convenience functions, which accept
// standard arithmetic or CheckedNumeric types, perform arithmetic operations,
// and return a CheckedNumeric result. The supported functions are:
//  CheckAdd() - Addition.
//  CheckSub() - Subtraction.
//  CheckMul() - Multiplication.
//  CheckDiv() - Division.
//  CheckMod() - Modulous (integer only).
//  CheckLsh() - Left integer shift (integer only).
//  CheckRsh() - Right integer shift (integer only).
//  CheckAnd() - Bitwise AND (integer only with unsigned result).
//  CheckOr()  - Bitwise OR (integer only with unsigned result).
//  CheckXor() - Bitwise XOR (integer only with unsigned result).
//  CheckMax() - Maximum of supplied arguments.
//  CheckMin() - Minimum of supplied arguments.
//
// The unary negation, increment, and decrement operators are supported, along
// with the following unary arithmetic methods, which return a new
// CheckedNumeric as a result of the operation:
//  Abs() - Absolute value.
//  UnsignedAbs() - Absolute value as an equal-width unsigned underlying type
//          (valid for only integral types).
//  Max() - Returns whichever is greater of the current instance or argument.
//          The underlying return type is whichever has the greatest magnitude.
//  Min() - Returns whichever is lowest of the current instance or argument.
//          The underlying return type is whichever has can represent the lowest
//          number in the smallest width (e.g. int8_t over unsigned, int over
//          int8_t, and float over int).
//
// The following methods convert from CheckedNumeric to standard numeric values:
//  AssignIfValid() - Assigns the underlying value to the supplied destination
//          pointer if the value is currently valid and within the range
//          supported by the destination type. Returns true on success.
//  ****************************************************************************
//  *  WARNING: All of the following functions return a StrictNumeric, which   *
//  *  is valid for comparison and assignment operations, but will trigger a   *
//  *  compile failure on attempts to assign to a type of insufficient range.  *
//  ****************************************************************************
//  IsValid() - Returns true if the underlying numeric value is valid (i.e. has
//          has not wrapped and is not the result of an invalid conversion).
//  ValueOrDie() - Returns the underlying value. If the state is not valid this
//          call will crash on a CHECK.
//  ValueOrDefault() - Returns the current value, or the supplied default if the
//          state is not valid (will not trigger a CHECK).
//
// The following wrapper functions can be used to avoid the template
// disambiguator syntax when converting a destination type.
//   IsValidForType<>() in place of: a.template IsValid<Dst>()
//   ValueOrDieForType<>() in place of: a.template ValueOrDie()
//   ValueOrDefaultForType<>() in place of: a.template ValueOrDefault(default)
//
// The following are general utility methods that are useful for converting
// between arithmetic types and CheckedNumeric types:
//  CheckedNumeric::Cast<Dst>() - Instance method returning a CheckedNumeric
//          derived from casting the current instance to a CheckedNumeric of
//          the supplied destination type.
//  MakeCheckedNum() - Creates a new CheckedNumeric from the underlying type of
//          the supplied arithmetic, CheckedNumeric, or StrictNumeric type.
//
// Comparison operations are explicitly not supported because they could result
// in a crash on an unexpected CHECK condition. You should use patterns like the
// following for comparisons:
//   CheckedNumeric<size_t> checked_size = untrusted_input_value;
//   checked_size += HEADER LENGTH;
//   if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size)
//     Do stuff...

template <typename T>
class CheckedNumeric {
  static_assert(std::is_arithmetic<T>::value,
                "CheckedNumeric<T>: T must be a numeric type.");

 public:
  using type = T;

  constexpr CheckedNumeric() {}

  // Copy constructor.
  template <typename Src>
  constexpr CheckedNumeric(const CheckedNumeric<Src>& rhs)
      : state_(rhs.state_.value(), rhs.IsValid()) {}

  template <typename Src>
  friend class CheckedNumeric;

  // This is not an explicit constructor because we implicitly upgrade regular
  // numerics to CheckedNumerics to make them easier to use.
  template <typename Src>
  constexpr CheckedNumeric(Src value)  // NOLINT(runtime/explicit)
      : state_(value) {
    static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
  }

  // This is not an explicit constructor because we want a seamless conversion
  // from StrictNumeric types.
  template <typename Src>
  constexpr CheckedNumeric(
      StrictNumeric<Src> value)  // NOLINT(runtime/explicit)
      : state_(static_cast<Src>(value)) {}

  // IsValid() - The public API to test if a CheckedNumeric is currently valid.
  // A range checked destination type can be supplied using the Dst template
  // parameter.
  template <typename Dst = T>
  constexpr bool IsValid() const {
    return state_.is_valid() &&
           IsValueInRangeForNumericType<Dst>(state_.value());
  }

  // AssignIfValid(Dst) - Assigns the underlying value if it is currently valid
  // and is within the range supported by the destination type. Returns true if
  // successful and false otherwise.
  template <typename Dst>
  constexpr bool AssignIfValid(Dst* result) const {
    return IsValid<Dst>() ? ((*result = static_cast<Dst>(state_.value())), true)
                          : false;
  }

  // ValueOrDie() - The primary accessor for the underlying value. If the
  // current state is not valid it will CHECK and crash.
  // A range checked destination type can be supplied using the Dst template
  // parameter, which will trigger a CHECK if the value is not in bounds for
  // the destination.
  // The CHECK behavior can be overridden by supplying a handler as a
  // template parameter, for test code, etc. However, the handler cannot access
  // the underlying value, and it is not available through other means.
  template <typename Dst = T, class CheckHandler = CheckOnFailure>
  constexpr StrictNumeric<Dst> ValueOrDie() const {
    return IsValid<Dst>() ? static_cast<Dst>(state_.value())
                          : CheckHandler::template HandleFailure<Dst>();
  }

  // ValueOrDefault(T default_value) - A convenience method that returns the
  // current value if the state is valid, and the supplied default_value for
  // any other state.
  // A range checked destination type can be supplied using the Dst template
  // parameter. WARNING: This function may fail to compile or CHECK at runtime
  // if the supplied default_value is not within range of the destination type.
  template <typename Dst = T, typename Src>
  constexpr StrictNumeric<Dst> ValueOrDefault(const Src default_value) const {
    return IsValid<Dst>() ? static_cast<Dst>(state_.value())
                          : checked_cast<Dst>(default_value);
  }

  // Returns a checked numeric of the specified type, cast from the current
  // CheckedNumeric. If the current state is invalid or the destination cannot
  // represent the result then the returned CheckedNumeric will be invalid.
  template <typename Dst>
  constexpr CheckedNumeric<typename UnderlyingType<Dst>::type> Cast() const {
    return *this;
  }

  // This friend method is available solely for providing more detailed logging
  // in the the tests. Do not implement it in production code, because the
  // underlying values may change at any time.
  template <typename U>
  friend U GetNumericValueForTest(const CheckedNumeric<U>& src);

  // Prototypes for the supported arithmetic operator overloads.
  template <typename Src>
  CheckedNumeric& operator+=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator-=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator*=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator/=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator%=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator<<=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator>>=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator&=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator|=(const Src rhs);
  template <typename Src>
  CheckedNumeric& operator^=(const Src rhs);

  constexpr CheckedNumeric operator-() const {
    return CheckedNumeric<T>(
        NegateWrapper(state_.value()),
        IsValid() &&
            (!std::is_signed<T>::value || std::is_floating_point<T>::value ||
             NegateWrapper(state_.value()) !=
                 std::numeric_limits<T>::lowest()));
  }

  constexpr CheckedNumeric operator~() const {
    return CheckedNumeric<decltype(InvertWrapper(T()))>(
        InvertWrapper(state_.value()), IsValid());
  }

  constexpr CheckedNumeric Abs() const {
    return CheckedNumeric<T>(
        AbsWrapper(state_.value()),
        IsValid() &&
            (!std::is_signed<T>::value || std::is_floating_point<T>::value ||
             AbsWrapper(state_.value()) != std::numeric_limits<T>::lowest()));
  }

  template <typename U>
  constexpr CheckedNumeric<typename MathWrapper<CheckedMaxOp, T, U>::type> Max(
      const U rhs) const {
    using R = typename UnderlyingType<U>::type;
    using result_type = typename MathWrapper<CheckedMaxOp, T, U>::type;
    // TODO(jschuh): This can be converted to the MathOp version and remain
    // constexpr once we have C++14 support.
    return CheckedNumeric<result_type>(
        static_cast<result_type>(
            IsGreater<T, R>::Test(state_.value(), Wrapper<U>::value(rhs))
                ? state_.value()
                : Wrapper<U>::value(rhs)),
        state_.is_valid() && Wrapper<U>::is_valid(rhs));
  }

  template <typename U>
  constexpr CheckedNumeric<typename MathWrapper<CheckedMinOp, T, U>::type> Min(
      const U rhs) const {
    using R = typename UnderlyingType<U>::type;
    using result_type = typename MathWrapper<CheckedMinOp, T, U>::type;
    // TODO(jschuh): This can be converted to the MathOp version and remain
    // constexpr once we have C++14 support.
    return CheckedNumeric<result_type>(
        static_cast<result_type>(
            IsLess<T, R>::Test(state_.value(), Wrapper<U>::value(rhs))
                ? state_.value()
                : Wrapper<U>::value(rhs)),
        state_.is_valid() && Wrapper<U>::is_valid(rhs));
  }

  // This function is available only for integral types. It returns an unsigned
  // integer of the same width as the source type, containing the absolute value
  // of the source, and properly handling signed min.
  constexpr CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>
  UnsignedAbs() const {
    return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>(
        SafeUnsignedAbs(state_.value()), state_.is_valid());
  }

  CheckedNumeric& operator++() {
    *this += 1;
    return *this;
  }

  CheckedNumeric operator++(int) {
    CheckedNumeric value = *this;
    *this += 1;
    return value;
  }

  CheckedNumeric& operator--() {
    *this -= 1;
    return *this;
  }

  CheckedNumeric operator--(int) {
    CheckedNumeric value = *this;
    *this -= 1;
    return value;
  }

  // These perform the actual math operations on the CheckedNumerics.
  // Binary arithmetic operations.
  template <template <typename, typename, typename> class M,
            typename L,
            typename R>
  static CheckedNumeric MathOp(const L lhs, const R rhs) {
    using Math = typename MathWrapper<M, L, R>::math;
    T result = 0;
    bool is_valid =
        Wrapper<L>::is_valid(lhs) && Wrapper<R>::is_valid(rhs) &&
        Math::Do(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs), &result);
    return CheckedNumeric<T>(result, is_valid);
  };

  // Assignment arithmetic operations.
  template <template <typename, typename, typename> class M, typename R>
  CheckedNumeric& MathOp(const R rhs) {
    using Math = typename MathWrapper<M, T, R>::math;
    T result = 0;  // Using T as the destination saves a range check.
    bool is_valid = state_.is_valid() && Wrapper<R>::is_valid(rhs) &&
                    Math::Do(state_.value(), Wrapper<R>::value(rhs), &result);
    *this = CheckedNumeric<T>(result, is_valid);
    return *this;
  };

 private:
  CheckedNumericState<T> state_;

  template <typename Src>
  constexpr CheckedNumeric(Src value, bool is_valid)
      : state_(value, is_valid) {}

  // These wrappers allow us to handle state the same way for both
  // CheckedNumeric and POD arithmetic types.
  template <typename Src>
  struct Wrapper {
    static constexpr bool is_valid(Src) { return true; }
    static constexpr Src value(Src value) { return value; }
  };

  template <typename Src>
  struct Wrapper<CheckedNumeric<Src>> {
    static constexpr bool is_valid(const CheckedNumeric<Src> v) {
      return v.IsValid();
    }
    static constexpr Src value(const CheckedNumeric<Src> v) {
      return v.state_.value();
    }
  };

  template <typename Src>
  struct Wrapper<StrictNumeric<Src>> {
    static constexpr bool is_valid(const StrictNumeric<Src>) { return true; }
    static constexpr Src value(const StrictNumeric<Src> v) {
      return static_cast<Src>(v);
    }
  };
};

// Convenience functions to avoid the ugly template disambiguator syntax.
template <typename Dst, typename Src>
constexpr bool IsValidForType(const CheckedNumeric<Src> value) {
  return value.template IsValid<Dst>();
}

template <typename Dst, typename Src>
constexpr StrictNumeric<Dst> ValueOrDieForType(
    const CheckedNumeric<Src> value) {
  return value.template ValueOrDie<Dst>();
}

template <typename Dst, typename Src, typename Default>
constexpr StrictNumeric<Dst> ValueOrDefaultForType(
    const CheckedNumeric<Src> value,
    const Default default_value) {
  return value.template ValueOrDefault<Dst>(default_value);
}

// These variadic templates work out the return types.
// TODO(jschuh): Rip all this out once we have C++14 non-trailing auto support.
template <template <typename, typename, typename> class M,
          typename L,
          typename R,
          typename... Args>
struct ResultType;

template <template <typename, typename, typename> class M,
          typename L,
          typename R>
struct ResultType<M, L, R> {
  using type = typename MathWrapper<M, L, R>::type;
};

template <template <typename, typename, typename> class M,
          typename L,
          typename R,
          typename... Args>
struct ResultType {
  using type =
      typename ResultType<M, typename ResultType<M, L, R>::type, Args...>::type;
};

// Convience wrapper to return a new CheckedNumeric from the provided arithmetic
// or CheckedNumericType.
template <typename T>
constexpr CheckedNumeric<typename UnderlyingType<T>::type> MakeCheckedNum(
    const T value) {
  return value;
}

// These implement the variadic wrapper for the math operations.
template <template <typename, typename, typename> class M,
          typename L,
          typename R>
CheckedNumeric<typename MathWrapper<M, L, R>::type> ChkMathOp(const L lhs,
                                                              const R rhs) {
  using Math = typename MathWrapper<M, L, R>::math;
  return CheckedNumeric<typename Math::result_type>::template MathOp<M>(lhs,
                                                                        rhs);
}

// General purpose wrapper template for arithmetic operations.
template <template <typename, typename, typename> class M,
          typename L,
          typename R,
          typename... Args>
CheckedNumeric<typename ResultType<M, L, R, Args...>::type>
ChkMathOp(const L lhs, const R rhs, const Args... args) {
  auto tmp = ChkMathOp<M>(lhs, rhs);
  return tmp.IsValid() ? ChkMathOp<M>(tmp, args...)
                       : decltype(ChkMathOp<M>(tmp, args...))(tmp);
};

// The following macros are just boilerplate for the standard arithmetic
// operator overloads and variadic function templates. A macro isn't the nicest
// solution, but it beats rewriting these over and over again.
#define BASE_NUMERIC_ARITHMETIC_VARIADIC(NAME)                                \
  template <typename L, typename R, typename... Args>                         \
  CheckedNumeric<typename ResultType<Checked##NAME##Op, L, R, Args...>::type> \
      Check##NAME(const L lhs, const R rhs, const Args... args) {             \
    return ChkMathOp<Checked##NAME##Op, L, R, Args...>(lhs, rhs, args...);    \
  }

#define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP)               \
  /* Binary arithmetic operator for all CheckedNumeric operations. */          \
  template <typename L, typename R,                                            \
            typename std::enable_if<IsCheckedOp<L, R>::value>::type* =         \
                nullptr>                                                       \
  CheckedNumeric<typename MathWrapper<Checked##NAME##Op, L, R>::type>          \
  operator OP(const L lhs, const R rhs) {                                      \
    return decltype(lhs OP rhs)::template MathOp<Checked##NAME##Op>(lhs, rhs); \
  }                                                                            \
  /* Assignment arithmetic operator implementation from CheckedNumeric. */     \
  template <typename L>                                                        \
  template <typename R>                                                        \
  CheckedNumeric<L>& CheckedNumeric<L>::operator COMPOUND_OP(const R rhs) {    \
    return MathOp<Checked##NAME##Op>(rhs);                                     \
  }                                                                            \
  /* Variadic arithmetic functions that return CheckedNumeric. */              \
  BASE_NUMERIC_ARITHMETIC_VARIADIC(NAME)

BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, +=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Lsh, <<, <<=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Rsh, >>, >>=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(And, &, &=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Or, |, |=)
BASE_NUMERIC_ARITHMETIC_OPERATORS(Xor, ^, ^=)
BASE_NUMERIC_ARITHMETIC_VARIADIC(Max)
BASE_NUMERIC_ARITHMETIC_VARIADIC(Min)

#undef BASE_NUMERIC_ARITHMETIC_VARIADIC
#undef BASE_NUMERIC_ARITHMETIC_OPERATORS

// These are some extra StrictNumeric operators to support simple pointer
// arithmetic with our result types. Since wrapping on a pointer is always
// bad, we trigger the CHECK condition here.
template <typename L, typename R>
L* operator+(L* lhs, const StrictNumeric<R> rhs) {
  uintptr_t result = CheckAdd(reinterpret_cast<uintptr_t>(lhs),
                              CheckMul(sizeof(L), static_cast<R>(rhs)))
                         .template ValueOrDie<uintptr_t>();
  return reinterpret_cast<L*>(result);
}

template <typename L, typename R>
L* operator-(L* lhs, const StrictNumeric<R> rhs) {
  uintptr_t result = CheckSub(reinterpret_cast<uintptr_t>(lhs),
                              CheckMul(sizeof(L), static_cast<R>(rhs)))
                         .template ValueOrDie<uintptr_t>();
  return reinterpret_cast<L*>(result);
}

}  // namespace internal

using internal::CheckedNumeric;
using internal::IsValidForType;
using internal::ValueOrDieForType;
using internal::ValueOrDefaultForType;
using internal::MakeCheckedNum;
using internal::CheckMax;
using internal::CheckMin;
using internal::CheckAdd;
using internal::CheckSub;
using internal::CheckMul;
using internal::CheckDiv;
using internal::CheckMod;
using internal::CheckLsh;
using internal::CheckRsh;
using internal::CheckAnd;
using internal::CheckOr;
using internal::CheckXor;

}  // namespace base

#endif  // BASE_NUMERICS_SAFE_MATH_H_


text:
using Util.Ui.Builders;

namespace Util.Ui.Angular.Builders {
    /// <summary>
    /// router-outlet生成器
    /// </summary>
    public class RouterOutletBuilder : TagBuilder {
        /// <summary>
        /// 初始化router-outlet生成器
        /// </summary>
        public RouterOutletBuilder() : base( "router-outlet" ) {
        }
    }
}


text:
package cz.kec.wls.feedcombiner.beans;

import cz.kec.wls.feedcombiner.exceptions.WrongIntervalException;
import cz.kec.wls.feedcombiner.feeds.FeedUpdater;
import cz.kec.wls.feedcombiner.utils.DateUtils;
import cz.kec.wls.feedcombiner.utils.MockUtils;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Singleton EJB with configurable timer.
 * Running synchronization of all combined feeds in default interval 10 sec.
 * Interval is configurable, but not persistent.
 *
 * @author Daniel Kec <daniel at kecovi.cz>
 * @since Dec 9, 2014
 */
@Startup
@Singleton
public class RefreshFeedsTimerBean {
private final Logger LOG = LoggerFactory.getLogger(RefreshFeedsTimerBean.class);

public static final int DEFAULT_INTERVAL    = 10;
public static final int MIN_INTERVAL        = 3;
public static final int MAX_INTERVAL        = Integer.MAX_VALUE;

    @Resource
    TimerService timerService;
    private Timer timer;

    /** Interval of refresh in seconds */
    private int timeoutIntervalInSeconds = 10;//10 sec is default

    @PostConstruct
    public void initTimer(){
        LOG.info("Initializing timer {}",RefreshFeedsTimerBean.class.getName());
        long timeoutInMilis = timeoutIntervalInSeconds*1000;
        this.timer = timerService.createIntervalTimer(timeoutInMilis,timeoutInMilis,
                new TimerConfig("Current combined feed refresh timeout", false));
        //if there are no combined feeds at startup, creates set of mockup ones
        MockUtils.createMockFeeds();
    }

    @Timeout
    public void refreshFeedsTimer() {
        LOG.info("Automatically refreshing feeds. Next refresh {}",
                DateUtils.humanReadableDuration(new Date(),this.timer.getNextTimeout()));
        FeedUpdater.updateAll();
        LOG.info("Refreshing DONE!");
    }

    /**
     * Returns actual refresh interval in seconds.
     * @return refresh interval in seconds
     */
    public int getTimerIntervalInSeconds(){
        return this.timeoutIntervalInSeconds;
    }

    /**
     * Returns time left to the next refresh in seconds.
     * @return time to next refresh in seconds
     */
    public int getTimeLeft(){
        return (int) (this.timer.getTimeRemaining()/1000);
    }

    /**
     * Sets new interval betweet automatic combined feeds refresh.
     * @param intervalDuration interval in seconds
     * @throws WrongIntervalException if interval is not within 3-INT_MAX.
     */
    public void setTimerIntevalInSeconds(int intervalDuration) throws WrongIntervalException {
        if(intervalDuration < MIN_INTERVAL){
            throw new WrongIntervalException(MIN_INTERVAL,MAX_INTERVAL,intervalDuration);
        }
        LOG.info("Setting a programmatic timeout for {} seconds from now.",intervalDuration);
        this.timeoutIntervalInSeconds = intervalDuration;
        timer.cancel();
        initTimer();
    }

}


text:
package org.apache.geronimo.clustering;

/**
 *
 * @version $Rev$ $Date$
 */
public class SessionAlreadyExistException extends Exception {

    public SessionAlreadyExistException() {
        super();
    }

    public SessionAlreadyExistException(String message, Throwable cause) {
        super(message, cause);
    }

    public SessionAlreadyExistException(String message) {
        super(message);
    }

    public SessionAlreadyExistException(Throwable cause) {
        super(cause);
    }
}


text:
package org.jclouds.ecs.internal;

public abstract class BaseEcsApiExpectTest<T> extends BaseEcsExpectTest<T> {

}


text:
import _ from 'lodash'

export default {
  install: function (Vue) {
    Object.defineProperty(Vue.prototype, '$_', { value: _ })
  }
}


text:
import rados

# This utility will be enhanced as needed. It will need to be ran from a ceph node.

cluster = rados.Rados(conffile='')  # /etc/ceph/ceph.conf', conf=dict(keyring='/etc/ceph/ceph.client.admin.keyring'))
cluster.connect()

print "Ceph (librados) version: " + str(cluster.version())

cluster.create_pool('test-me')
print "\nCeph pools:"
pools = cluster.list_pools()
for pool in pools:
    print pool

cluster_stats = cluster.get_cluster_stats()

print "\nCluster stats:"
for key, value in cluster_stats.iteritems():
    print key, value

cluster.shutdown()


text:
$(function () {

  'use strict';

  var $image = $(window.createCropperImage());

  $image.on('cropstart.cropper', function (e) {

    QUnit.test('events.cropstart', function (assert) {
      assert.equal(e.type, 'cropstart');
      assert.equal(e.namespace, 'cropper');
      assert.equal(e.action, 'crop');
    });

  }).cropper({
    built: function () {
      var $dragBox = $image.data('cropper').$dragBox;

      // Triggers events manually when built
      $dragBox.trigger('mousedown').trigger('mouseup');
    },

    cropstart: function (e) {

      QUnit.test('options.cropstart', function (assert) {
        assert.equal(e.type, 'cropstart');
        assert.equal(e.namespace, 'cropper');
        assert.equal(e.action, 'crop');
      });

    }
  });

});


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using SonarScanner.MSBuild.Common;

namespace SonarScanner.MSBuild.Tasks
{
    /// <summary>
    /// Build task to return the Roslyn analyzer settings from the analysis config file
    /// </summary>
    public class GetAnalyzerSettings : Task
    {
        private const string DllExtension = ".dll";

        #region Input properties

        /// <summary>
        /// The directory containing the analysis config settings file
        /// </summary>
        [Required]
        public string AnalysisConfigDir { get; set; }

        /// <summary>
        /// List of additional files that would be passed to the compiler if
        /// no SonarQube analysis was happening.
        /// </summary>
        [Required]
        public string[] OriginalAdditionalFiles { get; set; }

        /// <summary>
        /// The language for which we are gettings the settings
        /// </summary>
        public string Language { get; set; }

        /// <summary>
        /// Path to the generated ruleset file to use
        /// </summary>
        [Output]
        public string RuleSetFilePath { get; private set; }

        /// <summary>
        /// List of analyzer assemblies and dependencies to pass to the compiler as analyzers
        /// </summary>
        [Output]
        public string[] AnalyzerFilePaths { get; private set; }

        /// <summary>
        /// List of additional files to pass to the compiler
        /// </summary>
        [Output]
        public string[] AdditionalFiles { get; private set; }

        /// <summary>
        /// List of additional files that are originally passed to the compiler,
        /// but <see cref="AdditionalFiles"/> contains an explicit override for them.
        /// </summary>
        [Output]
        public string[] AdditionalFilesToRemove { get; private set; }

        #endregion Input properties

        #region Overrides

        public override bool Execute()
        {
            var config = TaskUtilities.TryGetConfig(AnalysisConfigDir, new MSBuildLoggerAdapter(Log));
            ExecuteAnalysis(config);

            return !Log.HasLoggedErrors;
        }

        private void ExecuteAnalysis(AnalysisConfig config)
        {
            if (config == null || Language == null)
            {
                return;
            }

            IList<AnalyzerSettings> analyzers = config.AnalyzersSettings;
            if (analyzers == null)
            {
                Log.LogMessage(MessageImportance.Low, Resources.AnalyzerSettings_NotSpecifiedInConfig, Language);
                return;
            }

            var settings = analyzers.SingleOrDefault(s => Language.Equals(s.Language));
            if (settings == null)
            {
                Log.LogMessage(MessageImportance.Low, Resources.AnalyzerSettings_NotSpecifiedInConfig, Language);
                return;
            }

            RuleSetFilePath = settings.RuleSetFilePath;

            if (settings.AnalyzerAssemblyPaths != null)
            {
                AnalyzerFilePaths = settings.AnalyzerAssemblyPaths.Where(f => IsAssemblyLibraryFileName(f)).ToArray();
            }

            if (settings.AdditionalFilePaths != null)
            {
                AdditionalFiles = settings.AdditionalFilePaths.ToArray();

                var additionalFileNames = new HashSet<string>(
                    AdditionalFiles
                        .Select(af => GetFileName(af))
                        .Where(n => !string.IsNullOrEmpty(n)));

                AdditionalFilesToRemove = (OriginalAdditionalFiles ?? Enumerable.Empty<string>())
                    .Where(original => additionalFileNames.Contains(GetFileName(original)))
                    .ToArray();
            }
        }

        #endregion Overrides

        #region Private methods

        private static string GetFileName(string path)
        {
            try
            {
                return Path.GetFileName(path)?.ToUpperInvariant();
            }
            catch (ArgumentException)
            {
                return null;
            }
        }

        /// <summary>
        /// Returns whether the supplied string is an assembly library (i.e. dll)
        /// </summary>
        private static bool IsAssemblyLibraryFileName(string filePath)
        {
            // Not expecting .winmd or .exe files to contain Roslyn analyzers
            // so we'll ignore them
            return filePath.EndsWith(DllExtension, StringComparison.OrdinalIgnoreCase);
        }

        #endregion Private methods
    }
}


text:
<?php
/************************************************************************/
/* ATutor																*/
/************************************************************************/
/* Copyright (c) 2002-2010												*/
/* Inclusive Design Institute                                           */
/* http://atutor.ca                                                     */
/* This program is free software. You can redistribute it and/or        */
/* modify it under the terms of the GNU General Public License          */
/* as published by the Free Software Foundation.                        */
/************************************************************************/
define('AT_INCLUDE_PATH', 'include/');
require(AT_INCLUDE_PATH . 'vitals.inc.php');

// hack for eXe content, remove now
header ('content-type: text/css');
echo('@import url(exestyles.css);');
exit;

if (isset ($_GET['cid'])){
	$cid = intval ($_GET['cid']);

	$sql = "SELECT * FROM ".TABLE_PREFIX."head WHERE course_id=$_SESSION[course_id] AND content_id=$cid";
	$result = mysql_query($sql, $db);

	if (($result != 0) && ($row = mysql_fetch_assoc($result))){
		// get the CSS used
		$styleText = get_styles ($row['text'], $_GET['path']);

		header ('content-type: text/css');
		echo($styleText);
	}
}

// Takes the contents of the 'head' section and returns the 'style' and 'link' elements.
function get_styles ($headText, $path) {
	$styleText = '';

	// get the contents of all the 'style' elements
	$styleStartPos = strpos ($headText, '<style');
	while ($styleStartPos !== false) {

		// remove the start and end 'style' elements
		// (we're using just the contents of the 'style' element)
		$styleStartPos = strPos ($headText, '>', $styleStartPos) + 1;
		$styleEndPos = strPos ($headText, '</style', $styleStartPos) -1;

		// contents of 'style' element
		$tempString = substr ($headText, $styleStartPos, ($styleEndPos - $styleStartPos) + 1);

		// add full path to any 'import' statements
		$importStartPos = strpos ($tempString, '@import');
		if ($importStartPos !== false){
			$bracketStartPos = strpos ($tempString, '(', $importStartPos);
			if ($bracketStartPos !== false){
				$bracketEndPos = strpos ($tempString, ')', $bracketStartPos);
				if ($bracketEndPos !== false){
					$uriCss = trim (substr ($tempString, $bracketStartPos + 1, ($bracketEndPos - $bracketStartPos)));

					$tempString2 = substr ($tempString, '0', $bracketStartPos);
					$tempString = $tempString2.'('.$path.$uriCss.substr ($tempString, $bracketEndPos + '1');
				}
			}
		}

		$styleText = $styleText."\n".$tempString;

		// look for another 'style' element
		$styleStartPos = strpos ($headText, '<style', $styleEndPos);
	}

	// get all the links to external stylesheets
	$linkStartPos = strpos ($headText, '<link');
	while ($linkStartPos !== false) {
		$linkEndPos = strPos ($headText, '>', $linkStartPos);

		// ensure this is a 'stylesheet' link
		$stylesheetPos = strpos ($headText, "\"text/css\"", $linkStartPos);
		if (($stylesheetPos !== false) && ($stylesheetPos < $linkEndPos)){

			// get the 'href' attribute value
			$hrefPos = strpos ($headText, 'href', $linkStartPos);
			if ($hrefPos !== false){
				$hrefPos = strpos ($headText, '=', $hrefPos);
				if ($hrefPos !== false){
					$hrefPos += '1';

					// get first character in attribute value
					$index = $hrefPos;

					// find first attribute character
					while (($headText[$index] == " ") || ($headText[$index] == '\'') || ($headText[$index] == "\"")){
						$index++;
						if ($index > strlen($headText)){
							break;
						}
					}
					$indexStart = $index;

					// find end of attribute character
					$indexEnd = $indexStart;
					while (($headText[$indexEnd] != " ") && ($headText[$indexEnd] != '\'') && ($headText[$indexEnd] != "\"")){
						$indexEnd++;
						if ($index > strlen($headText)){
							break;
						}
					}
				}
			}

			// convert the href attribute value to an "import url" statement
			$importStatement = '@import url('.$path.substr ($headText, $indexStart, ($indexEnd - $indexStart)).');';
			$styleText = $styleText."\n".$importStatement;
		}

		// look for another 'link' element
		$linkStartPos = strpos ($headText, '<link', $linkEndPos);
	}
	return $styleText;
}
?>


text:
#pragma once
#include <aws/pinpoint/Pinpoint_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Pinpoint
{
namespace Model
{
  enum class Frequency
  {
    NOT_SET,
    ONCE,
    HOURLY,
    DAILY,
    WEEKLY,
    MONTHLY,
    EVENT
  };

namespace FrequencyMapper
{
AWS_PINPOINT_API Frequency GetFrequencyForName(const Aws::String& name);

AWS_PINPOINT_API Aws::String GetNameForFrequency(Frequency value);
} // namespace FrequencyMapper
} // namespace Model
} // namespace Pinpoint
} // namespace Aws


text:
package io.quarkus.it.smallrye.config;

import static io.restassured.RestAssured.given;
import static javax.ws.rs.core.Response.Status.OK;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class QuarkusConfigTest {
    @Test
    void uuid() {
        given()
                .get("/config/{name}", "quarkus.uuid")
                .then()
                .statusCode(OK.getStatusCode())
                .body("value", is(notNullValue()))
                .body("configSourceName", equalTo("DefaultValuesConfigSource"));

        given()
                .get("/config/uuid")
                .then()
                .statusCode(OK.getStatusCode())
                .body("value", is(notNullValue()))
                .body("configSourceName", equalTo("DefaultValuesConfigSource"));
    }
}


text:
/**
 *
 */
package net.brord.plugins.runescape.datastore.database;

import java.io.File;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Brord
 *
 */
public class SQLite extends DataBase{
    private String dbLocation;

    /**
     * Starts a new SQlite dataclass
     * @param dbLocation the location to read from. .db will be appended if it was not yet there
     */
	public SQLite(String dbLocation) {
		if (!dbLocation.endsWith(".db")) dbLocation += ".db";
        this.dbLocation = dbLocation;
    }

	@Override
	public String openConnection() {
		File file = new File(dbLocation);
        if (!(file.exists())) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                return "Unable to create database!";
            }
        }
        try {
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:" + dbLocation);
        } catch (SQLException e) {
            return "Could not connect to SQLite server! because: " + e.getMessage();
        } catch (ClassNotFoundException e) {
            return "JDBC Driver not found!";
        }
        return null;
	}
}


text:
@ECHO OFF

%MSBuildRoot%\msbuild.exe "runner.msbuild" /l:FileLogger,Microsoft.Build.Engine;logfile=runner.log /t:Rebuild;Test /p:Configuration=Debug
if "%1" NEQ "noprompt" PAUSE


text:
extern crate gfx_corell as core;
extern crate winit;
extern crate cocoa;
#[macro_use] extern crate objc;
extern crate io_surface;
extern crate core_foundation;
extern crate core_graphics;
#[macro_use] extern crate log;
#[macro_use] extern crate scopeguard;
extern crate block;

extern crate metal_rs as metal;

mod command;
mod factory;
mod native;
mod conversions;

pub use command::{QueueFamily, CommandQueue, CommandPool, RenderPassInlineEncoder};
pub use factory::{Factory};

pub type GraphicsCommandPool = CommandPool;

use std::str::FromStr;
use std::mem;
use std::marker::PhantomData;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use core::{format, memory};
use core::format::SurfaceType;
use core::format::ChannelType;
use metal::*;
use winit::os::macos::WindowExt;
use objc::runtime::{Object, Class};
use core_foundation::base::TCFType;
use core_foundation::string::{CFString, CFStringRef};
use core_foundation::dictionary::CFDictionary;
use core_foundation::number::{CFNumber, CFNumberRef};
use core_foundation::bundle::{CFBundleGetBundleWithIdentifier, CFBundleGetFunctionPointerForName};
use cocoa::base::{nil, YES};
use cocoa::appkit::{self, NSWindow, NSView, NSOpenGLPixelFormat, NSOpenGLContext};
use core_graphics::base::CGFloat;
use core_graphics::geometry::CGRect;
use io_surface::IOSurface;

pub struct Instance {
}

pub struct Adapter {
    device: MTLDevice,
    adapter_info: core::AdapterInfo,
    queue_families: [QueueFamily; 1],
}

impl Drop for Adapter {
    fn drop(&mut self) {
        unsafe { self.device.release(); }
    }
}

pub struct Surface(Rc<SurfaceInner>);

struct SurfaceInner {
    nsview: *mut Object,
    render_layer: RefCell<*mut Object>,
}

impl Drop for SurfaceInner {
    fn drop(&mut self) {
        unsafe { msg_send![self.nsview, release]; }
    }
}

pub struct SwapChain {
    surface: Rc<SurfaceInner>,
    pixel_width: u64,
    pixel_height: u64,

    io_surfaces: Vec<IOSurface>,
    images: Vec<native::Image>,
    frame_index: usize,
    present_index: usize,
}

impl Drop for SwapChain {
    fn drop(&mut self) {
        unsafe {
            for image in self.images.drain(..) {
                image.0.release();
            }
        }
    }
}

const SWAP_CHAIN_IMAGE_COUNT: usize = 3;

#[derive(Debug, Clone, Hash)]
pub enum Resources {}

impl core::Instance for Instance {
    type Adapter = Adapter;
    type Surface = Surface;
    type Window = winit::Window;

    fn create() -> Self {
        Instance {}
    }

    fn enumerate_adapters(&self) -> Vec<Self::Adapter> {
        // TODO: enumerate all devices

        let device = metal::create_system_default_device(); // Returns retained

        vec![Adapter {
            device,
            adapter_info: core::AdapterInfo {
                name: device.name().into(),
                vendor: 0,
                device: 0,
                software_rendering: false,
            },
            queue_families: [QueueFamily{}],
        }]
    }

    fn create_surface(&self, window: &winit::Window) -> Self::Surface {
        unsafe {
            let wnd: cocoa::base::id = mem::transmute(window.get_nswindow());

            let view = wnd.contentView();
            if view.is_null() {
                panic!("window does not have a valid contentView");
            }

            msg_send![view, setWantsLayer: YES];
            let render_layer: *mut Object = msg_send![Class::get("CALayer").unwrap(), new]; // Returns retained
            let view_size: CGRect = msg_send![view, bounds];
            msg_send![render_layer, setFrame: view_size];
            let view_layer: *mut Object = msg_send![view, layer];
            msg_send![view_layer, addSublayer: render_layer];

            msg_send![view, retain];
            Surface(Rc::new(SurfaceInner {
                nsview: view,
                render_layer: RefCell::new(render_layer),
            }))
        }
    }
}

impl core::Adapter for Adapter {
    type CommandQueue = CommandQueue;
    type QueueFamily = QueueFamily;
    type Factory = Factory;
    type Resources = Resources;

    fn open<'a, I>(&self, mut queue_descs: I) -> core::Device<Self::Resources, Self::Factory, Self::CommandQueue>
        where I: ExactSizeIterator<Item=(&'a Self::QueueFamily, u32)>
    {
        if queue_descs.len() != 1 {
            panic!("Metal only supports one queue family");
        }
        let (_, queue_count) = queue_descs.next().unwrap();

        let factory = factory::create_factory(self.device);
        let general_queues = (0..queue_count).map(|_| {
            unsafe { core::GeneralQueue::new(command::CommandQueue::new(self.device)) }
        }).collect();

        let heap_types;
        let memory_heaps;

        #[cfg(not(feature = "native_heap"))]
        {
            // TODO: heap types for each memory binding
            heap_types = vec![core::HeapType {
                id: 0,
                properties: memory::HeapProperties::all(),
                heap_index: 0,
            }];
            memory_heaps = Vec::new();
        }

        core::Device {
            factory,
            general_queues,
            graphics_queues: Vec::new(),
            compute_queues: Vec::new(),
            transfer_queues: Vec::new(),
            heap_types,
            memory_heaps,
            _marker: PhantomData,
        }
    }

    fn get_info(&self) -> &core::AdapterInfo {
        &self.adapter_info
    }

    fn get_queue_families(&self) -> std::slice::Iter<Self::QueueFamily> {
        self.queue_families.iter()
    }
}

impl core::Surface for Surface {
    type Queue = CommandQueue;
    type SwapChain = SwapChain;

    fn build_swapchain<T: format::RenderFormat>(&self, queue: &CommandQueue) -> SwapChain {
        let (mtl_format, cv_format) = match T::get_format() {
            format::Format(SurfaceType::R8_G8_B8_A8, ChannelType::Srgb) => (MTLPixelFormat::RGBA8Unorm_sRGB, native::kCVPixelFormatType_32RGBA),
            _ => panic!("unsupported backbuffer format"), // TODO: more formats
        };

        let render_layer_borrow = self.0.render_layer.borrow_mut();
        let render_layer = *render_layer_borrow;
        let nsview = self.0.nsview;

        unsafe {
            // Update render layer size
            let view_points_size: CGRect = msg_send![nsview, bounds];
            msg_send![render_layer, setBounds: view_points_size];
            let view_window: *mut Object = msg_send![nsview, window];
            if view_window.is_null() {
                panic!("surface is not attached to a window");
            }
            let scale_factor: CGFloat = msg_send![view_window, backingScaleFactor];
            msg_send![render_layer, setContentsScale: scale_factor];
            let pixel_width = (view_points_size.size.width * scale_factor) as u64;
            let pixel_height = (view_points_size.size.height * scale_factor) as u64;
            let pixel_size = conversions::get_format_bytes_per_pixel(mtl_format) as u64;

            info!("allocating {} IOSurface backbuffers of size {}x{} with pixel format 0x{:x}", SWAP_CHAIN_IMAGE_COUNT, pixel_width, pixel_height, cv_format);
            // Create swap chain surfaces
            let io_surfaces: Vec<_> = (0..SWAP_CHAIN_IMAGE_COUNT).map(|_| {
                io_surface::new(&CFDictionary::from_CFType_pairs::<CFStringRef, CFNumberRef, CFString, CFNumber>(&[
                    (TCFType::wrap_under_get_rule(io_surface::kIOSurfaceWidth), CFNumber::from_i32(pixel_width as i32)),
                    (TCFType::wrap_under_get_rule(io_surface::kIOSurfaceHeight), CFNumber::from_i32(pixel_height as i32)),
                    (TCFType::wrap_under_get_rule(io_surface::kIOSurfaceBytesPerRow), CFNumber::from_i32((pixel_width * pixel_size) as i32)),
                    (TCFType::wrap_under_get_rule(io_surface::kIOSurfaceBytesPerElement), CFNumber::from_i32(pixel_size as i32)),
                    (TCFType::wrap_under_get_rule(io_surface::kIOSurfacePixelFormat), CFNumber::from_i32(cv_format as i32)),
                ]))
            }).collect();

            let device = queue.device();

            let backbuffer_descriptor = MTLTextureDescriptor::new();
            defer! { backbuffer_descriptor.release() };
            backbuffer_descriptor.set_pixel_format(mtl_format);
            backbuffer_descriptor.set_width(pixel_width as u64);
            backbuffer_descriptor.set_height(pixel_height as u64);
            backbuffer_descriptor.set_usage(MTLTextureUsageRenderTarget);

            let images = io_surfaces.iter().map(|surface| {
                let mapped_texture: MTLTexture = msg_send![device.0, newTextureWithDescriptor: backbuffer_descriptor.0 iosurface: surface.obj plane: 0];
                native::Image(mapped_texture)
            }).collect();

            SwapChain {
                surface: self.0.clone(),
                pixel_width,
                pixel_height,

                io_surfaces,
                images,
                frame_index: 0,
                present_index: 0,
            }
        }
    }
}

impl core::SwapChain for SwapChain {
    type R = Resources;
    type Image = native::Image;

    fn get_images(&mut self) -> &[native::Image] {
        &self.images
    }

    fn acquire_frame(&mut self, sync: core::FrameSync<Resources>) -> core::Frame {
        unsafe {
            match sync {
                core::FrameSync::Semaphore(semaphore) => {
                    // FIXME: this is definitely wrong
                    native::dispatch_semaphore_signal(semaphore.0);
                },
                core::FrameSync::Fence(_fence) => unimplemented!(),
            }

            let frame = core::Frame::new(self.frame_index % self.images.len());
            self.frame_index += 1;
            frame
        }
    }

    fn present(&mut self) {
        let buffer_index = self.present_index % self.io_surfaces.len();

        unsafe {
            let io_surface = &mut self.io_surfaces[buffer_index];
            let render_layer_borrow = self.surface.render_layer.borrow_mut();
            let render_layer = *render_layer_borrow;
            msg_send![render_layer, setContents: io_surface.obj];
        }

        self.present_index += 1;
    }
}

impl core::Resources for Resources {
    type ShaderLib = native::ShaderLib;
    type RenderPass = native::RenderPass;
    type PipelineLayout = native::PipelineLayout;
    type FrameBuffer = native::FrameBuffer;
    type GraphicsPipeline = native::GraphicsPipeline;
    type ComputePipeline = native::ComputePipeline;
    type UnboundBuffer = native::UnboundBuffer;
    type Buffer = native::Buffer;
    type UnboundImage = native::UnboundImage;
    type Image = native::Image;
    type ConstantBufferView = native::ConstantBufferView;
    type ShaderResourceView = native::ShaderResourceView;
    type UnorderedAccessView = native::UnorderedAccessView;
    type RenderTargetView = native::RenderTargetView;
    type DepthStencilView = native::DepthStencilView;
    type Sampler = native::Sampler;
    type Semaphore = native::Semaphore;
    type Fence = native::Fence;
    type Heap = native::Heap;
    type Mapping = native::Mapping;
    type DescriptorHeap = native::DescriptorHeap;
    type DescriptorSetPool = native::DescriptorSetPool;
    type DescriptorSet = native::DescriptorSet;
    type DescriptorSetLayout = native::DescriptorSetLayout;

}


text:
package com.navercorp.pinpoint.profiler.context;

import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.navercorp.pinpoint.bootstrap.context.AsyncTraceId;
import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder;
import com.navercorp.pinpoint.bootstrap.context.SpanRecorder;
import com.navercorp.pinpoint.bootstrap.context.Trace;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.context.TraceId;
import com.navercorp.pinpoint.bootstrap.context.TraceType;
import com.navercorp.pinpoint.exception.PinpointException;
import com.navercorp.pinpoint.profiler.context.storage.Storage;

/**
 * @author netspider
 * @author emeroad
 * @author jaehong.kim
 */
public final class DefaultTrace implements Trace {
    private static final Logger logger = LoggerFactory.getLogger(DefaultTrace.class.getName());
    private static final boolean isTrace = logger.isTraceEnabled();
    private static final boolean isWarn = logger.isWarnEnabled();

    private final boolean sampling;

    private final TraceId traceId;

    private final CallStack callStack;

    private Storage storage;

    private final TraceContext traceContext;
    private TraceType traceType = TraceType.DEFAULT;
    private final WrappedSpanEventRecorder spanEventRecorder;
    private final DefaultSpanRecorder spanRecorder;
    private boolean closed = false;

    private Thread bindThread;

    public DefaultTrace(final TraceContext traceContext, long transactionId, boolean sampling) {
        if (traceContext == null) {
            throw new NullPointerException("traceContext must not be null");
        }
        this.traceContext = traceContext;
        this.traceId = new DefaultTraceId(traceContext.getAgentId(), traceContext.getAgentStartTime(), transactionId);
        this.sampling = sampling;

        final Span span = createSpan();
        this.spanRecorder = new DefaultSpanRecorder(traceContext, span, traceId, sampling);
        this.spanRecorder.recordTraceId(traceId);
        this.spanEventRecorder = new WrappedSpanEventRecorder(traceContext);
        this.callStack = createCallStack(traceContext.getProfilerConfig(), span);
        setCurrentThread();
    }

    public DefaultTrace(TraceContext traceContext, TraceId continueTraceId, boolean sampling) {
        if (traceContext == null) {
            throw new NullPointerException("traceContext must not be null");
        }
        if (continueTraceId == null) {
            throw new NullPointerException("continueTraceId must not be null");
        }
        this.traceContext = traceContext;
        this.traceId = continueTraceId;
        this.sampling = sampling;

        final Span span = createSpan();
        this.spanRecorder = new DefaultSpanRecorder(traceContext, span, traceId, sampling);
        this.spanRecorder.recordTraceId(traceId);
        this.spanEventRecorder = new WrappedSpanEventRecorder(traceContext);
        this.callStack = createCallStack(traceContext.getProfilerConfig(), span);
        setCurrentThread();
    }

    private CallStack createCallStack(ProfilerConfig profilerConfig, Span span) {
        if (profilerConfig != null) {
            final int maxCallStackDepth = profilerConfig.getCallStackMaxDepth();
            return new CallStack(span, maxCallStackDepth);
        } else {
            return new CallStack(span);
        }
    }

    private Span createSpan() {
        Span span = new Span();
        span.setAgentId(traceContext.getAgentId());
        span.setApplicationName(traceContext.getApplicationName());
        span.setAgentStartTime(traceContext.getAgentStartTime());
        span.setApplicationServiceType(traceContext.getServerTypeCode());
        span.markBeforeTime();

        return span;
    }

    private SpanEventRecorder wrappedSpanEventRecorder(SpanEvent spanEvent) {
        final WrappedSpanEventRecorder spanEventRecorder = this.spanEventRecorder;
        spanEventRecorder.setWrapped(spanEvent);
        return spanEventRecorder;
    }

    public void setStorage(Storage storage) {
        this.storage = storage;
    }

    @Override
    public SpanEventRecorder traceBlockBegin() {
        return traceBlockBegin(DEFAULT_STACKID);
    }

    @Override
    public SpanEventRecorder traceBlockBegin(final int stackId) {
        // Set properties for the case when stackFrame is not used as part of Span.
        final SpanEvent spanEvent = new SpanEvent(spanRecorder.getSpan());
        spanEvent.markStartTime();
        spanEvent.setStackId(stackId);

        if (this.closed) {
            if (isWarn) {
                PinpointException exception = new PinpointException("already closed trace.");
                logger.warn("[DefaultTrace] Corrupted call stack found.", exception);
            }
        } else {
            callStack.push(spanEvent);
        }

        return wrappedSpanEventRecorder(spanEvent);
    }

    @Override
    public void traceBlockEnd() {
        traceBlockEnd(DEFAULT_STACKID);
    }

    @Override
    public void traceBlockEnd(int stackId) {
        if (this.closed) {
            if (isWarn) {
                final PinpointException exception = new PinpointException("already closed trace.");
                logger.warn("[DefaultTrace] Corrupted call stack found.", exception);
            }
            return;
        }

        final SpanEvent spanEvent = callStack.pop();
        if (spanEvent == null) {
            if (isWarn) {
                PinpointException exception = new PinpointException("call stack is empty.");
                logger.warn("[DefaultTrace] Corrupted call stack found.", exception);
            }
            return;
        }

        if (spanEvent.getStackId() != stackId) {
            // stack dump will make debugging easy.
            if (isWarn) {
                PinpointException exception = new PinpointException("not matched stack id. expected=" + stackId + ", current=" + spanEvent.getStackId());
                logger.warn("[DefaultTrace] Corrupted call stack found.", exception);
            }
        }

        if (spanEvent.isTimeRecording()) {
            spanEvent.markAfterTime();
        }
        logSpan(spanEvent);
    }

    @Override
    public void close() {
        if (closed) {
            logger.warn("Already closed trace.");
            return;
        }
        closed = true;

        if (!callStack.empty()) {
            if (isWarn) {
                PinpointException exception = new PinpointException("not empty call stack.");
                logger.warn("[DefaultTrace] Corrupted call stack found.", exception);
            }
            // skip
        } else {
            Span span = spanRecorder.getSpan();
            if (span.isTimeRecording()) {
                span.markAfterTime();
            }
            logSpan(span);
        }

        // If the stack is not handled properly, NullPointerException will be thrown after this. Is it OK?
        if (this.storage != null) {
            this.storage.close();
            this.storage = null;
        }
    }

    /**
     * Get current TraceID. If it was not set this will return null.
     *
     * @return
     */
    @Override
    public TraceId getTraceId() {
        return this.traceId;
    }

    @Override
    public long getId() {
        return traceId.getTransactionSequence();
    }

    @Override
    public long getStartTime() {
        final DefaultSpanRecorder copy = this.spanRecorder;
        if (copy == null) {
            return 0;
        }
        return copy.getSpan().getStartTime();
    }

    @Override
    public Thread getBindThread() {
        return bindThread;
    }

    private void setCurrentThread() {
        this.setBindThread(Thread.currentThread());
    }

    private void setBindThread(Thread thread) {
        bindThread = thread;
    }

    public boolean canSampled() {
        return this.sampling;
    }

    public boolean isRoot() {
        return getTraceId().isRoot();
    }

    private void logSpan(SpanEvent spanEvent) {
        if (isTrace) {
            final Thread th = Thread.currentThread();
            logger.trace("[DefaultTrace] Write {} thread{id={}, name={}}", spanEvent, th.getId(), th.getName());
        }
        this.storage.store(spanEvent);
    }

    private void logSpan(Span span) {
        if (isTrace) {
            final Thread th = Thread.currentThread();
            logger.trace("[DefaultTrace] Write {} thread{id={}, name={}}", span, th.getId(), th.getName());
        }
        this.storage.store(span);
    }

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean isRootStack() {
        return callStack.empty();
    }

    @Override
    public AsyncTraceId getAsyncTraceId() {
        return new DefaultAsyncTraceId(traceId, traceContext.getAsyncId(), spanRecorder.getSpan().getStartTime());
    }

    @Override
    public SpanRecorder getSpanRecorder() {
        return spanRecorder;
    }

    @Override
    public SpanEventRecorder currentSpanEventRecorder() {
        SpanEvent spanEvent = callStack.peek();
        if (spanEvent == null) {
            if (isWarn) {
                PinpointException exception = new PinpointException("call stack is empty");
                logger.warn("[DefaultTrace] Corrupted call stack found.", exception);
            }
            // make dummy.
            spanEvent = new SpanEvent(spanRecorder.getSpan());
        }

        return wrappedSpanEventRecorder(spanEvent);
    }

    @Override
    public int getCallStackFrameId() {
        if (callStack.empty()) {
            return ROOT_STACKID;
        }

        final SpanEvent spanEvent = callStack.peek();
        return spanEvent.getStackId();
    }

    @Override
    public TraceType getTraceType() {
        return this.traceType;
    }

    public void setTraceType(TraceType traceType) {
        this.traceType = traceType;
    }
}


text:
package org.nd4j.linalg.api.ops.impl.transforms;

import lombok.val;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.BaseTransformOp;
import org.nd4j.linalg.factory.Nd4j;
import org.tensorflow.framework.AttrValue;
import org.tensorflow.framework.GraphDef;
import org.tensorflow.framework.NodeDef;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Pow function
 *
 * @author Adam Gibson
 */
public class Pow extends BaseTransformOp {
    private double pow;

    public Pow() {
    }

    public Pow(SameDiff sameDiff, SDVariable i_v, boolean inPlace, double pow) {
        super(sameDiff, i_v, inPlace);
        this.pow = pow;
        this.extraArgs = new Object[]{pow};
    }

    public Pow(SameDiff sameDiff, SDVariable i_v, long[] shape, boolean inPlace, Object[] extraArgs, double pow) {
        super(sameDiff, i_v, shape, inPlace, extraArgs);
        this.pow = pow;
        this.extraArgs = new Object[]{pow};
    }

    public Pow(SameDiff sameDiff, SDVariable i_v, Object[] extraArgs, double pow) {
        super(sameDiff, i_v, extraArgs);
        this.pow = pow;
        this.extraArgs = new Object[]{pow};
    }

    public Pow(INDArray x, INDArray z, double pow) {
        super(x, z);
        this.pow = pow;
        init(x, null, z, x.lengthLong());
    }

    public Pow(INDArray x, INDArray z, long n, double pow) {
        super(x, z, n);
        this.pow = pow;
        init(x, null, z, n);

    }

    public Pow(INDArray x, INDArray y, INDArray z, long n, double pow) {
        super(x, y, z, n);
        this.pow = pow;
        init(x, y, z, n);

    }

    public Pow(INDArray x, double pow) {
        super(x);
        this.pow = pow;
        init(x, null, x, x.lengthLong());
    }

    @Override
    public int opNum() {
        return 7;
    }

    @Override
    public String opName() {
        return "pow";
    }

    @Override
    public void init(INDArray x, INDArray y, INDArray z, long n) {
        super.init(x, y, z, n);
        this.extraArgs = new Object[]{pow};
    }

    @Override
    public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) {
        val weightsName = nodeDef.getInput(1);
        val variable = initWith.getVariable(weightsName);
        val tmp = initWith.getArrForVarName(weightsName);

        // if second argument is scalar - we should provide array of same shape
        if (tmp != null) {
            if (tmp.isScalar()) {
                this.pow = tmp.getDouble(0);
            }
        }
    }

    @Override
    public String onnxName() {
        return "Pow";
    }

    @Override
    public String tensorflowName() {
        return "Pow";
    }

    @Override
    public List<SDVariable> doDiff(List<SDVariable> i_v1) {
        SDVariable g = f().powDerivative(arg(), this.pow).mul(i_v1.get(0));
        return Arrays.asList(g);
    }

}


text:
@interface PodsDummy_Pods_CoreDataPlatform : NSObject
@end
@implementation PodsDummy_Pods_CoreDataPlatform
@end


text:
From 8.0.0 release and beyond, release notes are published on
[docs.openstack.org](https://docs.openstack.org/releasenotes/puppet-gnocchi/).

##2015-11-25 - 7.0.0
###Summary

- Initial release of the puppet-gnocchi module


text:
<!DOCTYPE HTML>

<title>DatabaseBulkQueryable (Fluent JDBC library 0.2.2-SNAPSHOT API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2021-05-22">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package org.fluentjdbc

Interface DatabaseBulkQueryable<ENTITY,SELF extends DatabaseBulkQueryable<ENTITY,SELF>>

All Known Implementing Classes:

DatabaseBulkDeleteBuilder, DatabaseBulkUpdateBuilder, DbContextBulkDeleteBuilder, DbContextBulkUpdateBuilder

public interface DatabaseBulkQueryable<ENTITY,SELF extends DatabaseBulkQueryable<ENTITY,SELF>>

Fluently create a statement for a list of objects with a WHERE ... clause,
 such as UPDATE  or DELETE

Method Summary

All Methods Instance Methods Abstract Methods Default Methods

Modifier and Type
Method
Description

SELF
where(String field,
     Function<ENTITY,?> value)

Adds a function that will be called for each object to get the value for
 PreparedStatement.setObject(int, Object) for each row in the bulk update
 to extract the values for the SET fieldName = ? clause

default SELF
whereAll(List<String> fields,
        Function<ENTITY,List<?>> values)

Adds a list of functions that will be called for each object to get the value for
 PreparedStatement.setObject(int, Object) for each row in the bulk update
 to extract the values for the SET fieldName1 = ?, fieldName2 = ?, ... clause

Method Detail

where

@CheckReturnValue
SELF where(String field,
           Function<ENTITY,?> value)

Adds a function that will be called for each object to get the value for
 PreparedStatement.setObject(int, Object) for each row in the bulk update
 to extract the values for the SET fieldName = ? clause

whereAll

@CheckReturnValue
default SELF whereAll(List<String> fields,
                      Function<ENTITY,List<?>> values)

Adds a list of functions that will be called for each object to get the value for
 PreparedStatement.setObject(int, Object) for each row in the bulk update
 to extract the values for the SET fieldName1 = ?, fieldName2 = ?, ... clause

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2021. All rights reserved.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center">

    <RelativeLayout
        android:id="@+id/Search_the_user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/search_the_user_image"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_margin="15dp"
            android:src="@drawable/search_the_user" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/search_the_user_image"
            android:text="搜索好友"
            android:textSize="20dip" />

        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_margin="15dp"
            android:src="@drawable/setting_arrow_in" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/Invite_friends"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/Invite_friends_image"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_margin="15dp"
            android:src="@drawable/invite_friends" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/Invite_friends_image"
            android:text="邀请好友"
            android:textSize="20dip" />

        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_margin="15dp"
            android:src="@drawable/setting_arrow_in" />
    </RelativeLayout>
</LinearLayout>


text:
package org.apache.jena.shacl.engine;

import java.util.Collection;
import java.util.function.BiFunction;

import org.apache.jena.atlas.lib.InternalErrorException;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Node;
import org.apache.jena.shacl.lib.ShLib;

public class Target {

    public static Target create(Node node, TargetType targetType, Node targetObj, Graph shapesGraph) {
        BiFunction<Graph, Target, Collection<Node>> focusNodes = focusNodeFunction(targetType);
        return new Target(targetType, targetObj, shapesGraph, focusNodes);
    }

    private static BiFunction<Graph, Target, Collection<Node>> focusNodeFunction(TargetType targetType) {
        switch(targetType) {
            case implicitClass :    return TargetOps::focusImplicitClass;
            case targetClass :      return TargetOps::focusTargetClass;
            case targetNode :       return TargetOps::focusTargetNode;
            case targetSubjectsOf : return TargetOps::focusSubjectsOf;
            case targetObjectsOf :  return TargetOps::focusObjectsOf;
            case targetExtension :  return TargetOps::focusTargetExt;
            default:
                throw new InternalErrorException();
        }
    }

    private TargetType targetType;
    private Node node;
    private Graph shapesGraph;
    private BiFunction<Graph, Target, Collection<Node>> focusNodes;

    public Target(TargetType decl, Node obj, Graph shapesGraph, BiFunction<Graph, Target, Collection<Node>> focusNodes) {
        this.targetType = decl;
        this.node = obj;
        this.shapesGraph = shapesGraph;
        this.focusNodes = focusNodes;
    }

    public TargetType getTargetType() {
        return targetType;
    }

    public Node getObject() {
        return node;
    }

    public Collection<Node> getFocusNodes(Graph data) {
        return focusNodes.apply(data, this);
    }

    /**
     * Some targets need access to the shape graph - for example, SPARQL targets.
     * This is null if the target type does not need access.
     */
    public Graph getShapesGraph() {
        return shapesGraph;
    }

    @Override
    public String toString() {
        return getTargetType().name()+"["+ShLib.displayStr(getObject())+"]";
    }
}


text:
from response import ResponseObj
from request import RequestObjNew
import tornado.web
import tornado.gen
import tornado.ioloop
import tornado.concurrent
import tornado.httpclient
import logging
import asyncio
from easyspid.handlers.easyspidhandler import easyspidHandler
import globalsObj
import easyspid.lib.easyspid
from easyspid.lib.utils import Saml2_Settings, waitFuture
import commonlib

class validateAssertiondHandler(easyspidHandler):

    def __init__(self, *args, **kwds):
        super().__init__(*args, **kwds)

    #post
    async def post(self):
        x_real_ip = self.request.headers.get(globalsObj.easyspid_originIP_header)
        self.remote_ip = x_real_ip or self.request.remote_ip
        self.set_header('Content-Type', 'application/json; charset=UTF-8')
        self.set_default_headers()

        #settings
        response_obj = await asyncio.get_event_loop().run_in_executor(self.executor, self.validateAssertion)

        asyncio.ensure_future(self.writeLog(response_obj), loop = globalsObj.ioloop)
        super().writeResponse(response_obj)

    @commonlib.inner_log
    def validateAssertion(self):

        try:

            temp = RequestObjNew(self.request.body)
            if temp.error["code"] == 2:
                response_obj = ResponseObj(debugMessage=temp.error["message"], httpcode=400)
                response_obj.setError('400')
                logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('Validation error. Json input error')
                return response_obj

            elif temp.error["code"] > 0:
                raise tornado.web.HTTPError(httpcode=503, log_message=temp.error["message"])

            prvd = temp.request['provider']
            assertion = temp.request['assertion']

            if prvd != "":
                task  = asyncio.run_coroutine_threadsafe(self.dbobjSaml.execute_statment("get_signature('%s')" % prvd), globalsObj.ioloop)
                #assert not task.done()
                #prvdSignature = task.result()
                prvdSignature = easyspid.lib.utils.waitFuture(task)

                if prvdSignature['error'] == 0 and prvdSignature['result'] is not None:
                    certFingerprint = prvdSignature['result'][0]['fingerprint']
                    certFingerprintalg = prvdSignature['result'][0]['fingerprintalg']

                elif prvdSignature['error'] == 0 and prvdSignature['result'] is None:
                    response_obj = ResponseObj(httpcode=404)
                    response_obj.setError('easyspid112')
                    return response_obj

                elif prvdSignature['error'] > 0:
                    response_obj = ResponseObj(httpcode=500, debugMessage=prvdSignature['result'])
                    response_obj.setError("easyspid105")
                    return response_obj

            elif prvd == "":
                certFingerprint = None
                certFingerprintalg = None

            chk = easyspid.lib.utils.validateAssertion(assertion, fingerprint=certFingerprint, fingerprintalg=certFingerprintalg)

            if not chk['schemaValidate']:
                response_obj = ResponseObj(httpcode=401)
                response_obj.setError('easyspid104')
                response_obj.setResult(assertionChk = chk)

            elif chk['assertionName'] == 'AuthnRequest' and chk['signCheck'] is None:
                response_obj = ResponseObj(httpcode=200)
                response_obj.setError('easyspid119')
                response_obj.setResult(assertionChk = chk)

            elif not chk['signCheck']:
                response_obj = ResponseObj(httpcode=401)
                response_obj.setError('easyspid106')
                response_obj.setResult(assertionChk = chk)

            elif chk['schemaValidate'] and chk['signCheck']:
                response_obj = ResponseObj(httpcode=200)
                response_obj.setError('200')
                response_obj.setResult(assertionChk = chk)

        except tornado.web.MissingArgumentError as error:
            response_obj = ResponseObj(debugMessage=error.log_message, httpcode=error.status_code,
                                       devMessage=error.log_message)
            response_obj.setError(str(error.status_code))
            logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('%s'% error,exc_info=True)

        except Exception as inst:
            response_obj = ResponseObj(httpcode=500, debugMessage=inst)
            response_obj.setError('500')
            logging.getLogger(type(self).__module__+"."+type(self).__qualname__).error('Exception',exc_info=True)

        response_obj.setID(temp.id)
        return response_obj


text:
<button id="btn_start_animation" class="btn btn-primary">Start Animation</button>

Purpose: Search minimum value of the given test function below throughout the given space,  x = [-15, 15] and y = [-15, 15]. Total Iteration: 50

Test function =(0.007 * x * (-y - 1)) * (cos(x + 0.3) - sin(y))+(1 - sin(x))

Iteration:

Visualization of Test Function with Matlab

<input id="btn_animation" type="button" value="Click Me">

Test