text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using static WalletWasabi.Tor.Http.Constants;

namespace WalletWasabi.Tor.Http.Models
{
	public class HeaderSection
	{
		public List<HeaderField> Fields { get; private set; } = new List<HeaderField>();

		public string ToString(bool endWithTwoCRLF)
		{
			StringBuilder sb = new StringBuilder();
			foreach (var field in Fields)
			{
				sb.Append(field.ToString(endWithCRLF: true));
			}
			if (endWithTwoCRLF)
			{
				sb.Append(CRLF);
			}
			return sb.ToString();
		}

		public override string ToString()
		{
			return ToString(false);
		}

		public static async Task<HeaderSection> CreateNewAsync(string headersString)
		{
			headersString = HeaderField.CorrectObsFolding(headersString);

			var hs = new HeaderSection();
			if (headersString.EndsWith(CRLF + CRLF))
			{
				headersString = headersString.TrimEnd(CRLF, StringComparison.Ordinal);
			}

			using var reader = new StringReader(headersString);
			while (true)
			{
				var field = reader.ReadLine(strictCRLF: true);
				if (field is null)
				{
					break;
				}
				hs.Fields.Add(await HeaderField.CreateNewAsync(field).ConfigureAwait(false));
			}

			ValidateAndCorrectHeaders(hs);

			return hs;
		}

		private static void ValidateAndCorrectHeaders(HeaderSection hs)
		{
			// https://tools.ietf.org/html/rfc7230#section-5.4
			// Since the Host field - value is critical information for handling a
			// request, a user agent SHOULD generate Host as the first header field
			// following the request - line.
			HeaderField hostToCorrect = null;
			foreach (var f in hs.Fields)
			{
				// if we find host
				if (f.Name == "Host")
				{
					// if host is not first
					if (hs.Fields.First().Name != "Host")
					{
						// then correct host
						hostToCorrect = f;
						break;
					}
				}
			}

			if (hostToCorrect is { })
			{
				hs.Fields.Remove(hostToCorrect);
				hs.Fields.Insert(0, hostToCorrect);
			}

			// https://tools.ietf.org/html/rfc7230#section-3.3.2
			// If a message is received that has multiple Content-Length header
			// fields with field-values consisting of the same decimal value, or a
			// single Content-Length header field with a field value containing a
			// list of identical decimal values(e.g., "Content-Length: 42, 42"),
			// indicating that duplicate Content-Length header fields have been
			// generated or combined by an upstream message processor, then the
			// recipient MUST either reject the message as invalid or replace the
			// duplicated field - values with a single valid Content - Length field
			// containing that decimal value prior to determining the message body
			// length or forwarding the message.

			var allParts = new HashSet<string>();
			foreach (var field in hs.Fields)
			{
				if (field.Name == "Content-Length")
				{
					var parts = field.Value.Trim().Split(',');
					foreach (var part in parts)
					{
						allParts.Add(part.Trim());
					}
				}
			}
			if (allParts.Count > 0) // then has Content-Length field
			{
				if (allParts.Count > 1)
				{
					throw new InvalidDataException("Invalid Content-Length.");
				}
				hs.Fields.RemoveAll(x => x.Name == "Content-Length");
				hs.Fields.Add(new HeaderField("Content-Length", allParts.First()));
			}
		}

		public HttpRequestContentHeaders ToHttpRequestHeaders()
		{
			using var message = new HttpRequestMessage
			{
				Content = new ByteArrayContent(Array.Empty<byte>())
			};
			message.Content.Headers.ContentLength = null;
			foreach (var field in Fields)
			{
				if (field.Name.StartsWith("Content-", StringComparison.Ordinal))
				{
					message.Content.Headers.TryAddWithoutValidation(field.Name, field.Value);
				}
				else
				{
					message.Headers.TryAddWithoutValidation(field.Name, field.Value);
				}
			}

			return new HttpRequestContentHeaders
			{
				RequestHeaders = message.Headers,
				ContentHeaders = message.Content.Headers
			};
		}

		public HttpResponseContentHeaders ToHttpResponseHeaders()
		{
			using var message = new HttpResponseMessage
			{
				Content = new ByteArrayContent(Array.Empty<byte>())
			};
			message.Content.Headers.ContentLength = null;
			foreach (var field in Fields)
			{
				if (field.Name.StartsWith("Content-", StringComparison.Ordinal))
				{
					message.Content.Headers.TryAddWithoutValidation(field.Name, field.Value);
				}
				else
				{
					message.Headers.TryAddWithoutValidation(field.Name, field.Value);
				}
			}

			return new HttpResponseContentHeaders
			{
				ResponseHeaders = message.Headers,
				ContentHeaders = message.Content.Headers
			};
		}

		public static HeaderSection CreateNew(HttpHeaders headers)
		{
			var hs = new HeaderSection();
			foreach (var header in headers)
			{
				hs.Fields.Add(new HeaderField(header.Key, string.Join(",", header.Value)));
			}

			// -- Start [SECTION] Crazy VS2017/.NET Core 1.1 bug ---
			// The following if branch is needed as is to avoid the craziest VS2017/.NET Core 1.1 bug I have ever seen!
			// If this section is not added the Content-Length header will not be set unless...
			// - I put a break point at the start of the function
			// - And I explicitly expand the "headers" variable
			if (headers is HttpContentHeaders contentHeaders)
			{
				if (contentHeaders.ContentLength is { })
				{
					if (hs.Fields.All(x => x.Name != "Content-Length"))
					{
						hs.Fields.Add(new HeaderField("Content-Length", contentHeaders.ContentLength.ToString()));
					}
				}
			}
			// -- End [SECTION] Crazy VS2017/.NET Core 1.1 bug ---

			return hs;
		}
	}
}


text:
package edu.latrobe.blaze

import breeze.linalg.{DenseMatrix, DenseVector}
import edu.latrobe._
import edu.latrobe.blaze._
import edu.latrobe.blaze.modules._
import edu.latrobe.sizes._
import org.scalatest._
import TestUtils._
import edu.latrobe.blaze.modules.jvm.{Softmax_JVM_ApacheCommons_Description, Softmax_JVM_Baseline_Description}
import edu.latrobe.cublaze.modules._

