text:
"""Data augmentation lib for the Liver Tumor Segmentation (LiTS) dataset.

A set of data augmentation functions.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.compat.v1 as tf
import tensorflow_probability as tfp
from tensorflow.contrib import image as contrib_image

def _truncated_normal(mean, stddev):
  v = tf.random.normal(shape=[], mean=mean, stddev=stddev)
  v = tf.clip_by_value(v, -2 * stddev + mean, 2 * stddev + mean)
  return v

def _rand_noise(noise_mean, noise_dev, scale, shape):
  """Generate random noise given a particular scale and shape."""
  noise_shape = [x // scale for x in shape]
  noise_shape = [1 if x == 0 else x for x in noise_shape]
  noise = tf.random.normal(
      shape=noise_shape, mean=noise_mean, stddev=noise_dev)
  noise = tf.clip_by_value(
      noise, noise_mean - 2.0 * noise_dev, noise_mean + 2.0 * noise_dev)

  if scale != 1:
    noise = tf.image.resize_images(
        noise, [shape[0], shape[1]])
    noise = tf.transpose(noise, [0, 2, 1])
    noise = tf.image.resize_images(
        noise, [shape[0], shape[2]])
    noise = tf.transpose(noise, [0, 2, 1])
  return noise

def projective_transform(
    image, label, reso, image_translate_ratio, image_transform_ratio,
    sampled_2d_slices=False):
  """Apply projective transformation on image and label."""

  if image_translate_ratio < 0.000001 and (
      image_transform_ratio < 0.000001):
    return image, label

  def _projective_transform(data, proj_matrix, static_axis, interpolation):
    """Apply projective transformation."""
    if static_axis == 2:
      data = contrib_image.transform(data, proj_matrix, interpolation)
    elif static_axis == 1:
      data = tf.transpose(data, [0, 2, 1])
      data = contrib_image.transform(data, proj_matrix, interpolation)
      data = tf.transpose(data, [0, 2, 1])
    else:
      data = tf.transpose(data, [2, 1, 0])
      data = contrib_image.transform(data, proj_matrix, interpolation)
      data = tf.transpose(data, [2, 1, 0])
    return data

  for static_axis in [0, 1, 2]:
    if sampled_2d_slices and static_axis != 2:
      continue
    a0 = _truncated_normal(1.0, image_transform_ratio)
    a1 = _truncated_normal(0.0, image_transform_ratio)
    a2 = _truncated_normal(
        0.0, image_translate_ratio * reso)
    b0 = _truncated_normal(0.0, image_transform_ratio)
    b1 = _truncated_normal(1.0, image_transform_ratio)
    b2 = _truncated_normal(
        0.0, image_translate_ratio * reso)
    c0 = _truncated_normal(0.0, image_transform_ratio)
    c1 = _truncated_normal(0.0, image_transform_ratio)
    proj_matrix = [a0, a1, a2, b0, b1, b2, c0, c1]

    image = _projective_transform(image, proj_matrix, static_axis, 'BILINEAR')
    label = _projective_transform(label, proj_matrix, static_axis, 'NEAREST')

  return image, label

def maybe_add_noise(image, noise_shape, scale0, scale1,
                    image_noise_probability, image_noise_ratio):
  """Add noise at two scales."""

  if image_noise_probability < 0.000001 or (
      image_noise_ratio < 0.000001):
    return image

  noise_list = []
  for scale in [scale0, scale1]:
    rand_image_noise_ratio = tf.random.uniform(
        shape=[], minval=0.0, maxval=image_noise_ratio)
    noise_list.append(
        _rand_noise(0.0, rand_image_noise_ratio, scale, noise_shape))

  skip_noise = tf.greater(tf.random.uniform([]), image_noise_probability)
  image = tf.cond(skip_noise,
                  lambda: image, lambda: image + noise_list[0])
  image = tf.cond(skip_noise,
                  lambda: image, lambda: image + noise_list[1])

  return image

def _gen_rand_mask(ratio_mean, ratio_stddev, scale, shape, smoothness=0):
  """Generate a binary mask."""
  scale = max(scale, 1)

  ratio = tf.random.normal(
      shape=[], mean=ratio_mean, stddev=ratio_stddev)
  low_bound = tf.maximum(0.0, ratio_mean - 2 * ratio_stddev)
  up_bound = tf.minimum(1.0, ratio_mean + 2 * ratio_stddev)
  percentil_q = tf.cast(
      100.0 * tf.clip_by_value(ratio, low_bound, up_bound),
      tf.int32)

  pattern = _rand_noise(0.0, 1.0, scale, shape)
  if smoothness > 0:
    smoothness = int(smoothness) // 2 * 2 + 1
    pattern = tf.expand_dims(tf.expand_dims(pattern, 0), -1)
    pattern = tf.nn.conv3d(
        pattern, filter=tf.ones([smoothness, smoothness, smoothness, 1, 1]),
        strides=[1, 1, 1, 1, 1], padding='SAME', dilations=[1, 1, 1, 1, 1])
    pattern = tf.reduce_sum(pattern, 0)
    pattern = tf.reduce_sum(pattern, -1)

  thres = tfp.stats.percentile(pattern, q=percentil_q)
  rand_mask = tf.less(pattern, thres)

  return rand_mask

def maybe_gen_fake_data_based_on_real_data(
    image, label, reso, min_fake_lesion_ratio, gen_fake_probability):
  """Remove real lesion and synthesize lesion."""
  # TODO(lehou): Replace magic numbers with flag variables.
  gen_prob_indicator = tf.random_uniform(
      shape=[], minval=0.0, maxval=1.0, dtype=tf.float32)

  background_mask = tf.less(label, 0.5)
  lesion_mask = tf.greater(label, 1.5)
  liver_mask = tf.logical_not(tf.logical_or(background_mask, lesion_mask))

  liver_intensity = tf.boolean_mask(image, liver_mask)
  lesion_intensity = tf.boolean_mask(image, lesion_mask)

  intensity_diff = tf.reduce_mean(liver_intensity) - (
      tf.reduce_mean(lesion_intensity))
  intensity_diff *= 1.15
  intensity_diff = tf.cond(tf.is_nan(intensity_diff),
                           lambda: 0.0, lambda: intensity_diff)

  lesion_liver_ratio = 0.0
  lesion_liver_ratio += tf.random.normal(shape=[], mean=0.01, stddev=0.01)
  lesion_liver_ratio += tf.random.normal(shape=[], mean=0.0, stddev=0.05)
  lesion_liver_ratio = tf.clip_by_value(
      lesion_liver_ratio, min_fake_lesion_ratio, min_fake_lesion_ratio + 0.20)

  fake_lesion_mask = tf.logical_and(
      _gen_rand_mask(ratio_mean=lesion_liver_ratio, ratio_stddev=0.0,
                     scale=reso // 32, shape=label.shape,
                     smoothness=reso // 32),
      tf.logical_not(background_mask))
  liver_mask = tf.logical_not(tf.logical_or(background_mask, fake_lesion_mask))

  # Blur the masks
  lesion_mask_blur = tf.squeeze(tf.nn.conv3d(
      tf.expand_dims(tf.expand_dims(tf.cast(lesion_mask, tf.float32), -1), 0),
      filter=tf.ones([reso // 32] * 3 + [1, 1], tf.float32) / (reso // 32) ** 3,
      strides=[1, 1, 1, 1, 1],
      padding='SAME'))
  fake_lesion_mask_blur = tf.squeeze(tf.nn.conv3d(
      tf.expand_dims(tf.expand_dims(
          tf.cast(fake_lesion_mask, tf.float32), -1), 0),
      filter=tf.ones([reso // 32] * 3 + [1, 1], tf.float32) / (reso // 32) ** 3,
      strides=[1, 1, 1, 1, 1],
      padding='SAME'))

  # Remove real lesion and add fake lesion.
  # If the intensitify is too small (maybe no liver or lesion region labeled),
  # do not generate fake data.
  gen_prob_indicator = tf.cond(
      tf.greater(intensity_diff, 0.0001),
      lambda: gen_prob_indicator, lambda: 0.0)
  # pylint: disable=g-long-lambda
  image = tf.cond(
      tf.greater(gen_prob_indicator, 1 - gen_fake_probability),
      lambda: image + intensity_diff * lesion_mask_blur \
                    - intensity_diff * fake_lesion_mask_blur,
      lambda: image)
  label = tf.cond(
      tf.greater(gen_prob_indicator, 1 - gen_fake_probability),
      lambda: tf.cast(background_mask, tf.float32) * 0 + \
          tf.cast(liver_mask, tf.float32) * 1 + \
          tf.cast(fake_lesion_mask, tf.float32) * 2,
      lambda: label)
  # pylint: enable=g-long-lambda

  return image, label

def maybe_flip(image, label, flip_axis, flip_indicator=None):
  """Randomly flip the image."""
  if flip_indicator is None:
    flip_indicator = tf.random_uniform(shape=[])
  flip_or_not = tf.greater(flip_indicator, 0.5)

  def _maybe_flip(data):
    """Flip or not according to flip_or_not."""
    data = tf.cond(tf.logical_and(flip_or_not, tf.equal(flip_axis, 1)),
                   lambda: tf.transpose(data, [1, 0, 2]),
                   lambda: data)
    data = tf.cond(tf.logical_and(flip_or_not, tf.equal(flip_axis, 2)),
                   lambda: tf.transpose(data, [2, 1, 0]),
                   lambda: data)

    data = tf.cond(flip_or_not,
                   lambda: tf.image.flip_up_down(data),
                   lambda: data)

    data = tf.cond(tf.logical_and(flip_or_not, tf.equal(flip_axis, 1)),
                   lambda: tf.transpose(data, [1, 0, 2]),
                   lambda: data)
    data = tf.cond(tf.logical_and(flip_or_not, tf.equal(flip_axis, 2)),
                   lambda: tf.transpose(data, [2, 1, 0]),
                   lambda: data)
    return data

  return _maybe_flip(image), _maybe_flip(label)

def maybe_rot180(image, label, static_axis, rot180_k=None):
  """Randomly rotate the image 180 degrees."""
  if rot180_k is None:
    rot180_k = 2 * tf.random_uniform(
        shape=[], minval=0, maxval=2, dtype=tf.int32)
  rot_or_not = tf.not_equal(rot180_k, 0)

  def _maybe_rot180(data):
    """Rotate or not according to rot_or_not."""
    data = tf.cond(tf.logical_and(rot_or_not, tf.equal(static_axis, 0)),
                   lambda: tf.transpose(data, [2, 1, 0]),
                   lambda: data)
    data = tf.cond(tf.logical_and(rot_or_not, tf.equal(static_axis, 1)),
                   lambda: tf.transpose(data, [0, 2, 1]),
                   lambda: data)

    data = tf.cond(rot_or_not,
                   lambda: tf.image.rot90(data, k=rot180_k),
                   lambda: data)

    data = tf.cond(tf.logical_and(rot_or_not, tf.equal(static_axis, 0)),
                   lambda: tf.transpose(data, [2, 1, 0]),
                   lambda: data)
    data = tf.cond(tf.logical_and(rot_or_not, tf.equal(static_axis, 1)),
                   lambda: tf.transpose(data, [0, 2, 1]),
                   lambda: data)
    return data

  return _maybe_rot180(image), _maybe_rot180(label)

def intensity_shift(
    image, label, per_class_intensity_scale, per_class_intensity_shift):
  """Perturb intensity in lesion and non-lesion regions."""

  if per_class_intensity_scale < 0.000001 and (
      per_class_intensity_shift < 0.000001):
    return image

  # Randomly change (mostly increase) intensity of non-lesion region.
  per_class_noise = _truncated_normal(
      per_class_intensity_shift, per_class_intensity_scale)
  image = image + per_class_noise * (
      image * tf.cast(tf.greater(label, 1.5), tf.float32))

  # Randomly change (mostly decrease) intensity of lesion region.
  per_class_noise = _truncated_normal(
      -per_class_intensity_shift, per_class_intensity_scale)
  image = image + per_class_noise * (
      image * tf.cast(tf.less(label, 1.5), tf.float32))

  return image

def image_corruption(
    image, label, reso, image_corrupt_ratio_mean, image_corrupt_ratio_stddev):
  """Randomly drop non-lesion pixels."""

  if image_corrupt_ratio_mean < 0.000001 and (
      image_corrupt_ratio_stddev < 0.000001):
    return image

  # Corrupt non-lesion region according to keep_mask.
  keep_mask = _gen_rand_mask(
      1 - image_corrupt_ratio_mean,
      image_corrupt_ratio_stddev,
      reso // 3, image.shape)

  keep_mask = tf.logical_or(tf.greater(label, 1.5), keep_mask)
  image *= tf.cast(keep_mask, tf.float32)

  return image

redpajama_set_name: RedPajamaGithub


text:
package uk.co.thefishlive.auth.session;

/**
 * Listener to listen for updates about the current active session.
 */
public interface SessionListener {

    /**
     * Event called when a new session is set as the active session.
     *
     * @param newSession
     *     the new active session
     */
    public void onActiveSessionChanged(Session newSession);

}


text:
require 'spec_helper'

describe Siphre::Encoded do
  describe 'inheritable methods' do

    subject { Siphre::Encoded }

    it { should respond_to :encode }
    it { should respond_to :equal }
    it { should respond_to :decode }
    it { should respond_to :option }

    it 'should raise an error as they are intended to be implemented on every class' do
      %w[encode equal decode].each do |method|
        expect { subject.send(method.to_sym) }.to raise_error Siphre::UnimplementedMethod
      end
    end

    it 'should allow setting of siphre options' do
      class Basic < Siphre::Encoded
        option :cipher, '1234567890'
      end

      Basic.new.should respond_to :cipher
      Basic.new.cipher.should == '1234567890'
    end

  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.apache.taverna.workbench</groupId>
		<artifactId>apache-taverna-workbench</artifactId>
		<version>3.1.0-incubating-SNAPSHOT</version>
	</parent>
	<artifactId>taverna-menu-items</artifactId>
	<packaging>bundle</packaging>
	<name>Apache Taverna menu items</name>
	<dependencies>
<!--
		<dependency>
			<groupId>org.apache.taverna.osgi</groupId>
			<artifactId>taverna-services-api</artifactId>
			<version>${taverna.osgi.version}</version>
		</dependency>
-->
                <dependency>
                        <groupId>${project.parent.groupId}</groupId>
                        <artifactId>taverna-contextual-views-impl</artifactId>
                        <version>${project.parent.version}</version>
                </dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-menu-api</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-report-api</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-selection-api</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-workbench-api</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-design-ui</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-graph-view</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-workflow-view</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.parent.groupId}</groupId>
			<artifactId>taverna-ui</artifactId>
			<version>${project.parent.version}</version>
		</dependency>
        <dependency>
                <groupId>${project.parent.groupId}</groupId>
                <artifactId>taverna-stringconstant-activity-ui</artifactId>
                <version>${project.parent.version}</version>
        </dependency>
	</dependencies>
</project>


text:
using UnityEngine;
using System.Collections;

public class RemoteCamera : MonoBehaviour {
	public GameObject ScreenToDisplayOn;
	//public int X;
	//public int Y;
	public RemoteCameraCapture cam;
	private int FrameInterval=30;
	private int FrameIntervalCounter=30;
	//public Texture2D RenderedImage;
	public string Target;
	private GameObject player;
	Material[] myMat;

	// Use this for initialization
	void Start () {
		GameObject TargetCamera= GameObject.Find (Target);
		if (TargetCamera!=null)
		{
			cam = TargetCamera.GetComponent<RemoteCameraCapture>();
			if (cam==null)
			{
				cam=TargetCamera.AddComponent<RemoteCameraCapture>();
			}
		}

		myMat = ScreenToDisplayOn.GetComponent<Renderer>().materials;
		player=UWCharacter.Instance.gameObject;//GameObject.Find ("Gronk");
	}

	// Update is called once per frame
	void Update () {
		if (Vector3.Distance(player.transform.position,this.transform.position)<=3)
		    {
			cam.camEnabled=true;
			}
		else
			{
			cam.camEnabled=false;
			}

		//Material[] myMat = ScreenToDisplayOn.renderer.materials;
		//for (int i = 0; i<myMat.GetUpperBound(0);i++)
		//{
			//Debug.Log (myMat[i].name);
		//	myMat[i].mainTexture=RenderedImage;
		//}
		//RenderedImage=CaptureImage(cam,Screen.width,Screen.height);

		FrameIntervalCounter++;
		if (FrameIntervalCounter>=FrameInterval)
		{
			FrameIntervalCounter=0;
			for (int i = 0; i<=myMat.GetUpperBound(0);i++)
			{
				//Debug.Log (myMat[i].name);
				myMat[i].mainTexture=cam.RenderedImage;
			}
		}
	}

	//void OnPostRender()
	//{
	//	Debug.Log ("Onpostrender");
		//if (ScreenToDisplayOn!=null)
		//{
			//SpriteRenderer SR = ScreenToDisplayOn.GetComponent<SpriteRenderer>();
			//if (SR!=null)
		//{
		//#pragma warning disable
	//	RenderedImage=CaptureImage(cam,Screen.width,Screen.height);
		//#pragma warning restore

				//Sprite newSprite= Sprite.Create( RenderedImage,new Rect(0,0,RenderedImage.width,RenderedImage.height), new Vector2(0.5f, 0.5f));
				//SR.sprite= newSprite;
			//}
	//	}
	//}

	///*Source: http://raypendergraph.wikidot.com/codesnippet:capturing-a-camera-image-in-unity*/
	//public Texture2D CaptureImage (Camera camera, int width, int height)
	//{
	//	Debug.Log ("Capturing");
	//	Texture2D captured = new Texture2D (width, height);
	//	camera.Render();
	//	RenderTexture.active = camera.targetTexture;
	//	captured.ReadPixels(new Rect(0,0,width,height),0,0);
	//	captured.Apply();
	//	RenderTexture.active = null;
	//	return captured;
	//}
}


text:
<?php slot('header') ?>
<?php include_partial('menu/header_menu', array('account' => $account)); ?>
<?php end_slot() ?>

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="/js/jquery.ui.touch-punch.min.js"></script>
<div class="assessment-wrapper">
    <?php include_partial('flight/report', array(
        'mitigation_info' => $mitigation_info,
        'high_risk_factors' => $high_risk_factors,
        'flight' => $flight
    )) ?>
</div>


text:
describe Faceter::Nodes::Exclude do

  let(:attributes) { { selector: Selector.new(options) } }

  it_behaves_like :creating_immutable_node do
    let(:options) { {} }
  end

  it_behaves_like :mapping_immutable_input do
    let(:options) { { only: [:foo, :bar] } }

    let(:input)   { { foo: :FOO, bar: :BAR, baz: :BAZ } }
    let(:output)  { { baz: :BAZ } }
  end

end # describe Faceter::Nodes::Exclude


text: if (decrypted != text) ;


text:
package rules_test

import (
	"code.cloudfoundry.org/lib/rules"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotal-cf-experimental/gomegamatchers"
)

var _ = Describe("Rules", func() {
	Describe("AppendComment", func() {
		var originalRule rules.IPTablesRule
		BeforeEach(func() {
			originalRule = rules.IPTablesRule{"some", "rule"}
		})
		It("appends the comment to the iptables rule, replacing spaces with underscores", func() {
			rule := rules.AppendComment(originalRule, `some:comment statement`)
			Expect(rule).To(Equal(rules.IPTablesRule{
				"some", "rule", "-m", "comment", "--comment", `some:comment_statement`,
			}))
		})
	})

	Describe("NewLogRule", func() {
		Context("when the log prefix is greater than 28 characters", func() {
			It("shortens the log-prefix to 28 characters and adds a space", func() {
				rule := rules.NewLogRule([]string{}, "some-very-very-very-long-app-guid")
				Expect(rule).To(ContainElement(`"some-very-very-very-long-app "`))
			})
		})
	})

	Describe("NewMarkAllowLogRule", func() {
		Context("when the log prefix is greater than 28 characters", func() {
			Context("when the protocol is not udp", func() {
				It("shortens the log-prefix to 28 characters and adds a space", func() {
					rule := rules.NewMarkAllowLogRule("10.255.0.1", "tcp", 80, 80, "0", "some-very-very-very-long-app-guid", -1)
					Expect(rule).To(Equal(rules.IPTablesRule{
						"-d", "10.255.0.1",
						"-p", "tcp",
						"--dport", "80:80",
						"-m", "mark", "--mark", "0x0",
						"-m", "conntrack", "--ctstate", "INVALID,NEW,UNTRACKED",
						"--jump", "LOG", "--log-prefix",
						`"OK_0_some-very-very-very-lon "`,
					}))
				})
			})
			Context("when the protocol is udp", func() {
				It("does not use conntrack", func() {
					rule := rules.NewMarkAllowLogRule("10.255.0.1", "udp", 80, 80, "0", "some-very-very-very-long-app-guid", 4)
					Expect(rule).To(Equal(rules.IPTablesRule{
						"-d", "10.255.0.1",
						"-p", "udp",
						"--dport", "80:80",
						"-m", "mark", "--mark", "0x0",
						"-m", "limit",
						"--limit", "4/s",
						"--limit-burst", "4",
						"--jump", "LOG", "--log-prefix",
						`"OK_0_some-very-very-very-lon "`,
					}))
				})

			})
		})
	})

	Describe("NewNetOutDefaultNonUDPLogRule", func() {
		Context("when the log prefix is greater than 28 characters", func() {
			It("shortens the log-prefix to 28 characters and adds a space", func() {
				rule := rules.NewNetOutDefaultNonUDPLogRule("some-very-very-very-long-app-guid")
				Expect(rule).To(Equal(rules.IPTablesRule{
					"!", "-p", "udp",
					"-m", "conntrack", "--ctstate", "INVALID,NEW,UNTRACKED",
					"-j", "LOG", "--log-prefix", `"OK_some-very-very-very-long- "`,
				},
				))
			})
		})
	})

	Describe("NewNetOutDefaultUDPLogRule", func() {
		Context("when the log prefix is greater than 28 characters", func() {
			It("shortens the log-prefix to 28 characters and adds a space", func() {
				rule := rules.NewNetOutDefaultUDPLogRule("some-very-very-very-long-app-guid", 5)
				Expect(rule).To(Equal(rules.IPTablesRule{
					"-p", "udp",
					"-m", "limit",
					"--limit", "5/s",
					"--limit-burst", "5",
					"-j", "LOG", "--log-prefix", `"OK_some-very-very-very-long- "`,
				}))
			})
		})
	})

	Describe("NewOverlayDefaultRejectLogRule", func() {
		Context("when the log prefix is greater than 28 characters", func() {
			It("shortens the log-prefix to 28 characters and adds a space", func() {
				rule := rules.NewOverlayDefaultRejectLogRule("some-very-very-very-long-app-guid", "", 5)
				Expect(rule).To(gomegamatchers.ContainSequence(rules.IPTablesRule{
					"-m", "limit", "--limit", "5/s", "--limit-burst", "5",
				}))
				Expect(rule).To(ContainElement(`"DENY_C2C_some-very-very-very "`))
			})
		})
	})

	Describe("NewNetOutDefaultRejectLogRule", func() {
		Context("when the log prefix is greater than 28 characters", func() {
			It("shortens the log-prefix to 28 characters and adds a space", func() {
				rule := rules.NewNetOutDefaultRejectLogRule("some-very-very-very-long-app-guid", 3)
				Expect(rule).To(gomegamatchers.ContainSequence(rules.IPTablesRule{
					"-m", "limit", "--limit", "3/s", "--limit-burst", "3",
				}))
				Expect(rule).To(ContainElement(`"DENY_some-very-very-very-lon "`))
			})
		})
	})
})


text:
"""
Module contains helper functions used in loading data into database
"""

import json
from sqlalchemy.exc import ProgrammingError
import sys
import os

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
                                             os.pardir, os.pardir)))

import housinginsights.ingestion.Cleaners as Cleaners

from housinginsights.tools.logger import HILogger
logger = HILogger(name=__file__, logfile="ingestion.log")

# Completed, tests not written.
def load_meta_data(filename='meta.json'):
    """
    Helper function validates the format of the JSON data in meta.json.

    :param filename: meta.json filepath
    :return: the validated JSON data of meta.json file
    """
    """
    Expected meta data format:
        { tablename: {fields:[
            {   "display_name": "Preservation Catalog ID",
                "display_text": "description of what this field is",
                "source_name": "Nlihc_id",
                "sql_name": "nlihc_id",
                "type": "object"
            }
            ]}
        }
    """
    with open(filename) as fh:
        meta = json.load(fh)

    # validate that meta.json meets the expected data format
    json_is_valid = True
    try:
        for table in meta:
            for field in meta[table]['fields']:
                for key in field:
                    if key not in ('display_name', 'display_text', 'source_name', 'sql_name', 'type', 'required_in_source', '_comment'):
                        json_is_valid = False
                        first_json_error = "Location: table: {}, section: {}, attribute: {}".format(table, field, key)
                        raise ValueError("Error found in JSON, check expected format. {}".format(first_json_error))
    except:
        raise ValueError("Error found in JSON, check expected format.")

    logger.info("{} imported. JSON format is valid: {}".format(filename, json_is_valid))

    return meta

def check_or_create_sql_manifest(engine, rebuild=False):
    '''
    Makes sure we have a manifest table in the database.
    If not, it creates it with appropriate fields.

    This corresponds to the manifest.csv file, which contains a log
    of all the individual data files we have used as well as which
    table they each go into.

    The csv version of the manifest includes all files we have ever
    used, including ones not in the database.

    The SQL version of the manifest only tracks those that have been
    written to the database, and whether they are still there or
    have been deleted.

    engine = the SQLalchemy engine to get to the database
    rebuild = Boolean as to whether to drop the table first.
    '''
    try:
        db_conn = engine.connect()
        sql_query = "SELECT * FROM manifest"
        query_result = db_conn.execute(sql_query)
        results = [dict(row.items()) for row in query_result]
        db_conn.close()
        return True
    except ProgrammingError as e:
        try:
            #Create the query with appropriate fields and datatypes
            db_conn = engine.connect()
            fields = [
                ("status","text"),
                ("load_date", "timestamp"),
                ("include_flag","text"),
                ("destination_table","text"),
                ("unique_data_id","text"),
                ("update_method", "text"),
                ("data_date","date"),
                ("encoding", "text"),
                ("local_folder","text"),
                ("s3_folder","text"),
                ("filepath","text"),
                ("notes","text")
                ]
            field_statements = []
            for tup in fields:
                field_statements.append(tup[0] + " " + tup[1])
            field_command = ",".join(field_statements)
            create_command = "CREATE TABLE manifest({});".format(field_command)
            db_conn.execute(create_command)
            db_conn.close()
            logger.info("Manifest table created in the SQL database")
            return True

        except Exception as e:
            raise e

def get_cleaner_from_name(meta, manifest_row, name="GenericCleaner", engine=None):
    """
    Returns the instance of the cleaner class matching the given cleaner class
    name.

    :param meta: in memory JSON object representing meta.json
    :param manifest_row: the given row in manifest.csv
    :param name: the referenced cleaner class in meta.json for the table as str
    :return: a class object of the given cleaner class
    """

    #Import
    #module = import_module("module.submodule")
    Class_ = getattr(Cleaners, name)
    instance = Class_(meta, manifest_row, engine=engine)
    return instance

def join_paths(pieces=[]):
    '''
    Joins arbitrary pieces of a url or path.
    Alternative to os.path.join if the second argument might start with "/"
    '''
    return '/'.join(s.strip('/') for s in pieces)

#Used for testing purposes
if __name__ == '__main__':

    from housinginsights.tools import dbtools
    meta_path = os.path.abspath('../../scripts/meta.json')

    meta = load_meta_data(meta_path)
    engine = dbtools.get_database_engine('docker_database')
    meta_json_to_database(engine=engine, meta=meta)


text:
using System;

namespace System.IO
{
    /// <devdoc>
    ///   Defines constants for read, write, or read/write
    ///   access to a file.
    /// </devdoc>
    [Flags]
    public enum FileAccess
    {
        /// <devdoc>
        ///   Specifies read access to the file.  Data can be read from the file and
        ///   the file pointer can be moved.  Combine with WRITE for read-write access.
        /// </devdoc>
        Read = 1,

        /// <devdoc>
        ///   Specifies write access to the file.  Data can be written to the file and
        ///   the file pointer can be moved.  Combine with READ for read-write access.
        /// </devdoc>
        Write = 2,

        /// <devdoc>
        ///   Specifies read and write access to the file.  Data can be written to the
        ///   file and the file pointer can be moved.  Data can also be read from the
        ///   file.
        /// </devdoc>
        ReadWrite = 3
    }
}


text:
import React,{ Component } from 'react';
import {
    Text,
    View,
    Image,
    StyleSheet,
    TouchableHighlight
} from 'react-native';

import styles from '../../../css/styles';

export default class RefundItem extends Component {
    constructor(props){
    	super(props);
      this.attr = this.props.props;
    }
    render() {
        let _data = this.props.data;
        return (
           <View style={styles.sorderItem.item}>
              <View style={styles.sorderItem.itemTitle}>
                <View style={styles.sorderItem.row}>
                  <View style={_data.orderType == 10 ? styles.orderItem.type : styles.orderItem.type2}>
                    <Text style={styles.orderItem.typeText}>{_data.orderType == 10 ? '自营' : '入驻商'}</Text>
                  </View>
                  <Text style={styles.sorderItem.orderSn} numberOfLines={1}>{_data.order && _data.order.shopName}</Text>
                  <Text style={styles.sorderItem.orderStatus}>{_data.statusName}</Text>
                </View>
                <View style={styles.sorderItem.row}>
                  <Text style={[styles.sorderItem.orderInfo, styles.common.flex]}>退款单号:{_data.orderRefundSn}</Text>
                  <Text style={styles.sorderItem.orderInfo}>{_data.ctime}</Text>
                </View>
                <View style={styles.sorderItem.row}>
                  <Text style={[styles.sorderItem.orderInfo, styles.common.flex]}>订单编号:{_data.order && _data.order.orderSn}</Text>
                </View>
              </View>
              {
                  _data.refundGoods && _data.refundGoods.map((v, k) => {
                  return (<TouchableHighlight underlayColor='#eee' style={styles.sorderItem.goods} onPress={() => this._toRefundDetail(_data)}>
                    <View style={styles.sorderItem.itemBody}>
                      <View style={styles.sorderItem.imgWrapper}>
                        <Image style={styles.sorderItem.img} source={{uri: v.imgUrlSmall}} />
                      </View>
                      <View style={styles.sorderItem.info}>
                        <Text style={styles.sorderItem.infoName} numberOfLines={2}>{v.goodsName}</Text>
                        <Text style={styles.sorderItem.infoAttr}>{v.skuAttr}</Text>
                        <View style={styles.common.flex}>
                          <Text style={styles.sorderItem.infoPrice}>¥{v.price}</Text>
                          <Text style={styles.sorderItem.infoNum}>数量:{v.qty}</Text>
                        </View>
                      </View>
                    </View>
                  </TouchableHighlight>)
                })
              }
              <View style={[styles.common.flexDirectionRow, styles.common.flexCenterv, styles.orderItem.footer]}>
                <View style={styles.common.flex}>
                  <Text style={styles.refundItem.totalText}>订单金额:<Text style={styles.refundItem.totalTextActive}>¥{_data.order && _data.order.totalAmount}</Text></Text>
                  <Text style={styles.refundItem.totalText}>退款金额:<Text style={styles.refundItem.totalTextActive}>¥{_data.refundAmount}</Text></Text>
                </View>
                <View>
                  {_data.status == 20 ?
                  <TouchableHighlight underlayColor="#fafafa" onPress={this._toFillLogi}>
                    <Text style={[styles.btn3.defaults, styles.btn3.danger]}>填写物流</Text>
                  </TouchableHighlight>
                  : null}
                </View>
              </View>
           </View>
        );
    }
    _toRefundDetail = (item) => {
      this.attr.navigation.navigate('BuyerRefundDetail', {
        id: item.id
      });
    }
    _toExamine = (item) => {
      this.attr.navigation.navigate('SellerRefundExamine', {
        id: item.id,
        shopid: item.shopId,
        ordersn: this.props.type == 1 ? (item.order.relationOrderSn || item.order.orderSn) : (item.order.mainOrderSn || item.order.orderSn),
        type: this.props.type,
        refundtype: item.type,
        fromdetail: false,
      });
    }
    _toFillLogi = () => {

    }
}


text:
0">

1">

Maps:

All

	  {{ map.properties.mapName }}

    <leaflet style="width:100%;height:600px"></leaflet>

    <slick class="slider" ng-if="slickLoaded" settings="slideConfig">

    </slick>

  User hasn't created any maps yet


text:
	defined(STM32F4XX) || defined(STM32F7XX) || defined(STM32L0XX) || \
	defined(STM32L1XX) || defined(STM32H7XX)

// strong implementation of this function specific to the STM32 targets
uint32_t SUPPORT_ComputeCRC(const void* rgBlock, const uint32_t nLength, const uint32_t crc)
{
	crcAquireModule();

	uint32_t myCrc = crcCompute(rgBlock, nLength, crc);

	crcReleaseModule();

    return myCrc;
};

#endif


text:
/*
 * This file is part of the Sulu CMS.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

define([
    'services/sulucontact/account-manager',
    'services/sulucontact/account-router',
    'services/sulucontact/account-delete-dialog',
], function(AccountManager, AccountRouter, DeleteDialog) {

    'use strict';

    return {

        collaboration: function() {
            if (!this.options.id) {
                return;
            }

            return {
                id: this.options.id,
                type: 'contact'
            };
        },

        /**
         * Returns the header config for this main-view
         * if an existing contact is edited a delete-button is added
         * @return {Object} the header config object
         */
        header: function() {
            var config = {
                title: function() {
                    return this.data.name;
                }.bind(this),
                tabs: {
                    url: '/admin/content-navigations?alias=account',
                    options: {
                        data: function() {
                            // this.data is set by sulu-content.js with data from loadComponentData()
                            return this.sandbox.util.extend(false, {}, this.data);
                        }.bind(this)
                    },
                    componentOptions: {
                        values: this.data
                    }
                },
                toolbar: {
                    buttons: {
                        save: {
                            parent: 'saveWithOptions'
                        }
                    }
                }
            };
            if (!!this.options.id) {
                config.toolbar.buttons.delete = {};
            }
            return config;
        },

        title: function() {
            return this.data.name;
        },

        loadComponentData: function() {
            var promise = this.sandbox.data.deferred();
            AccountManager.loadOrNew(this.options.id).then(function(data) {
                promise.resolve(data);
            });
            return promise;
        },

        initialize: function() {
            this.bindCustomEvents();
        },

        bindCustomEvents: function() {
            this.sandbox.on('sulu.header.back', this.toList.bind(this));
            this.sandbox.on('sulu.tab.dirty', this.enableSave.bind(this));
            this.sandbox.on('sulu.router.navigate', this.disableSave.bind(this));
            this.sandbox.on('sulu.toolbar.save', this.save.bind(this));
            this.sandbox.on('sulu.tab.saving', this.loadingSave.bind(this));
            this.sandbox.on('sulu.tab.data-changed', this.changeData.bind(this));
            this.sandbox.on('sulu.toolbar.delete', this.deleteAccount.bind(this));
        },

        /**
         * Routes back to the list
         */
        toList: function() {
            AccountRouter.toList();
        },

        /**
         * Shows a delete dialog and deletes the current account
         */
        deleteAccount: function() {
            DeleteDialog.showDialog([this.options.id], function(deleteContacts) {
                AccountManager.delete(this.options.id, deleteContacts).then(function() {
                    AccountRouter.toList();
                }.bind(this));
            }.bind(this));
        },

        /**
         * Sets the save-button into loading-state and tells the tab to save itselve
         * @param action {String} the after-save action
         */
        save: function(action) {
            this.saveTab().then(function(savedData) {
                this.afterSave(action, savedData);
            }.bind(this));
        },

        /**
         * Override the current view-data
         * @param newData {Object} the new data to use
         */
        changeData: function(newData) {
            this.data = newData
        },

        /**
         * Saves the tab and returns a after the tab has saved itselve
         * @returns promise with the saved data
         */
        saveTab: function() {
            var promise = $.Deferred();
            this.sandbox.once('sulu.tab.saved', function(savedData, updateData) {
                if (!!updateData) {
                    this.changeData(savedData)
                }
                promise.resolve(savedData);
            }.bind(this));
            this.sandbox.emit('sulu.tab.save');
            return promise;
        },

        /**
         * Enables the save-button
         */
        enableSave: function() {
            this.sandbox.emit('sulu.header.toolbar.item.enable', 'save', false);
        },

        /**
         * Disables the save-button
         */
        disableSave: function() {
            this.sandbox.emit('sulu.header.toolbar.item.disable', 'save', false);
        },

        /**
         * Sets the save-button in loading-state
         */
        loadingSave: function() {
            this.sandbox.emit('sulu.header.toolbar.item.loading', 'save');
        },

        /**
         * Executes the after save action: Navigates to edit, add or list
         * @param action {String} the after-save action
         * @param savedData {Object} the data after the save-process has finished
         */
        afterSave: function(action, savedData) {
            this.sandbox.emit('sulu.header.toolbar.item.disable', 'save', true);
            this.sandbox.emit('sulu.header.saved', savedData);
            if (action === 'back') {
                AccountRouter.toList();
            } else if (action === 'new') {
                AccountRouter.toAdd(savedData);
            } else if (!this.options.id) {
                AccountRouter.toEdit(savedData.id);
            }
        }
    };
});


text:
{-
Copyright 2015 Tristan Aubrey-Jones
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}

import System.Directory
import Data.List (isSuffixOf)

import Compiler.Front.Front
import Compiler.Front.ExprTree
import Compiler.Front.SrcLexer
import Compiler.Front.SrcParser

main :: IO ()
main = do
  -- get test suite path
  curDir <- getCurrentDirectory
  let testDir = curDir ++ "/Compiler/Tests/FrontEnd1/"

  -- show caption
  putStr $ "FrontEnd1: Parse input programs in: " ++ testDir ++ "\n"

  -- get directory listing flocc programs
  contents <- getDirectoryContents testDir
  let floccFiles = filter (isSuffixOf ".flocc") contents
  let floccPaths = map (testDir++) floccFiles

  -- read in each flocc program
  srcPrograms <- mapM readFile floccPaths

  -- try and parse them all, catching any exceptions
  asts <- mapM testParseSrcFile floccPaths

  -- show results
  mapM (\(path,code,ast) -> do putStr "\n----------------\n" ;
                               putStr path ;
                               putStr "\n----------------\n" ;
                               putStr code ;
                               putStr "----------------\n" ;
                               putStr (show ast)) $ zip3 floccFiles srcPrograms asts

  putStr "\n\n"
  return ()

-- parse source code
 {- pg <- parseAndLabel typeNames (scan s)
  --pg <- parseAndLabel (flipAssocList globalNames) (scan s)
  --pg <- generateGraph
  pg' <- convertAllToLets pg
  pg'' <- applyLetLifting pg'
-}


text:
require File.expand_path '../../test_helper', __dir__

# Storage Blob Class
class TestAcquireBlobLease < Minitest::Test
  # This class posesses the test cases for the requests of acquire blob lease.
  def setup
    Fog.mock!
    @mock_service = Fog::Storage::AzureRM.new(storage_account_credentials)
    Fog.unmock!
    @mocked_response = mocked_storage_http_error

    @service = Fog::Storage::AzureRM.new(storage_account_credentials)
    @blob_client = @service.instance_variable_get(:@blob_client)

    @blob_lease_id = ApiStub::Requests::Storage::File.blob_lease_id
  end

  def test_acquire_blob_lease_success
    @blob_client.stub :acquire_blob_lease, @blob_lease_id do
      assert_equal @blob_lease_id, @service.acquire_blob_lease('test_container', 'test_blob')
    end
  end

  def test_acquire_blob_lease_http_exception
    http_exception = ->(*) { raise Azure::Core::Http::HTTPError.new(@mocked_response) }
    @blob_client.stub :acquire_blob_lease, http_exception do
      assert_raises(RuntimeError) do
        @service.acquire_blob_lease('test_container', 'test_blob')
      end
    end
  end

  def test_acquire_blob_lease_mock
    assert_equal @blob_lease_id, @mock_service.acquire_blob_lease('test_container', 'test_blob')
  end
end


text:
<?php

/*
 * Paragraph control
 * @author Jake Josol
 * @description Paragraph
 */

use Warp\UI\Control;

class Paragraph extends Control
{
	protected $type = "p";
	protected $isParent = true;
	protected static $name = "Paragraph";

	public function SetText($content)
	{
		$controlText = new Text($content);
		$this->children = array($controlText);

		return $this;
	}
}

?>