final class TestModule_Softmax
  extends FlatSpec with Matchers {

  def softmax(x: DenseVector[Real])
  : DenseVector[Real] = {
    val sum: Real = Real(VectorEx.foldLeft(0.0, x)(_ + Math.exp(_)))
    DenseVector(VectorEx.map(x)(
      x => Real(Math.exp(x) / sum)
    ))
  }

  def softmax(x: DenseMatrix[Real])
  : DenseMatrix[Real] = {
    val result = DenseMatrix.zeros[Real](x.rows, x.cols)
    MatrixEx.foreachColumnVector(result, x)(_ := softmax(_))
    result
  }

  def softmax_dx(x: DenseVector[Real], err: DenseVector[Real])
  : DenseVector[Real] = {
    val y = softmax(x)
    val sum = VectorEx.dot(err, y)
    val tmp = err - sum
    tmp :*= y
    tmp
  }

  def softmax_dx(x: DenseMatrix[Real], err: DenseMatrix[Real])
  : DenseMatrix[Real] = {
    val result = DenseMatrix.zeros[Real](x.rows, x.cols)
    MatrixEx.foreachColumnVector(result, x, err)(_ := softmax_dx(_, _))
    result
  }

  "All Softmax variants" should "behave as exactly as defined" in {

    val x = RealArrayTensor.fill(Size1(2, 1), 4, PseudoRNG.default.gaussianDistribution())
    val y = RealArrayTensor.derive(Size1(2, 1), softmax(x.valuesMatrix))
    val e = RealArrayTensor.fill(Size1(2, 1), 4, PseudoRNG.default.gaussianDistribution())
    val d = RealArrayTensor.derive(Size1(2, 1), softmax_dx(x.valuesMatrix, e.valuesMatrix))

    // Isolate CPU Baseline variant.
    if (true) {
      SoftmaxBuilder.unregisterAll()
      SoftmaxBuilder.register(10, Softmax_JVM_Baseline_Description)
      val layer = SoftmaxBuilder().build(BuildHints.derive(x))
      val prediction = layer.predict(Training(0L), x, null)
      similarity(y, prediction.output) should be < tolerance0
      val gHat = layer.weightBuffer.allocateZeroedSibling()
      val dHat = layer.deriveGradients(prediction, e, gHat).compute()
      similarity(d, dHat) should be < tolerance0
    }

    // Isolate CPU ApacheCommons variant.
    if (true) {
      SoftmaxBuilder.unregisterAll()
      SoftmaxBuilder.register(10, Softmax_JVM_ApacheCommons_Description)
      val layer = SoftmaxBuilder().build(BuildHints.derive(x))
      val prediction = layer.predict(Training(0L), x, null)
      similarity(y, prediction.output) should be < tolerance0
      val gHat = layer.weightBuffer.allocateZeroedSibling()
      val dHat = layer.deriveGradients(prediction, e, gHat).compute()
      similarity(d, dHat) should be < tolerance0
    }

    // Isolate CUDA Direct variant.
    if (true) {
      SoftmaxBuilder.unregisterAll()
      SoftmaxBuilder.register(10, Softmax_CUDA_CUDNN_Description)
      val layer = SoftmaxBuilder().build(BuildHints.derive(x))
      val prediction = layer.predict(Training(0L), x, null)
      similarity(y, prediction.output) should be < tolerance0
      val gHat = layer.weightBuffer.allocateZeroedSibling()
      val dHat = layer.deriveGradients(prediction, e, gHat).compute()
      similarity(d, dHat) should be < tolerance0
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">

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

  <title>ansible.parsing.yaml.constructor — Ansible 1 documentation</title>

    <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />

    <link rel="top" title="Ansible 1 documentation" href="../../../../index.html"/>
        <link rel="up" title="Module code" href="../../../index.html"/>

             Ansible

                2.2

  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        Ansible

Docs »

Module code »

ansible.parsing.yaml.constructor

Source code for ansible.parsing.yaml.constructor

# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from yaml.constructor import Constructor, ConstructorError
from yaml.nodes import MappingNode
from ansible.parsing.yaml.objects import AnsibleMapping, AnsibleSequence, AnsibleUnicode
from ansible.vars.unsafe_proxy import wrap_var

try:
    from __main__ import display
except ImportError:
    from ansible.utils.display import Display
    display = Display()

[docs]class AnsibleConstructor(Constructor):
    def __init__(self, file_name=None):
        self._ansible_file_name = file_name
        super(AnsibleConstructor, self).__init__()

[docs]    def construct_yaml_map(self, node):
        data = AnsibleMapping()
        yield data
        value = self.construct_mapping(node)
        data.update(value)
        data.ansible_pos = self._node_position_info(node)

[docs]    def construct_mapping(self, node, deep=False):
        # Most of this is from yaml.constructor.SafeConstructor.  We replicate
        # it here so that we can warn users when they have duplicate dict keys
        # (pyyaml silently allows overwriting keys)
        if not isinstance(node, MappingNode):
            raise ConstructorError(None, None,
                    "expected a mapping node, but found %s" % node.id,
                    node.start_mark)
        self.flatten_mapping(node)
        mapping = AnsibleMapping()

        # Add our extra information to the returned value
        mapping.ansible_pos = self._node_position_info(node)

        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            try:
                hash(key)
            except TypeError as exc:
                raise ConstructorError("while constructing a mapping", node.start_mark,
                        "found unacceptable key (%s)" % exc, key_node.start_mark)

            if key in mapping:
                display.warning(u'While constructing a mapping from {1}, line {2}, column {3}, found a duplicate dict key ({0}).  Using last defined value only.'.format(key, *mapping.ansible_pos))

            value = self.construct_object(value_node, deep=deep)
            mapping[key] = value

        return mapping

[docs]    def construct_yaml_str(self, node, unsafe=False):
        # Override the default string handling function
        # to always return unicode objects
        value = self.construct_scalar(node)
        ret = AnsibleUnicode(value)

        ret.ansible_pos = self._node_position_info(node)

        if unsafe:
            ret = wrap_var(ret)

        return ret

[docs]    def construct_yaml_seq(self, node):
        data = AnsibleSequence()
        yield data
        data.extend(self.construct_sequence(node))
        data.ansible_pos = self._node_position_info(node)

[docs]    def construct_yaml_unsafe(self, node):
        return self.construct_yaml_str(node, unsafe=True)

    def _node_position_info(self, node):
        # the line number where the previous token has ended (plus empty lines)
        # Add one so that the first line is line 1 rather than line 0
        column = node.start_mark.column + 1
        line = node.start_mark.line + 1

        # in some cases, we may have pre-read the data and then
        # passed it to the load() call for YAML, in which case we
        # want to override the default datasource (which would be
        # '<string>') to the actual filename we read in
        datasource = self._ansible_file_name or node.start_mark.name

        return (datasource, line, column)

AnsibleConstructor.add_constructor(
    u'tag:yaml.org,2002:map',
    AnsibleConstructor.construct_yaml_map)

AnsibleConstructor.add_constructor(
    u'tag:yaml.org,2002:python/dict',
    AnsibleConstructor.construct_yaml_map)

AnsibleConstructor.add_constructor(
    u'tag:yaml.org,2002:str',
    AnsibleConstructor.construct_yaml_str)

AnsibleConstructor.add_constructor(
    u'tag:yaml.org,2002:python/unicode',
    AnsibleConstructor.construct_yaml_str)

AnsibleConstructor.add_constructor(
    u'tag:yaml.org,2002:seq',
    AnsibleConstructor.construct_yaml_seq)

AnsibleConstructor.add_constructor(
    u'!unsafe',
    AnsibleConstructor.construct_yaml_unsafe)

        © Copyright 2016, Red Hat.

  Built with Sphinx using a theme provided by Read the Docs.


text:
package com.wecan.xhin.studio.fragment;

import com.wecan.xhin.studio.api.Api;
import com.wecan.xhin.studio.bean.down.UsersData;

import rx.Observable;

/**
 * Created by xhinliang on 15-11-20.
 * xhinliang@gmail.com
 */
public class AllUserFragment extends UsersFragment {

    public static AllUserFragment newInstance() {
        return new AllUserFragment();
    }

    @Override
    protected Observable<UsersData> getUserApi(Api api) {
        return api.getAllUser();
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Substation */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'shortcode')->textInput(['maxlength' => 7]) ?>

    <?= $form->field($model, 'name_hi')->textInput(['maxlength' => 50]) ?>

    <?= $form->field($model, 'name_en')->textInput(['maxlength' => 50]) ?>

    <?= $form->field($model, 'type')->textInput() ?>

    <?= $form->field($model, 'documents')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'division_id')->textInput() ?>

    <?= $form->field($model, 'je_area_id')->textInput() ?>

    <?= $form->field($model, 'voltageratio')->textInput(['maxlength' => 30]) ?>

    <?= $form->field($model, 'mva')->textInput(['maxlength' => 20]) ?>

    <?= $form->field($model, 'notrf')->textInput() ?>

    <?= $form->field($model, 'capacity')->textInput() ?>

    <?= $form->field($model, 'mvamax')->textInput() ?>

    <?= $form->field($model, 'mvarmax')->textInput() ?>

    <?= $form->field($model, 'remarks')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'circle_id')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<# Code by MSP-Greg
Applies all patches to ruby
#>

#————————————————————————————————————————————————————————————————— Apply-Patches
# Applies patches
function Apply-Patches($p_dir) {
  $patch_exe = "$d_msys2/usr/bin/patch.exe"
  Push-Location "$d_repo/$p_dir"
  [string[]]$patches = Get-ChildItem -Include *.patch -Path . -Recurse |
    select -expand name
  Pop-Location
  Push-Location "$d_ruby"
  foreach ($p in $patches) {
    if ($p.substring(0,2) -eq "__") { continue }
    Write-Host $($dash * 55) $p -ForegroundColor $fc
    & $patch_exe -p1 -N --no-backup-if-mismatch -i "$d_repo/$p_dir/$p"
  }
  Pop-Location
  Write-Host ''
}

#————————————————————————————————————————————————————————————————— Set-Variables
# set base variables, including MSYS2 location and bit related varis
function Set-Variables-Local {
  $script:ruby_path = $(ruby.exe -e "puts RbConfig::CONFIG['bindir']").trim().replace('\', '/')
  $script:time_info = ''
  $script:time_old  = $null
  $script:time_start = $null
}

#——————————————————————————————————————————————————————————————————————— Set-Env
# Set ENV, including gcc flags
function Set-Env {
  $env:path = "$ruby_path;$d_mingw;$d_repo/git/cmd;$d_msys2/usr/bin;$base_path"

  # used in Ruby scripts
  $env:D_MSYS2  = $d_msys2

  $env:CFLAGS   = "-march=$march -mtune=generic -O3 -pipe"
  $env:CXXFLAGS = "-march=$march -mtune=generic -O3 -pipe"
  $env:CPPFLAGS = "-D_FORTIFY_SOURCE=2 -D__USE_MINGW_ANSI_STDIO=1 -DFD_SETSIZE=2048"
  $env:LDFLAGS  = "-pipe"
}

#——————————————————————————————————————————————————————————————————— start build
# defaults to 64 bit
$script:bits = if ($args.length -eq 1 -and $args[0] -eq 32) { 32 } else { 64 }

cd $PSScriptRoot

. ./0_common.ps1
Set-Variables
Set-Variables-Local
Set-Env

Apply-Patches "patches"

# apply patches for testing
Apply-Patches "patches_basic_boot"
Apply-Patches "patches_spec"
Apply-Patches "patches_test"


text:
@implementation AGSMapViewBase (EQSHelper)
+(void)load
{
    // First of all we want to replace setDelegate and getDelegate with our own
    // methods. We'll still call them, but we want to creep into the call stack.
    Class swap = [self class];
    Method a = nil; Method b = nil;

    a = class_getInstanceMethod(swap, @selector(setLayerDelegate:));
    b = class_getInstanceMethod(swap, @selector(eqs_setLayerDelegate:));
    method_exchangeImplementations(a, b);

    a = class_getInstanceMethod(swap, @selector(layerDelegate));
    b = class_getInstanceMethod(swap, @selector(eqs_layerDelegate));
    method_exchangeImplementations(a, b);
}

-(void)eqs_setLayerDelegate:(id<AGSMapViewLayerDelegate>)layerDelegate
{
    // We store the externally visible delegate as an associate object…
    // Although we don't allow anyone to set EQSHelper's singleton as it…
    if (layerDelegate && layerDelegate != [EQSHelper defaultHelper])
    {
        objc_setAssociatedObject(self, kEQSInterceptedDelegate, layerDelegate, OBJC_ASSOCIATION_RETAIN);
    }
    else
    {
        objc_setAssociatedObject(self, kEQSInterceptedDelegate, nil, OBJC_ASSOCIATION_ASSIGN);
    }

    // But internally we set the delegate as the EQSHelper singleton.
    //
    // Note: Because of the method swizzling that happens on AGSMapView +load(), this is actually
    // the originally defined setLayerDelegate: method. Where we are now is by this point known as
    // AGSMapView->setLayerDelegate: - confusing, powerful, and neat.
    [self eqs_setLayerDelegate:[EQSHelper defaultHelper]];
}

-(id<AGSMapViewLayerDelegate>)eqs_layerDelegate
{
    // And whenever anyone asks for the delegate, we'll return the EQSHelper Singleton.
    //
    // When someone calls an <AGSMapViewLayerDelegate> protocol method, the EQSHelper
    // singleton will receive that call and marshall it to the actual externally visible
    // delegate, but in the case of mapViewDidLoad will raise a notification too.
    //
    // End result? Delegate model still works, but now we also have a notification when
    // the map view loaded.
    return [EQSHelper defaultHelper];
}
@end


text:
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using NUnit.Framework;

namespace MonoTests.System.Xml.Xsl
{
	[TestFixture]
	public class MsxslScriptTests
	{
		// PI calc stuff are one of MSDN samples.

		static XmlDocument doc;
		static MsxslScriptTests ()
		{
			string inputxml = @"<?xml version='1.0'?>
<data>
  <circle>
    <radius>12</radius>
  </circle>
  <circle>
    <radius>37.5</radius>
  </circle>
</data>";
			doc = new XmlDocument ();
			doc.LoadXml (inputxml);
		}

		static string xslstring = @"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
    xmlns:msxsl='urn:schemas-microsoft-com:xslt'
    xmlns:user='urn:my-scripts'>

    ***** rewrite here *****

  <xsl:template match='data'>
    <circles>

      <xsl:for-each select='circle'>
        <circle>
          <xsl:copy-of select='node()'/>
          <circumference>
             <!-- xsl:value-of select='user:circumference(radius)'/ -->
               TEST:
             <xsl:value-of select='user:PadRight("test-string", 20)'/>
          </circumference>
        </circle>
      </xsl:for-each>
    </circles>
  </xsl:template>
</xsl:stylesheet>";

		string cs1 = @"<msxsl:script language='C#' implements-prefix='user'>
    <![CDATA[
        public string PadRight( string str, int padding) {
            return str.PadRight(padding);
        }
        public double circumference(double radius){
           double pi = 3.14;
           double circ = pi*radius*2;
           return circ;
        }
      ]]>
   </msxsl:script>";
		string vb1 = @"<msxsl:script language='VB' implements-prefix='user'>
     <![CDATA[
     public function circumference(radius as double) as double
       dim pi as double = 3.14
       dim circ as double = pi*radius*2
       return circ
     end function
     public function PadRight(str as string, padding as integer) as string
            return str.PadRight(padding)
     end function
      ]]>
   </msxsl:script>";
		string js1 = @"<msxsl:script language='JScript' implements-prefix='user'>
     <![CDATA[
     function circumference(radius : double) : double {
       var pi : double = 3.14;
       var circ : double = pi*radius*2;
       return circ;
     }
     function PadRight(str : String, padding : int) {
       return str.PadRight(padding);
     }
      ]]>
   </msxsl:script>";

		XslTransform xslt;

		[SetUp]
		public void GetReady ()
		{
			xslt = new XslTransform ();
		}

		[Test]
		[Category ("NotWorking")] // it depends on "mcs" existence
		public void TestCSharp ()
		{
			string style = xslstring.Replace ("***** rewrite here *****", cs1);
			XmlTextReader xr = new XmlTextReader (style, XmlNodeType.Document, null);
			xslt.Load (xr);
			xslt.Transform (doc.CreateNavigator (), null, new XmlTextWriter (new StringWriter ()));
		}

		[Test]
		[Category ("NotWorking")] // it depends on "mbas" existence
		public void TestVB ()
		{
			string style = xslstring.Replace ("***** rewrite here *****", vb1);
			XmlTextReader xr = new XmlTextReader (style, XmlNodeType.Document, null);
			xslt.Load (xr);
			xslt.Transform (doc.CreateNavigator (), null, new XmlTextWriter (new StringWriter ()));
		}

		[Test]
		[Category ("NotWorking")] // it depends on "mjs" existence
		public void TestJScript ()
		{
			string style = xslstring.Replace ("***** rewrite here *****", js1);
			XmlTextReader xr = new XmlTextReader (style, XmlNodeType.Document, null);
			xslt.Load (xr);
			xslt.Transform (doc.CreateNavigator (), null, new XmlTextWriter (new StringWriter ()));
		}

		[Test]
		[Ignore ("Actually it should throw compile exception")]
		[ExpectedException (typeof (XsltException))]
		public void InvalidScript ()
		{
			string script = @"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:user='urn:my-scripts'
    xmlns:msxsl='urn:schemas-microsoft-com:xslt'>
    <!-- -->
    <xsl:output method='html' indent='no' />
    <!-- -->
    <xsl:template match='/project'>
        <xsl:if test='user:BadScriptFunction('test')'></xsl:if>
    </xsl:template>
    <!-- -->
    <msxsl:script language='C#' implements-prefix='user'>
        <![CDATA[
            string BadScriptFunction(string test) {
                xxx;
            }
        ]]>
    </msxsl:script>
    <!-- -->
</xsl:stylesheet>";
			xslt.Load (new XmlTextReader (script, XmlNodeType.Document, null));
		}

		[Test]
		[Category ("NotWorking")] // it depends on "mcs" existence
		public void CompilerWarningsShouldBeIgnored ()
		{
			string script = @"<xslt:stylesheet xmlns:xslt='http://www.w3.org/1999/XSL/Transform' version='1.0' xmlns:msxsl='urn:schemas-microsoft-com:xslt'
    xmlns:stringutils='urn:schemas-sourceforge.net-blah'>
    <xslt:output method='text' />
    <msxsl:script language='C#' implements-prefix='stringutils'>
    <![CDATA[
        string PadRight( string str, int padding) {
            return str.PadRight(padding);
        }
    ]]>
    </msxsl:script>
    <xslt:template match='project'>
        <xslt:apply-templates select='target[string(@description) != '' ]'>
            <xslt:sort select='@name' order='ascending' />
        </xslt:apply-templates>
    </xslt:template>
    <xslt:template match='target'>
        <xslt:value-of select='stringutils:PadRight(@name, 20)' />
        <xslt:value-of select='@description' />
    </xslt:template>
</xslt:stylesheet>";
			xslt.Load (new XmlTextReader (script, XmlNodeType.Document, null));
			xslt.Transform (doc.CreateNavigator (), null, new XmlTextWriter (TextWriter.Null));
		}

		[Test]
		[Category ("NotWorking")] // it depends on "mcs" existence
		public void CompileNoLineInfoSource ()
		{
			// bug #76116
			string xslt = @"<xslt:stylesheet xmlns:xslt='http://www.w3.org/1999/XSL/Transform' version='1.0' xmlns:msxsl='urn:schemas-microsoft-com:xslt' xmlns:stringutils='urn:schemas-sourceforge.net-blah' xmlns:nant='unknown-at-this-time'>
    <xslt:output method='text' />
    <msxsl:script language='C#' implements-prefix='stringutils'>
    <![CDATA[
        string PadRight( string str, int padding) {
            return str.PadRight(padding);
        }
    ]]>
    </msxsl:script>
    <xslt:template match='/'>
        <foo/>
    </xslt:template>
</xslt:stylesheet>";
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (xslt);

			XslTransform t = new XslTransform ();
			t.Load (doc);
		}
	}
}


text:
using Avalonia.Markup.Xaml;
using System;
using System.Runtime.InteropServices;

namespace WalletWasabi.Fluent.Helpers
{
	public class PlatformExtension : MarkupExtension
	{
		public PlatformExtension()
		{
		}

		public PlatformExtension(object defaultValue)
		{
			Default = defaultValue;
		}

		public object? Default { get; set; }

		public object? Osx { get; set; }

		public object? Linux { get; set; }

		public object? Windows { get; set; }

		public override object? ProvideValue(IServiceProvider serviceProvider)
		{
			var result = Default;

			if (Osx != null && RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
			{
				result = Osx;
			}
			else if (Linux != null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
			{
				result = Linux;
			}
			else if (Windows != null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				result = Windows;
			}

			return result;
		}
	}
}


text:
Erlang stdlib implementation on Java, based on JInterface

# Contact Us

If you find any **bugs** or have a **problem** while using this library, please [open an issue](https://github.com/inaka/jinterface_stdlib/issues/new) in this repo (or a pull request :)).

And you can check all of our open-source projects at [inaka.github.io](http://inaka.github.io)

# About

[Erlang](http://erlang.org) comes with a very nice java library ([jinterface](http://www.erlang.org/doc/apps/jinterface/)) that let's you _do Erlang stuff_ inside a Java program.
But Erlang programmers are used to write applications using [OTP](http://www.erlang.org/doc/).
If you check otp's code you may come accross [this comment](https://github.com/erlang/otp/blob/maint/lib/stdlib/src/gen.erl#L228-L233) that seems to indicate that there is OTP support for Java nodes. Turns out… there is no such thing.
This library goal is to fill that vacuum.

# Structure

This project provides [abstract] classes that work as your usual OTP behaviours and modules, according to the following table:

| Class | OTP Module |
| ----- | ---------- |
| `OtpGenServer` | `gen_server` |
| `OtpSysProcess` | `gen` |

# Usage

To use it just include ``priv/jinterface_stdlib.jar`` in your classpath as you do with the erlang provided jinterface.jar

## Documentation

To generate the [documentation](http://inaka.github.io/jinterface_stdlib/), run

```sh
$ make doc
```

## Usage Example

You can see this library being used in [lucene_server](http://github.com/inaka/lucene_server)


text:
import socket
import cPickle as pickle
import struct
import string
import re
import logging
import sys
import base64
import urllib2
import json
import os

class Measurement(object):
    def __init__(self):
        self.NAME = ''  # metric name
        self.SOURCE = ''  # The source of the metric (used for librato source)
        self.VALUE = ''   # numerical value of the measurement
        self.TIME = ''    # The epoc time when the measurement was taken

    def __repr__(self):
        return "Name: %s, Source: %s, Value: %s, Time: %s" % (self.NAME,
        self.SOURCE, self.VALUE, self.TIME)

###########################################################
# #### Librato Backend
class librato(object):
    def __init__(self, cfg):
        """
        Implements the librato backend-module
        """

        self.log = logging.getLogger("log.backends.librato")
        self.log.info("Librato Backend Initialized")
        self.api = "https://metrics-api.librato.com"
        self.flush_timeout_secs = 5
        self.gauges = {}
        self.whitelist = []
        self.metrics_sent = 0
        self.max_metrics_payload = 500

        try:
            cfg["librato_email"]
        except:
            self.log.critical("please define librato_email")
            sys.exit(1)
        else:
            self.email = cfg['librato_email']

        try:
            cfg["librato_token"]
        except:
            self.log.critical("please define librato_token")
            sys.exit(1)
        else:
            self.token = cfg['librato_token']

        try:
            cfg["librato_floor_time_secs"]
        except:
            self.floor_time_secs = 10
        else:
            self.floor_time_secs = cfg["librato_floor_time_secs"]

        try:
            cfg["librato_whitelist"]
        except:
            self.whitelist = [re.compile(".*")]
        else:
            for pattern in cfg["librato_whitelist"]:
                self.log.debug("adding librato whitelist pattern %s" % pattern)
                self.whitelist.append(re.compile(pattern))

        try:
            uname = os.uname()
            system = "; ".join([uname[0], uname[4]])
        except:
            system = os.name()

        sink_name = "gryphie-librato"
        sink_version = "0.0.1"
        pver = sys.version_info
        self.user_agent = '%s/%s (%s) Python-Urllib2/%d.%d' % \
                     (sink_name, sink_version,
                      system, pver[0], pver[1])

        base64string = base64.encodestring('%s:%s' % (self.email, self.token))
        self.auth = base64string.translate(None, '\n')

        self.headers = {
            'Content-Type': 'application/json',
            'User-Agent': self.user_agent,
            'Authorization': 'Basic %s' % self.auth
        }

    def fix_path(self, m):
        path = ''

        try:
            m.SOURCE
        except:
            m.SOURCE = os.uname()[1]

        pdict=m.NAME.split('.')

        while m.SOURCE in pdict:
            pdict.remove(m.SOURCE)

        path = string.join(pdict)
        return path

    def not_in_whitelist(self, k):
        # return True if k isn't whitelisted
        wl_match = True
        for pattern in self.whitelist:
            if pattern.search(k) is not None:
                return False
        return True

    def add_measure(self, m):
        ts = float(m.TIME)
        if self.floor_time_secs is not None:
            ts = (ts / self.floor_time_secs) * self.floor_time_secs

        name = self.fix_path(m)
        source = m.SOURCE

        k = "%s\t%s" % (name, source)

        #bail if this metric isn't whitelisted
        if self.not_in_whitelist(k):
            return None

        #add the metric to our gauges dict
        if k not in self.gauges:
            self.gauges[k] = {
                'name': name,
                'source': source,
                'measure_time': ts,
            }

        value = float(m.VALUE)
        self.gauges[k]['value'] = value

    def post_payload(self, g):
        """
        POST a payload to Librato.
        """
        body = json.dumps({'gauges': g})
        url = "%s/v1/metrics" % (self.api)
        req = urllib2.Request(url, body, self.headers)

        try:
            f = urllib2.urlopen(req, timeout=self.flush_timeout_secs)
            f.close()
        except urllib2.HTTPError as error:
            self.metrics_sent = 0
            body = error.read()
            self.log.warning('Failed to send metrics to Librato: Code: \
                                %d . Response: %s' % (error.code, body))
        except IOError as error:
            self.metrics_sent = 0
            if hasattr(error, 'reason'):
                self.log.warning('Error when sending metrics Librato \
                                    (%s)' % (error.reason))
            elif hasattr(error, 'code'):
                self.log.warning('Error when sending metrics Librato \
                                    (%s)' % (error.code))
            else:
                self.log.warning('Error when sending metrics Librato \
                                    and I dunno why')

    def send(self, metrics):

        self.metrics_sent = len(metrics)
        # Construct the output
        for m in metrics:
            self.add_measure(m)

        # Nothing to do
        if len(self.gauges) == 0:
            return 0

        metrics = []
        count = 0
        for g in self.gauges.values():
            metrics.append(g)
            count += 1

            if count >= self.max_metrics_payload:
                self.post_payload(metrics)
                count = 0
                metrics = []

        if count > 0:
            self.post_payload(metrics)
            self.gauges = {}

        return self.metrics_sent

############################################################
# #### Carbon back-end #####

class carbon(object):
    def __init__(self, cfg):
        self.log = logging.getLogger("log.backends.carbon")
        self.log.info("Carbon Backend Initialized")

        self.carbon_servers=[]
        servers=''
        try:
            cfg['carbon_servers']
        except:
            self.carbon_servers = [{'127.0.0.1' : 2004}]
        else:
            serv = cfg['carbon_servers']
            if ":" in serv:
                s, p= serv.split(":")
                s = socket.gethostbyname(s)
                p = int(p)
            else:
                s = socket.gethostbyname(serv)
                p = 2004
            print("appending server:%s port:%s"%(s,p))
            self.carbon_servers.append({ s : p })

        try:
            cfg['replacement_character']
        except:
            self.replacement_character = '_'
        else:
            self.replacement_character = cfg['replacement_character']

        try:
            cfg['carbon_max_metrics']
            self.carbon_max_metrics = cfg['carbon_max_metrics']
        except:
            self.carbon_max_metrics = 200

        try:
            cfg['use_service_desc']
            self.use_service_desc = cfg['use_service_desc']
        except:
            self.use_service_desc = False

    def convert_pickle(self, metrics):
        """
        Converts the metric obj list into a pickle message
        """
        pickle_list = []
        messages = []
        for m in metrics:
            path = self.fix_string(m.NAME)
            value = m.VALUE
            timestamp = m.TIME
            metric_tuple = (path, (timestamp, value))
            pickle_list.append(metric_tuple)
        for pickle_list_chunk in self.chunks(pickle_list,
                                             self.carbon_max_metrics):
            payload = pickle.dumps(pickle_list_chunk)
            header = struct.pack("!L", len(payload))
            message = header + payload
            messages.append(message)
        return messages

    def chunks(self, l, n):
        """ Yield successive n-sized chunks from l.
        """
        for i in xrange(0, len(l), n):
            yield l[i:i + n]

    def fix_string(self, my_string):
        """
        takes a string and replaces whitespace and invalid carbon chars with
        the global replacement_character
        """
        invalid_chars = '~!@#$:;%^*()+={}[]|\/<>'
        my_string = re.sub("\s", self.replacement_character, my_string)
        for char in invalid_chars:
            my_string = my_string.replace(char, self.replacement_character)
        return my_string

    def send(self, metrics):
        """
        Connect to the Carbon server
        Send the metrics
        """
        ret = 0
        sock = socket.socket()
        for s in self.carbon_servers:
            print("parsing carbon_servers: %s"%s)
            server,port=s.items()[0]
            self.log.debug("Connecting to carbon at %s:%s" %
                          (server, port))
            try:
                sock.connect((server, port))
                self.log.debug("connected")
            except Exception, ex:
                self.log.warning("Can't connect to carbon: %s:%s %s" % (
                                 server, port, ex))

            messages = self.convert_pickle(metrics)
            try:
                for message in messages:
                    sock.sendall(message)
            except Exception, ex:
                self.log.critical("Can't send message to carbon error:%s" % ex)
            else:
                ret += 1
            sock.close()
        return ret

# ###########################################################
# #### statsd backend  #######################################

class statsd(object):
    def __init__(self, cfg):
        self.log = logging.getLogger("log.backends.statsd")
        self.log.info("Statsd backend initialized")

        servers=''
        self.statsd_servers=[]
        try:
            cfg['statsd_servers']
        except:
            self.statsd_servers = [{ '127.0.0.1' : 8125 }]
        else:
            serv=cfg['statsd_servers']
            if ":" in serv:
                s, p= serv.split(":")
                s = socket.gethostbyname(s)
                p = int(p)
            else:
                s = socket.gethostbyname(serv)
                p = 8125
            self.statsd_servers.append({ s : p })

    def convert(self, metrics):
        # Converts the metric object list into a list of statsd tuples
        out_list = []
        for m in metrics:
            value = "%s|g" % m.VALUE  # FIXME: you wanted a gauge right?
            metric_tuple = "%s:%s" % (m.NAME, value)
            out_list.append(metric_tuple)

        return out_list

    def send(self, metrics):
        # Fire metrics at the statsd server and hope for the best (loludp)
        ret = True
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        mlist = self.convert(metrics)
        ret = 0

        for s in self.statsd_servers:
            server, port = s.items()[0]
            self.log.debug("sending to statsd at %s:%s" %
                          (server, port))
            for m in mlist:
                try:
                    sock.sendto(m, (server, port))
                except Exception, ex:
                    self.log.critical("Can't send metric to statsd error:%s"
                                      % ex)
                else:
                    ret += 1

        return ret

# ###########################################################
# #### stdout backend  #######################################

class stdout(object):
    def __init__(self, cfg):
        self.log = logging.getLogger("log.backends.stdout")
        self.log.info("STDOUT Backend Initialized")

    def send(self, metrics):
        ret = 0
        print("-------")
        for metric in metrics:
            ret += 1
            print(metric)
            print("-------")

        return ret

# ###########################################################
# #### start here  #######################################

if __name__ == "__main__":
    print("I'm just a lowly module")
    sys.exit(42)


text:
var async     = require('async');
var cleankill = require('cleankill');

var CliReporter = require('./clireporter');
var Context     = require('./context');
var steps       = require('./steps');

/**
 * Runs a suite of web component tests.
 *
 * The returned Context (a kind of EventEmitter) fires various events to allow
 * you to track the progress of the tests:
 *
 * Lifecycle Events:
 *
 * `run-start`
 *   WCT is ready to begin spinning up browsers.
 *
 * `browser-init` {browser} {stats}
 *   WCT is ready to begin spinning up browsers.
 *
 * `browser-start` {browser} {metadata} {stats}
 *   The browser has begun running tests. May fire multiple times (i.e. when
 *   manually refreshing the tests).
 *
 * `sub-suite-start` {browser} {sharedState} {stats}
 *   A suite file has begun running.
 *
 * `test-start` {browser} {test} {stats}
 *   A test has begun.
 *
 * `test-end` {browser} {test} {stats}
 *  A test has ended.
 *
 * `sub-suite-end` {browser} {sharedState} {stats}
 *   A suite file has finished running all of its tests.
 *
 * `browser-end` {browser} {error} {stats}
 *   The browser has completed, and it shutting down.
 *
 * `run-end` {error}
 *   WCT has run all browsers, and is shutting down.
 *
 * Generic Events:
 *
 *  * log:debug
 *  * log:info
 *  * log:warn
 *  * log:error
 *
 * @param {!Object|!Context} options The configuration, as specified in,
 *     `./config.js` or an already formed `Context` object.
 * @param {function(*)} done callback indicating error or success.
 * @return {!Context}
 */
module.exports = function test(options, done) {
  var context = (options instanceof Context) ? options : new Context(options);

  // We assume that any options related to logging are passed in via the initial
  // `options`.
  if (context.options.output) {
    new CliReporter(context, context.options.output, context.options);
  }

  async.series([
    steps.setupOverrides.bind(steps, context),
    steps.loadPlugins.bind(steps, context),
    steps.configure.bind(steps, context),
    steps.prepare.bind(steps, context),
    steps.runTests.bind(steps, context),
  ], function(error) {
    if (options.skipCleanup) {
      done(error);
    } else {
      cleankill.close(done.bind(null, error));
    }
  });

  return context;
};


text:
Commands
========

The Makefile contains the central entry points for common tasks related to this project.

Syncing data to S3
^^^^^^^^^^^^^^^^^^

* `make sync_data_to_s3` will use `aws s3 sync` to recursively sync files in `data/` up to `s3://gudataengineering/data/`.
* `make sync_data_from_s3` will use `aws s3 sync` to recursively sync files from `s3://gudataengineering/data/` to `data/`.


text:
"""Support for Eufy lights."""
import logging

import lakeside

from homeassistant.components.light import (
    ATTR_BRIGHTNESS,
    ATTR_COLOR_TEMP,
    ATTR_HS_COLOR,
    SUPPORT_BRIGHTNESS,
    SUPPORT_COLOR,
    SUPPORT_COLOR_TEMP,
    Light,
)
import homeassistant.util.color as color_util
from homeassistant.util.color import (
    color_temperature_kelvin_to_mired as kelvin_to_mired,
    color_temperature_mired_to_kelvin as mired_to_kelvin,
)

_LOGGER = logging.getLogger(__name__)

EUFY_MAX_KELVIN = 6500
EUFY_MIN_KELVIN = 2700

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up Eufy bulbs."""
    if discovery_info is None:
        return
    add_entities([EufyLight(discovery_info)], True)

class EufyLight(Light):
    """Representation of a Eufy light."""

    def __init__(self, device):
        """Initialize the light."""

        self._temp = None
        self._brightness = None
        self._hs = None
        self._state = None
        self._name = device["name"]
        self._address = device["address"]
        self._code = device["code"]
        self._type = device["type"]
        self._bulb = lakeside.bulb(self._address, self._code, self._type)
        self._colormode = False
        if self._type == "T1011":
            self._features = SUPPORT_BRIGHTNESS
        elif self._type == "T1012":
            self._features = SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP
        elif self._type == "T1013":
            self._features = SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_COLOR
        self._bulb.connect()

    def update(self):
        """Synchronise state from the bulb."""
        self._bulb.update()
        if self._bulb.power:
            self._brightness = self._bulb.brightness
            self._temp = self._bulb.temperature
            if self._bulb.colors:
                self._colormode = True
                self._hs = color_util.color_RGB_to_hs(*self._bulb.colors)
            else:
                self._colormode = False
        self._state = self._bulb.power

    @property
    def unique_id(self):
        """Return the ID of this light."""
        return self._address

    @property
    def name(self):
        """Return the name of the device if any."""
        return self._name

    @property
    def is_on(self):
        """Return true if device is on."""
        return self._state

    @property
    def brightness(self):
        """Return the brightness of this light between 0..255."""
        return int(self._brightness * 255 / 100)

    @property
    def min_mireds(self):
        """Return minimum supported color temperature."""
        return kelvin_to_mired(EUFY_MAX_KELVIN)

    @property
    def max_mireds(self):
        """Return maximu supported color temperature."""
        return kelvin_to_mired(EUFY_MIN_KELVIN)

    @property
    def color_temp(self):
        """Return the color temperature of this light."""
        temp_in_k = int(
            EUFY_MIN_KELVIN + (self._temp * (EUFY_MAX_KELVIN - EUFY_MIN_KELVIN) / 100)
        )
        return kelvin_to_mired(temp_in_k)

    @property
    def hs_color(self):
        """Return the color of this light."""
        if not self._colormode:
            return None
        return self._hs

    @property
    def supported_features(self):
        """Flag supported features."""
        return self._features

    def turn_on(self, **kwargs):
        """Turn the specified light on."""
        brightness = kwargs.get(ATTR_BRIGHTNESS)
        colortemp = kwargs.get(ATTR_COLOR_TEMP)
        # pylint: disable=invalid-name
        hs = kwargs.get(ATTR_HS_COLOR)

        if brightness is not None:
            brightness = int(brightness * 100 / 255)
        else:
            if self._brightness is None:
                self._brightness = 100
            brightness = self._brightness

        if colortemp is not None:
            self._colormode = False
            temp_in_k = mired_to_kelvin(colortemp)
            relative_temp = temp_in_k - EUFY_MIN_KELVIN
            temp = int(relative_temp * 100 / (EUFY_MAX_KELVIN - EUFY_MIN_KELVIN))
        else:
            temp = None

        if hs is not None:
            rgb = color_util.color_hsv_to_RGB(hs[0], hs[1], brightness / 255 * 100)
            self._colormode = True
        elif self._colormode:
            rgb = color_util.color_hsv_to_RGB(
                self._hs[0], self._hs[1], brightness / 255 * 100
            )
        else:
            rgb = None

        try:
            self._bulb.set_state(
                power=True, brightness=brightness, temperature=temp, colors=rgb
            )
        except BrokenPipeError:
            self._bulb.connect()
            self._bulb.set_state(
                power=True, brightness=brightness, temperature=temp, colors=rgb
            )

    def turn_off(self, **kwargs):
        """Turn the specified light off."""
        try:
            self._bulb.set_state(power=False)
        except BrokenPipeError:
            self._bulb.connect()
            self._bulb.set_state(power=False)


text:
//
//  ILSwapMvrContactSupport.h
//  SwapKit
//
//  Created by ∞ on 07/02/10.

#import <SwapKit/SwapKit.h>
#import <AddressBook/AddressBook.h>

#define kMvrContactAsPropertyListType @"net.infinite-labs.Slide.AddressBookPersonPropertyList"

@interface ILSwapItem (ILSwapMvrContactSupport)

+ (ILSwapItem*) moverContactItemFromPersonRecord:(ABRecordRef) record;
- (ABRecordRef) copyPersonRecordFromMoverContactItem;

@end


text:
This is a tool for prioritizing code smells using developers' context. Note that this tool supports only class level code smells. Please refer to our [publication](#publication) for more details.
## How to use
1. Prepare the input files: code smell file and impact analysis file (see [Input File Format](#input-file-format)).
2. Use the following command to generate the result.
3. The result will be generated as Result.csv (see [Output File Format](#output-file-format)).
#### Usage:
```
 python CSP.py code_smell_file_name impact_analysis_file_name [alpha=1] [cut_point=40]
```
*alpha* = The combination ratio of *CRI* and *Severity*
*cut_point* = The maximum number of impact analysis results of each issue that are going to be considered
For the details, please refer to our [publication](#publication).

#### Example:
```
python CSP.py Smells.csv IA.csv 1 40
```

## Input File Format
#### Code smell file:

| Smell ID	| Severity	| Class Name	| Package Name	 | Smell Type |
| --- | ------- |  ---------- |  ----------------- |  --------- |
| 1  | 7        |  ClassA     |  com.package.ui    |  God       |
| 2  | 8        |  ClassB     |  com.package.model |  Blob      |
| .  | .        | .           | .                  | .          |

*Smell ID* = A Unique ID of each smell
*Severity* = An integer representing the severity of each smell (e.g. 1-10)
*Package Name* = Package name of the class (in case there is folder name in front of it, the tool will automatically remove the folder name, e.g., src/java/com.package.ui → com.package.ui)

Example: Smells.csv

#### Impact analysis file:

| Issue ID  | Class Full Name            | Score |
| --------- | -------------------------- | ----- |
| 1001      | com.package.ui.ClassA      | 0.321 |
| 1001      | com.package.model.ClassB   | 0.211 |
| .         | .                          | .     |

Please remove the header line of the file before using the tool (if any).

Example: IA.csv

## Output File Format
#### Result file:
| Smell ID |	Ranking	| CRI        	| Severity	| Class Name	       | Package Name |
| -------- | ------- |  ---------- |  ------- |  ---------------- | ------------ |
| 70       | 1.0     |  3.21       |  2       | com.package.ui    |  God         |
| 25       | 0.9     |  2.13       |  3       | com.package.model |  Blob        |
| .        | .       | .           | .        | .                 | .            |

*Ranking* = A criterion used for prioritizing code smell generated by combining CRI and Severity.
*CRI* = Context Relevance Index
For the details on the calculation of *Ranking* and *CRI*, please refer to our [publication](#publication).

Example: Result.csv
## Publication
To be added


text:
<?php

namespace AkeleiBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AkeleiBundle extends Bundle
{
}


text:
create table sdata_profile (
   userid varchar(255) not null,
   basic text,
   aboutme text,
   contactinfo text,
   education text,
   job text,
   websites text,
   academic text,
   picture text,
   primary key  (userid)
)
ENGINE = InnoDB
CHARACTER SET utf8;


text:
all: tinyply-core

tinyply-core: tinyply.h tinyply.cpp example.cpp
	$(CXX) tinyply.cpp example.cpp -std=c++11 -o $@ -Wall -Wpedantic

.PHONY: clean
clean:
	rm tinyply-core


text:
package gov.nasa.ensemble.core.plan.constraints.operations;

import gov.nasa.ensemble.core.model.plan.EPlanElement;
import gov.nasa.ensemble.core.model.plan.constraints.TemporalChain;
import gov.nasa.ensemble.core.plan.constraints.TemporalChainUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.junit.Assert;

public class MoveOutsideOfChainPostconditionRunnable extends ChainRepeatabilityPostconditionRunnable {

	private final Set<TemporalChain> completelyMovedChains = new HashSet<TemporalChain>();
	private final Set<TemporalChain> allButOneMovedChains = new HashSet<TemporalChain>();
	private final Set<TemporalChain> unaffectedChains = new HashSet<TemporalChain>();
	private final List<List<EPlanElement>> unselectedChainsMembers = new ArrayList<List<EPlanElement>>();
	private final List<List<EPlanElement>> selectedChainsMembers = new ArrayList<List<EPlanElement>>();

	public MoveOutsideOfChainPostconditionRunnable(ChainTestPlan plan, EPlanElement[] selectedElements, EPlanElement targetElement) {
		super("move", plan, selectedElements);
		List<EPlanElement> selectedElementsList = Arrays.asList(selectedElements);
		for (TemporalChain chain : TemporalChainUtils.getChains(plan.plan)) {
			List<EPlanElement> unselectedSubset = new ArrayList<EPlanElement>();
			List<EPlanElement> selectedSubset = new ArrayList<EPlanElement>();
			for (EPlanElement chainElement : chain.getElements()) {
				if (selectedElementsList.contains(chainElement)) {
					selectedSubset.add(chainElement);
				} else {
					unselectedSubset.add(chainElement);
				}
			}
			if (selectedSubset.isEmpty()) {
				unaffectedChains.add(chain);
			} else if (unselectedSubset.isEmpty()) {
				completelyMovedChains.add(chain);
			} else if (unselectedSubset.size() == 1) {
				allButOneMovedChains.add(chain);
			}
			if (unselectedSubset.size() >= 2 && !selectedSubset.isEmpty()) {
				unselectedChainsMembers.add(unselectedSubset);
			}
			if (selectedSubset.size() >= 2 && !unselectedSubset.isEmpty()) {
				selectedChainsMembers.add(selectedSubset);
			}
		}
	}

	@Override
	public void run() {
		Set<TemporalChain> chains = TemporalChainUtils.getChains(plan.plan);
		Assert.assertTrue("chains that have all of their activities " + actionName  + " should still exist. ",
			              chains.containsAll(completelyMovedChains));
		Assert.assertTrue("chains that have all but one of their activities " + actionName + " should be removed. ",
			              Collections.disjoint(allButOneMovedChains, chains));
		Assert.assertTrue("chains that had no " + actionName + " activities should remain. ",
			              chains.containsAll(unaffectedChains));
		chains.removeAll(completelyMovedChains);
		chains.removeAll(unaffectedChains); // leaving only the new chains
		Assert.assertEquals("new chains should number the chains leftover from unselected elements plus the new chains from the selected elements. ",
			                unselectedChainsMembers.size() + selectedChainsMembers.size(), chains.size());
		for (TemporalChain chain : chains) {
			List<EPlanElement> chainElements = chain.getElements();
			EPlanElement firstPlanElement = chainElements.iterator().next();
			List<EPlanElement> expectedChainMembers = null;
			for (List<EPlanElement> unselectedChainMembers : unselectedChainsMembers) {
				if (unselectedChainMembers.iterator().next() == firstPlanElement) {
					Assert.assertNull("each plan element should only be in one chainMembers list", expectedChainMembers);
					expectedChainMembers = unselectedChainMembers;
				}
			}
			for (List<EPlanElement> selectedChainMembers : selectedChainsMembers) {
				if (selectedChainMembers.iterator().next() == firstPlanElement) {
					Assert.assertNull("each plan element should only be in one chainMembers list", expectedChainMembers);
					expectedChainMembers = selectedChainMembers;
				}
			}
			Assert.assertNotNull("a new chain should correspond to one of the expected chainMembers", expectedChainMembers);
			if (expectedChainMembers != null) {
				Assert.assertEquals("a new chain should be the same size as expected",
						expectedChainMembers.size(), chainElements.size());
				Iterator<EPlanElement> chainElementIterator = chainElements.iterator();
				Iterator<EPlanElement> expectedChainMembersIterator = expectedChainMembers.iterator();
				while (chainElementIterator.hasNext() && expectedChainMembersIterator.hasNext()) {
					EPlanElement chainPlanElement = chainElementIterator.next();
					EPlanElement memberPlanElement = expectedChainMembersIterator.next();
					Assert.assertEquals("all elements in the resulting chain should exist in the order expected", memberPlanElement, chainPlanElement);
				}
			}
		}
	}

}


text:
Template.templateBasicHeader.events({
    'click a.lang': function (e) {
        lang = 'undefined';
        $this = $(e.target);
        lang = $this.data("lang");
        TAPi18n.setLanguage(lang);
    },
    'click #btnLogout': function () {
        Meteor.logout(function () {
            Router.go('usersLogin');
        });
    }
    , 'click .logo-head': function (e, t) {
        e.preventDefault();
        if (Meteor.user() != null) {
            $('.sidebar')
                .sidebar('toggle');
        }
    }
});
Template.templateBasicHeader.onRendered(function () {

})


text:
namespace NLog.UnitTests.LayoutRenderers
{
    using System;
    using Xunit;

    public class ExceptionDataLayoutRendererTests : NLogTestBase
    {
        [Fact]
        public void ExceptionWithDataItemIsLoggedTest()
        {
            const string exceptionMessage = "Test exception";
            const string exceptionDataKey = "testkey";
            const string exceptionDataValue = "testvalue";

            var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
            <nlog>
                <targets>
                    <target name='debug' type='Debug' layout='${exceptiondata:" + exceptionDataKey + @"}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug' />
                </rules>
            </nlog>").LogFactory;
            Exception ex = new ArgumentException(exceptionMessage);
            ex.Data.Add(exceptionDataKey, exceptionDataValue);

            logFactory.GetCurrentClassLogger().Error(ex, "msg");

            logFactory.AssertDebugLastMessage("debug", exceptionDataValue);
        }

        [Fact]
        public void ExceptionWithOutDataIsNotLoggedTest()
        {
            const string exceptionMessage = "Test exception";
            const string exceptionDataKey = "testkey";

            var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
            <nlog>
                <targets>
                    <target name='debug' type='Debug' layout='${exceptiondata:" + exceptionDataKey + @"}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug' />
                </rules>
            </nlog>").LogFactory;

            Exception ex = new ArgumentException(exceptionMessage);
            logFactory.GetCurrentClassLogger().Error(ex, "msg");

            logFactory.AssertDebugLastMessage("");
        }

        [Fact]
        public void ExceptionUsingSpecifiedParamLogsProperlyTest()
        {
            const string exceptionMessage = "I don't like nullref exception!";
            const string exceptionDataKey = "testkey";
            const string exceptionDataValue = "testvalue";

            var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
            <nlog>
                <targets>
                    <target name='debug' type='Debug' layout='${exceptiondata:item=" + exceptionDataKey + @"}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug' />
                </rules>
            </nlog>").LogFactory;

            Exception ex = new ArgumentException(exceptionMessage);
            ex.Data.Add(exceptionDataKey, exceptionDataValue);
            logFactory.GetCurrentClassLogger().Error(ex);
            logFactory.AssertDebugLastMessage(exceptionDataValue);
        }

        [Fact]
        public void BadDataForItemResultsInEmptyValueTest()
        {
            const string exceptionMessage = "I don't like nullref exception!";
            const string exceptionDataKey = "testkey";
            const string exceptionDataValue = "testvalue";

            var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
            <nlog>
                <targets>
                    <target name='debug' type='Debug' layout='${exceptiondata:item=@}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug' />
                </rules>
            </nlog>").LogFactory;

            Exception ex = new ArgumentException(exceptionMessage);
            ex.Data.Add(exceptionDataKey, exceptionDataValue);
            logFactory.GetCurrentClassLogger().Error(ex);
            logFactory.AssertDebugLastMessage("");
        }

        [Fact]
        public void NoDatkeyTest()
        {
            const string exceptionMessage = "I don't like nullref exception!";
            const string exceptionDataKey = "testkey";
            const string exceptionDataValue = "testvalue";
            var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
            <nlog>
                <targets>
                    <target name='debug' type='Debug' layout='${exceptiondata:}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug' />
                </rules>
            </nlog>").LogFactory;

            Exception ex = new ArgumentException(exceptionMessage);
            ex.Data.Add(exceptionDataKey, exceptionDataValue);
            logFactory.GetCurrentClassLogger().Error(ex);
            logFactory.AssertDebugLastMessage("");
        }

        [Fact]
        public void NoDatkeyUingParamTest()
        {
            const string exceptionMessage = "I don't like nullref exception!";
            const string exceptionDataKey = "testkey";
            const string exceptionDataValue = "testvalue";
            var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
            <nlog>
                <targets>
                    <target name='debug' type='Debug' layout='${exceptiondata:item=}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug' />
                </rules>
            </nlog>").LogFactory;

            Exception ex = new ArgumentException(exceptionMessage);
            ex.Data.Add(exceptionDataKey, exceptionDataValue);
            logFactory.GetCurrentClassLogger().Error(ex);
            logFactory.AssertDebugLastMessage("");
        }

        [Fact]
        public void BaseExceptionFlippedTest()
        {
            const string exceptionDataKey = "testkey";
            const string exceptionDataValue = "testvalue";
            var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
            <nlog>
                <targets>
                    <target name='debug' type='Debug' layout='${exceptiondata:item=" + exceptionDataKey + @":BaseException=true}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug' />
                </rules>
            </nlog>").LogFactory;

            Exception exceptionToTest;
            try
            {
                try
                {
                    try
                    {
                        var except = new ArgumentException("Inner Exception");
                        except.Data[exceptionDataKey] = exceptionDataValue;
                        throw except;
                    }
                    catch (Exception exception)
                    {
                        throw new System.ArgumentException("Wrapper1", exception);
                    }
                }
                catch (Exception exception)
                {
                    throw new ApplicationException("Wrapper2", exception);
                }
            }
            catch (Exception ex)
            {
                exceptionToTest = ex;
            }

            logFactory.GetCurrentClassLogger().Fatal(exceptionToTest, "msg");

            logFactory.AssertDebugLastMessage(exceptionDataValue);
        }
    }
}