text:
feature = <<~HEREDOC
  When developer wants to install analytics code snippet,
  he wants to create new code snippet with tag 'head',
  so that its text will be rendered in application layout
HEREDOC

RSpec.feature feature, issues: ['railgun#89'] do
  scenario = <<~HEREDOC
    Given developer is on the new snippet page
    When he fills in slug and text and clicks 'Create Snippet'
    Then new snippet record with that data is present
  HEREDOC

  scenario scenario do
    login_as create(:developer)
    visit new_staff_snippet_path

    fill_in 'snippet_slug', with: 'slug'
    fill_in 'snippet_text', with: 'text'
    click_button 'Create Snippet'

    expect(Snippet.find_by_slug(:slug).text).to eq('text')
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">

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

  <title>Table of Contents — CookCC 0.4.3 documentation</title>

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

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

        <link rel="index" title="Index"
              href="genindex.html"/>
        <link rel="search" title="Search" href="search.html"/>
    <link rel="top" title="CookCC 0.4.3 documentation" href="index.html"/>
        <link rel="next" title="CookCC documentation" href="index.html"/>

             CookCC

                0.4.3

  <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>

CookCC documentation

Tutorial (pdf)

Command Line Options

Maven

Ant Task

Lexer

Regular Expression

Parser

Input

Java

XML

Yacc

Output

Java

Plain Text

XML

Yacc

Miscellaneous

JavaDoc

Troubleshooting

Test cases

Discussion group

LICENSE

Input Encoding Detection

ASCII map

Unicode map

          CookCC

Docs »

Table of Contents

Table of Contents¶

CookCC documentation

Tutorial (pdf)

Command Line Options

Command Line Options

Annotation Processing

Java Compiler

APT

Options

Maven

Basic Usage

<task> Attributes

<option> Attributes

Run Maven

Ant Task

Initiate CookCC Ant Task

Generic CookCC Input

Annotation Processing Tool (APT)

Nested Option Tag

Lexer

Lexer Table Format

Line Mode

Trail Context

CookCC Warnings

Backup

Incomplete States

Some Patterns Can Never Be Matched

Multi-Line Patterns in Line Mode

TODO List

Regular Expression

Escape Characters

POSIX Character Classes

Character Class Manipulations

Tips

Parser

Introduction

Extended Grammar

Optional Operator

List Operator

Optional List Operator

Grouping Operator

Or Operator

cookcc-rt Runtime

Parser Table Format

Default Reduce

Analysis Output

Error Recovery

Error Recovery in Java

Input

Java

Why Java Annotation

Java Annotation vs Lex/Yacc

Java Annotation vs JavaDoc

Annotation Processing API Changes

Overview

Setup

Lexer Section

Parser Section

Examples

Related Work

XML

Overview

XML Tag Explanations

<cookcc>

<code>

<tokens>

<lexer>

<shortcut>

<state>

<rule>

<pattern>

<action>

<parser>

<type>

<grammar>

<rhs>

<action>

Yacc

Deviations

Non-terminal name restrictions

Embedded actions are not supported

Token declaration works somewhat differently

Code Sections

Output

Java

Introduction

Command Line Options

Code Locations

Lexer

Buffer Size

yywrap

Input Stack

Unicode Support

Performance

Plain Text

Command Line Options

XML

Command Line Options

Yacc

Command Line Options

Miscellaneous

JavaDoc

Troubleshooting

Mysterious Crash in APT

Test cases

Discussion group

LICENSE

Input Encoding Detection

Detection Methods

Java Libraries

ASCII map

Unicode map

        Next

        © Copyright 2017-2018, Heng Yuan.

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

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ignite.yardstick.compute.model;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.apache.ignite.lang.IgniteCallable;

/**
 *
 */
public class NoopCallable implements IgniteCallable<Object>, Externalizable {
    /** {@inheritDoc} */
    @Override public Object call() {
        return null;
    }

    /** {@inheritDoc} */
    @Override public void writeExternal(ObjectOutput out) throws IOException {
        //No-op
    }

    /** {@inheritDoc} */
    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        //No-op
    }
}


text:
module ImpactTravel
  class AboutsController < ImpactTravel::ApplicationController
    before_action :require_login
  end
end


text:
require 'spec_helper'

describe VagrantPlugins::VSphere::Action::PowerOff do
  before :each do
    @env[:vSphere_connection] = @vim
  end

  it 'should power off the VM if it is powered on' do
    @machine.stub(:id).and_return(EXISTING_UUID)
    @machine.state.stub(:id).and_return(VagrantPlugins::VSphere::Util::VmState::POWERED_ON)

    call

    expect(@vm).to have_received :PowerOffVM_Task
  end

  it 'should not power off the VM if is powered off' do
    @machine.stub(:id).and_return(EXISTING_UUID)
    @vm.runtime.stub(:powerState).and_return(VagrantPlugins::VSphere::Util::VmState::POWERED_OFF)

    call

    expect(@vm).not_to have_received :PowerOffVM_Task
  end

  it 'should power on and off the VM if is suspended' do
    @machine.stub(:id).and_return(EXISTING_UUID)
    @vm.runtime.stub(:powerState).and_return(VagrantPlugins::VSphere::Util::VmState::SUSPENDED)

    call

    expect(@vm).to have_received :PowerOnVM_Task
    expect(@vm).to have_received :PowerOffVM_Task
  end
end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xinfan.msgbox.service.dao.UserBalanceMapper" >
  <resultMap id="BaseResultMap" type="com.xinfan.msgbox.service.dao.entity.UserBalance" >
    <id column="USER_ID" property="userId" jdbcType="BIGINT" />
    <result column="USER_CREDIT" property="userCredit" jdbcType="INTEGER" />
    <result column="USER_BALANCE" property="userBalance" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    USER_ID, USER_CREDIT, USER_BALANCE
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.xinfan.msgbox.service.dao.entity.UserBalanceExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from t_user_balance
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select
    <include refid="Base_Column_List" />
    from t_user_balance
    where USER_ID = #{userId,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from t_user_balance
    where USER_ID = #{userId,jdbcType=BIGINT}
  </delete>
  <delete id="deleteByExample" parameterType="com.xinfan.msgbox.service.dao.entity.UserBalanceExample" >
    delete from t_user_balance
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.xinfan.msgbox.service.dao.entity.UserBalance" >
    insert into t_user_balance (USER_ID, USER_CREDIT, USER_BALANCE
      )
    values (#{userId,jdbcType=BIGINT}, #{userCredit,jdbcType=INTEGER}, #{userBalance,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.xinfan.msgbox.service.dao.entity.UserBalance" >
    insert into t_user_balance
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        USER_ID,
      </if>
      <if test="userCredit != null" >
        USER_CREDIT,
      </if>
      <if test="userBalance != null" >
        USER_BALANCE,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        #{userId,jdbcType=BIGINT},
      </if>
      <if test="userCredit != null" >
        #{userCredit,jdbcType=INTEGER},
      </if>
      <if test="userBalance != null" >
        #{userBalance,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.xinfan.msgbox.service.dao.entity.UserBalanceExample" resultType="java.lang.Integer" >
    select count(*) from t_user_balance
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update t_user_balance
    <set >
      <if test="record.userId != null" >
        USER_ID = #{record.userId,jdbcType=BIGINT},
      </if>
      <if test="record.userCredit != null" >
        USER_CREDIT = #{record.userCredit,jdbcType=INTEGER},
      </if>
      <if test="record.userBalance != null" >
        USER_BALANCE = #{record.userBalance,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update t_user_balance
    set USER_ID = #{record.userId,jdbcType=BIGINT},
      USER_CREDIT = #{record.userCredit,jdbcType=INTEGER},
      USER_BALANCE = #{record.userBalance,jdbcType=INTEGER}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.xinfan.msgbox.service.dao.entity.UserBalance" >
    update t_user_balance
    <set >
      <if test="userCredit != null" >
        USER_CREDIT = #{userCredit,jdbcType=INTEGER},
      </if>
      <if test="userBalance != null" >
        USER_BALANCE = #{userBalance,jdbcType=INTEGER},
      </if>
    </set>
    where USER_ID = #{userId,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.xinfan.msgbox.service.dao.entity.UserBalance" >
    update t_user_balance
    set USER_CREDIT = #{userCredit,jdbcType=INTEGER},
      USER_BALANCE = #{userBalance,jdbcType=INTEGER}
    where USER_ID = #{userId,jdbcType=BIGINT}
  </update>
</mapper>


text:
package org.kuali.kra.award;

import org.kuali.kra.award.home.Award;
import org.kuali.kra.award.home.AwardAmountInfo;

import java.util.List;

public interface AwardAmountInfoService {

    AwardAmountInfo fetchLastAwardAmountInfoForAwardVersionAndFinalizedTandMDocumentNumber(Award award);
    /**
     *
     * This method should return the awardAmountInfo object having highest transaction id.
     * @param awardAmountInfos
     * @return
     */
    AwardAmountInfo fetchAwardAmountInfoWithHighestTransactionId(List<AwardAmountInfo> awardAmountInfos);

    AwardAmountInfo fetchLastAwardAmountInfoForDocNum(Award award, String docNum);

    int fetchIndexOfAwardAmountInfoWithHighestTransactionId(List<AwardAmountInfo> awardAmountInfos);
}


text:
#region License

#endregion

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace Spring.Util
{
    ///
    /// Represents a URI template. An URI template is a URI-like String that contained variables
    /// marked of in braces {}, which can be expanded to produce a URI.
    ///
    /// <author>Arjen Poutsma</author>
    /// <author>Juergen Hoeller</author>
    /// <author>Bruno Baia (.NET)</author>
    public class UriTemplate
    {
        // Captures URI template variable names.
#if SILVERLIGHT
        private static Regex VARIABLENAMES_REGEX = new Regex(@"\{([^/]+?)\}");
#else
        private static Regex VARIABLENAMES_REGEX = new Regex(@"\{([^/]+?)\}", RegexOptions.Compiled);
#endif

        // Replaces template variables in the URI template.
	    private static string VARIABLEVALUE_PATTERN = "(?<{0}>.*)";

        private const string BRACE_LEFT = "{";
        private const string BRACE_RIGHT = "}";

        private string uriTemplate;
        private string[] variableNames;
        private Regex matchRegex;

        ///
        /// Gets the names of the variables in the template, in order.
        ///
        public string[] VariableNames
        {
            get { return this.variableNames; }
        }

        ///
        /// Creates a new instance of <see cref="UriTemplate"/> with the given URI String.
        ///
        /// <param name="uriTemplate">The URI template string.</param>
        public UriTemplate(string uriTemplate)
        {
            this.uriTemplate = uriTemplate;
            Parser parser = new Parser(uriTemplate);
            this.variableNames = parser.GetVariableNames();
            this.matchRegex = parser.GetMatchRegex();
        }

        ///
        /// Given the dictionary of variables, expands this template into a full URI.
        /// The dictionary keys represent variable names, the dicitonary values variable values.
        /// The order of variables is not significant.
        ///
        /// <example>
        ///
        /// UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
        /// IDictionary<string, object> uriVariables = new Dictionary<string, object>();
        /// uriVariables.Add("booking", "42");
        /// uriVariables.Add("hotel", 1);
        /// Console.Out.WriteLine(template.Expand(uriVariables));
        ///
        /// will print:
http://example.com/hotels/1/bookings/42

        /// </example>
        /// <param name="uriVariables">The dictionary of URI variables.</param>
        /// <returns>The expanded URI</returns>
        public Uri Expand(IDictionary<string, object> uriVariables)
        {
            if (uriVariables.Count != this.variableNames.Length)
            {
                throw new ArgumentException(String.Format(
                        "Invalid amount of variables values in '{0}': expected {1}; got {2}",
                        this.uriTemplate, this.variableNames.Length, uriVariables.Count));
            }

            string uri = this.uriTemplate;
            foreach (string variableName in this.variableNames)
            {
                if (!uriVariables.ContainsKey(variableName))
                {
                    throw new ArgumentException(String.Format(
                        "'uriVariables' dictionary has no value for '{0}'",
                        variableName));
                }
                uri = Replace(uri, variableName, uriVariables[variableName]);
            }

            return new Uri(uri, UriKind.RelativeOrAbsolute);
        }

        ///
        /// Given an array of variables, expands this template into a full URI.
        /// The array represent variable values. The order of variables is significant.
        ///
        /// <example>
        ///
        /// UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
        /// Console.Out.WriteLine(template.Expand(1, "42"));
        ///
        /// will print:
http://example.com/hotels/1/bookings/42

        /// </example>
        /// <param name="uriVariableValues">The array of URI variables.</param>
        /// <returns>The expanded URI</returns>
        public Uri Expand(params object[] uriVariableValues)
        {
            if (uriVariableValues.Length != this.variableNames.Length)
            {
                throw new ArgumentException(String.Format(
                        "Invalid amount of variables values in '{0}': expected {1}; got {2}",
                        this.uriTemplate, this.variableNames.Length, uriVariableValues.Length));
            }

            string uri = this.uriTemplate;
            for (int i = 0; i < this.variableNames.Length; i++)
            {
                uri = Replace(uri, this.variableNames[i], uriVariableValues[i]);
            }

            return new Uri(uri, UriKind.RelativeOrAbsolute);
        }

        ///
        /// Indicates whether the given URI matches this template.
        ///
        /// <param name="uri">The URI to match to.</param>
        /// <returns><see langword="true"/> if it matches; otherwise <see langword="false"/></returns>
        public bool Matches(string uri)
        {
            if (uri == null)
            {
                return false;
            }
            return this.matchRegex.IsMatch(uri);
        }

        ///
        /// Match the given URI to a dictionary of variable values. Keys in the returned map are variable names,
        /// values are variable values, as occurred in the given URI
        ///
        /// <example>
        ///
        /// UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
        /// Console.Out.WriteLine(template.Match("http://example.com/hotels/1/bookings/42"));
        ///
        /// will print:
{hotel=1, booking=42}

        /// </example>
        /// <param name="uri">The URI to match to.</param>
        /// <returns>A dictionary of variable values.</returns>
        public IDictionary<string, string> Match(string uri)
        {
            ArgumentUtils.AssertNotNull(uri, "uri");

            IDictionary<string, string> result = new Dictionary<string, string>();
            Match match = this.matchRegex.Match(uri);
            for (int i = 1; i < match.Groups.Count; i++ )
            {
                result.Add(this.matchRegex.GroupNameFromNumber(i), match.Groups[i].Value);
            }
            return result;
        }

        ///
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object."/>
        ///
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object."/>.
        /// </returns>
        public override string ToString()
        {
            return this.uriTemplate;
        }

        private static string Replace(string uriTemplate, string token, object value)
        {
            string quotedToken = BRACE_LEFT + token + BRACE_RIGHT;
            return uriTemplate.Replace(quotedToken, (value == null) ? String.Empty : value.ToString());
        }

        // Static inner class to parse uri template strings into a matching regular expression.
        private class Parser
        {
		    private List<String> variableNames = new List<String>();
		    private StringBuilder patternBuilder = new StringBuilder();

		    public Parser(string uriTemplate)
            {
			    ArgumentUtils.AssertNotNull(uriTemplate, "uriTemplate");

                int index = 0;
                this.patternBuilder.Append("^");
                foreach (Match match in VARIABLENAMES_REGEX.Matches(uriTemplate))
                {
                    string variableName = match.Groups[1].Value;
                    if (!variableNames.Contains(variableName))
                    {
                        variableNames.Add(variableName);
                    }

                    this.patternBuilder.Append(Escape(uriTemplate, index, match.Index - index));
                    this.patternBuilder.Append(String.Format(VARIABLEVALUE_PATTERN, variableName));
                    index = match.Index + match.Length;
                }
                this.patternBuilder.Append(Escape(uriTemplate, index, uriTemplate.Length - index));
                this.patternBuilder.Append("$");
		    }

            private static string Escape(String fullPath, int start, int end)
            {
                if (start == end)
                {
                    return "";
                }
                return Regex.Escape(fullPath.Substring(start, end));
            }

            public string[] GetVariableNames()
            {
			    return this.variableNames.ToArray();
		    }

            public Regex GetMatchRegex()
            {
                return new Regex(this.patternBuilder.ToString());
		    }
	    }
    }
}


text:
package com.fitpay.android.paymentdevice.utils;

import android.content.Context;

import com.fitpay.android.BaseTestActions;
import com.fitpay.android.paymentdevice.impl.mock.MockPaymentDeviceConnector;
import com.fitpay.android.paymentdevice.interfaces.PaymentDeviceConnectable;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.FieldSetter;

import java.util.HashMap;

public class PaymentDeviceConnectorManagerTest extends BaseTestActions{

    @Test
    public void managerTest() throws NoSuchFieldException {

        PaymentDeviceConnectorManager manager = PaymentDeviceConnectorManager.getInstance();
        Assert.assertNotNull(manager);

        Context context = Mockito.mock(Context.class);
        MockPaymentDeviceConnector connector = new MockPaymentDeviceConnector(context);
        Assert.assertNotNull(connector);

        HashMap<String, PaymentDeviceConnectable> map = new HashMap<>(5);
        FieldSetter.setField(manager, manager.getClass().getDeclaredField("connectors"), map);

        manager.addConnector("1", connector);
        Assert.assertEquals(connector, manager.getConnector("1"));

        manager.removeConnector(connector);
        Assert.assertNull(manager.getConnector("1"));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    <property name="now" value="now()" dbms="mysql,h2"/>
    <property name="now" value="current_timestamp" dbms="postgresql"/>

    <!--
        Added the entity Person.
    -->
    <changeSet id="20150518212914" author="jhipster">
        <createTable tableName="PERSON">
            <column name="id" type="bigint" autoIncrement="true">
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <column name="name" type="varchar(255)">
                <constraints nullable="false" />
            </column>
        </createTable>

    </changeSet>
</databaseChangeLog>


text:
import {NDArrayMathCPU} from '../math/math_cpu';
import {NDArrayMathGPU} from '../math/math_gpu';
import {Array1D, Scalar} from '../math/ndarray';

import {InCPUMemoryShuffledInputProviderBuilder} from './input_provider';

describe('InCPUMemoryShuffledInputProviderBuilder', () => {
  let math: NDArrayMathCPU;

  beforeEach(() => {
    math = new NDArrayMathCPU();
  });

  it('ensure inputs stay in sync', () => {
    const x1s = [Scalar.new(1), Scalar.new(2), Scalar.new(3)];
    const x2s = [Scalar.new(10), Scalar.new(20), Scalar.new(30)];

    const shuffledInputProvider =
        new InCPUMemoryShuffledInputProviderBuilder([x1s, x2s]);

    const [x1provider, x2provider] = shuffledInputProvider.getInputProviders();

    const seenNumbers: {[key: number]: boolean} = {};
    for (let i = 0; i < x1s.length; i++) {
      const x1 = x1provider.getNextCopy(math);
      const x2 = x2provider.getNextCopy(math);

      expect(x1.get() * 10).toEqual(x2.get());

      seenNumbers[x1.get()] = true;
      seenNumbers[x2.get()] = true;
    }

    // Values are shuffled, make sure we've seen everything.
    const expectedSeenNumbers = [1, 2, 3, 10, 20, 30];
    for (let i = 0; i < expectedSeenNumbers.length; i++) {
      expect(seenNumbers[expectedSeenNumbers[i]]).toEqual(true);
    }
  });

  it('different number of examples', () => {
    const x1s = [Scalar.new(1), Scalar.new(2)];
    const x2s = [Scalar.new(10), Scalar.new(20), Scalar.new(30)];

    expect(() => new InCPUMemoryShuffledInputProviderBuilder([x1s, x2s]))
        .toThrowError();
  });

  it('different shapes within input', () => {
    const x1s = [Scalar.new(1), Array1D.new([1, 2])];
    const x2s = [Scalar.new(10), Scalar.new(20), Scalar.new(30)];

    expect(() => new InCPUMemoryShuffledInputProviderBuilder([x1s, x2s]))
        .toThrowError();
  });
});

describe('InGPUMemoryShuffledInputProviderBuilder', () => {
  let math: NDArrayMathGPU;

  beforeEach(() => {
    math = new NDArrayMathGPU();
  });

  it('ensure inputs stay in sync', () => {
    const x1s = [Scalar.new(1), Scalar.new(2), Scalar.new(3)];
    const x2s = [Scalar.new(10), Scalar.new(20), Scalar.new(30)];

    const shuffledInputProvider =
        new InCPUMemoryShuffledInputProviderBuilder([x1s, x2s]);

    const [x1provider, x2provider] = shuffledInputProvider.getInputProviders();

    const seenNumbers: {[key: number]: boolean} = {};
    for (let i = 0; i < x1s.length; i++) {
      const x1 = x1provider.getNextCopy(math);
      const x2 = x2provider.getNextCopy(math);

      expect(x1.get() * 10).toEqual(x2.get());

      seenNumbers[x1.get()] = true;
      seenNumbers[x2.get()] = true;

      x1provider.disposeCopy(math, x1);
      x2provider.disposeCopy(math, x1);
    }

    // Values are shuffled, make sure we've seen everything.
    const expectedSeenNumbers = [1, 2, 3, 10, 20, 30];
    for (let i = 0; i < expectedSeenNumbers.length; i++) {
      expect(seenNumbers[expectedSeenNumbers[i]]).toEqual(true);
    }
  });

  it('different number of examples', () => {
    const x1s = [Scalar.new(1), Scalar.new(2)];
    const x2s = [Scalar.new(10), Scalar.new(20), Scalar.new(30)];

    expect(() => new InCPUMemoryShuffledInputProviderBuilder([x1s, x2s]))
        .toThrowError();

    x1s.forEach(x1 => {
      x1.dispose();
    });
    x2s.forEach(x2 => {
      x2.dispose();
    });
  });

  it('different shapes within input', () => {
    const x1s = [Scalar.new(1), Array1D.new([1, 2])];
    const x2s = [Scalar.new(10), Scalar.new(20), Scalar.new(30)];

    expect(() => new InCPUMemoryShuffledInputProviderBuilder([x1s, x2s]))
        .toThrowError();

    x1s.forEach(x1 => {
      x1.dispose();
    });
    x2s.forEach(x2 => {
      x2.dispose();
    });
  });
});


text:
package looli

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestSetContentType(t *testing.T) {
	router := New()
	router.Get("/", func(c *Context) {
		setContentType(c.ResponseWriter, plainContentType)
	})

	server := httptest.NewServer(router)
	defer server.Close()

	serverURL := server.URL
	resp, err := http.Get(serverURL)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()

	assert.Equal(t, plainContentType[0], resp.Header.Get("Content-Type"))
}

func TestRenderString(t *testing.T) {
	router := New()
	router.Get("/", func(c *Context) {
		renderString(c.ResponseWriter, "hello ")
		renderString(c.ResponseWriter, "world %v!", "cssivision")
	})

	server := httptest.NewServer(router)
	defer server.Close()

	serverURL := server.URL
	resp, err := http.Get(serverURL)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()

	assert.Equal(t, plainContentType[0], resp.Header.Get("Content-Type"))
	bodyBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatal(err)
	}

	assert.Equal(t, "hello world cssivision!", string(bodyBytes))
}

func TestRenderJSON(t *testing.T) {
	type Info struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}
	router := New()
	router.Get("/", func(c *Context) {
		renderJSON(c.ResponseWriter, JSON{
			"name": "cssivision",
			"age":  21,
		})
	})

	server := httptest.NewServer(router)
	defer server.Close()

	serverURL := server.URL
	resp, err := http.Get(serverURL)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()

	assert.Equal(t, jsonContentType[0], resp.Header.Get("Content-Type"))
	info := new(Info)
	json.NewDecoder(resp.Body).Decode(info)
	assert.Equal(t, "cssivision", info.Name)
	assert.Equal(t, 21, info.Age)
}

func TestRenderHTML(t *testing.T) {
	t.Run("render with name", func(t *testing.T) {
		router := New()
		router.LoadHTMLGlob("test/templates/*")
		router.Get("/", func(c *Context) {
			err := renderHTML(c.ResponseWriter, c.template, "index.tmpl", JSON{
				"title": "Posts",
			})
			assert.Nil(t, err)
		})

		server := httptest.NewServer(router)
		defer server.Close()

		serverURL := server.URL
		resp, err := http.Get(serverURL)
		assert.Nil(t, err)
		defer resp.Body.Close()

		assert.Equal(t, htmlContentType[0], resp.Header.Get("Content-Type"))
		bodyBytes, err := ioutil.ReadAll(resp.Body)
		assert.Nil(t, err)
		assert.True(t, strings.Contains(string(bodyBytes), "Posts"))
	})

	t.Run("render without name", func(t *testing.T) {
		router := New()
		router.LoadHTMLGlob("test/templates/*")
		router.Get("/", func(c *Context) {
			err := renderHTML(c.ResponseWriter, c.template, "", JSON{
				"title": "Posts",
			})
			assert.Nil(t, err)
		})

		server := httptest.NewServer(router)
		defer server.Close()

		serverURL := server.URL
		resp, err := http.Get(serverURL)
		assert.Nil(t, err)
		defer resp.Body.Close()

		assert.Equal(t, htmlContentType[0], resp.Header.Get("Content-Type"))
		bodyBytes, err := ioutil.ReadAll(resp.Body)
		assert.Nil(t, err)

		assert.True(t, strings.Contains(string(bodyBytes), "Posts"))
	})
}


text:
class Qt4 < Formula
  desc "Cross-platform application and UI framework"
  homepage "https://www.qt.io/"
  url "https://download.qt.io/archive/qt/4.8/4.8.7/qt-everywhere-opensource-src-4.8.7.tar.gz"
  mirror "http://qt.mirror.constant.com/archive/qt/4.8/4.8.7/qt-everywhere-opensource-src-4.8.7.tar.gz"
  sha256 "e2882295097e47fe089f8ac741a95fef47e0a73a3f3cdf21b56990638f626ea0"

  bottle do
    root_url "https://dl.bintray.com/homebrew-osgeo/osgeo-bottles"
    rebuild 1
    sha256 "b144bc04f10d95c1855ab79d69e0a2905694eb0165907846c8b153fa64ff1f67" => :high_sierra
    sha256 "b144bc04f10d95c1855ab79d69e0a2905694eb0165907846c8b153fa64ff1f67" => :sierra
  end

  # Backport of Qt5 commit to fix the fatal build error with Xcode 7, SDK 10.11.
  # https://code.qt.io/cgit/qt/qtbase.git/commit/?id=b06304e164ba47351fa292662c1e6383c081b5ca
  if MacOS.version >= :el_capitan
    patch do
      url "https://raw.githubusercontent.com/Homebrew/formula-patches/480b7142c4e2ae07de6028f672695eb927a34875/qt/el-capitan.patch"
      sha256 "c8a0fa819c8012a7cb70e902abb7133fc05235881ce230235d93719c47650c4e"
    end
  end

  keg_only "deprecated in homebrew-core for macOS >= Sierra (10.12)"

  option "with-qt3support", "Build with deprecated Qt3Support module support"
  option "with-docs", "Build documentation"
  option "without-webkit", "Build without QtWebKit module"

  depends_on "openssl"
  depends_on "dbus" => :optional
  depends_on "mysql" => :optional
  depends_on "osgeo-postgresql" => :optional

  # Qt4 is dead upstream. We backported a build fix for 10.11 but do not
  # intend to keep rescuing it forever, including for macOS 10.12. Homebrew will
  # be migrating to Qt5 as widely as possible, which remains supported upstream.
  # depends on MaximumMacOSRequirement => :el_capitan

  deprecated_option "qtdbus" => "with-dbus"
  deprecated_option "with-d-bus" => "with-dbus"

  resource "test-project" do
    url "https://gist.github.com/tdsmith/f55e7e69ae174b5b5a03.git",
        :revision => "6f565390395a0259fa85fdd3a4f1968ebcd1cc7d"
  end

  def install
    if ENV.compiler == :clang && (MacOS::Xcode.version >= "9.0" || MacOS::CLT.version >= "9.0")
      odie <<~EOS
        Compilation not supported with Xcode/CLT 9.0 or higher.
        Use no formula or source-build options and install available bottle.
      EOS
    end

    args = %W[
      -prefix #{prefix}
      -release
      -opensource
      -confirm-license
      -fast
      -system-zlib
      -qt-libtiff
      -qt-libpng
      -qt-libjpeg
      -nomake demos
      -nomake examples
      -cocoa
    ]

    if ENV.compiler == :clang
      args << "-platform"

      if MacOS.version >= :mavericks
        args << "unsupported/macx-clang-libc++"
      else
        args << "unsupported/macx-clang"
      end
    end

    # Phonon is broken on macOS 10.12+ and Xcode 8+ due to QTKit.framework
    # being removed.
    args << "-no-phonon" if MacOS.version >= :sierra || MacOS::Xcode.version >= "8.0"

    args << "-openssl-linked"
    args << "-I" << Formula["openssl"].opt_include
    args << "-L" << Formula["openssl"].opt_lib

    args << "-plugin-sql-mysql" if build.with? "mysql"
    args << "-plugin-sql-psql" if build.with? "postgresql"

    if build.with? "dbus"
      dbus_opt = Formula["dbus"].opt_prefix
      args << "-I#{dbus_opt}/lib/dbus-1.0/include"
      args << "-I#{dbus_opt}/include/dbus-1.0"
      args << "-L#{dbus_opt}/lib"
      args << "-ldbus-1"
      args << "-dbus-linked"
    end

    if build.with? "qt3support"
      args << "-qt3support"
    else
      args << "-no-qt3support"
    end

    args << "-nomake" << "docs" if build.without? "docs"

    if MacOS.prefer_64_bit?
      args << "-arch" << "x86_64"
    else
      args << "-arch" << "x86"
    end

    args << "-no-webkit" if build.without? "webkit"

    system "./configure", *args
    system "make"
    ENV.deparallelize
    system "make", "install"

    # what are these anyway?
    (bin+"pixeltool.app").rmtree
    (bin+"qhelpconverter.app").rmtree
    # remove porting file for non-humans
    (prefix+"q3porting.xml").unlink if build.without? "qt3support"

    # Some config scripts will only find Qt in a "Frameworks" folder
    frameworks.install_symlink Dir["#{lib}/*.framework"]

    # The pkg-config files installed suggest that headers can be found in the
    # `include` directory. Make this so by creating symlinks from `include` to
    # the Frameworks' Headers folders.
    Pathname.glob("#{lib}/*.framework/Headers") do |path|
      include.install_symlink path => path.parent.basename(".framework")
    end

    # Make `HOMEBREW_PREFIX/lib/qt-4/plugins` an additional plug-in search path
    # for Qt Designer to support formulae that provide Qt Designer plug-ins.
    system "/usr/libexec/PlistBuddy",
            "-c", "Add :LSEnvironment:QT_PLUGIN_PATH string \"#{HOMEBREW_PREFIX}/lib/qt-4/plugins\"",
           "#{bin}/Designer.app/Contents/Info.plist"

    Pathname.glob("#{bin}/*.app") { |app| mv app, prefix }
  end

  def post_install
    (HOMEBREW_PREFIX/"lib/qt-4/plugins/designer").mkpath
  end

  def caveats; <<~EOS
    We agreed to the Qt opensource license for you.
    If this is unacceptable you should uninstall.

    Qt Designer no longer picks up changes to the QT_PLUGIN_PATH environment
    variable as it was tweaked to search for plug-ins provided by formulae in
      #{HOMEBREW_PREFIX}/lib/qt-4/plugins

    Phonon is not supported on macOS Sierra or with Xcode 8.
    EOS
  end

  test do
    Encoding.default_external = "UTF-8" unless RUBY_VERSION.start_with? "1."
    resource("test-project").stage testpath
    system bin/"qmake"
    system "make"
    assert_match(/GitHub/, pipe_output(testpath/"qtnetwork-test 2>&1", nil, 0))
  end
end


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Luval.Tests.Stubs
{
    class DbConnection : IDbConnection
    {
        public DbConnection()
        {
            State = ConnectionState.Closed;
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public IDbTransaction BeginTransaction()
        {
            return new DbTransactionStub(this);
        }

        public IDbTransaction BeginTransaction(IsolationLevel il)
        {
            return new DbTransactionStub(this, il);
        }

        public void Close()
        {
            State = ConnectionState.Closed;
        }

        public void ChangeDatabase(string databaseName)
        {
            Database = databaseName;
        }

        public IDbCommand CreateCommand()
        {
            throw new NotImplementedException();
        }

        public void Open()
        {
            State = ConnectionState.Open;
        }

        public string ConnectionString { get; set; }
        public int ConnectionTimeout { get; private set; }
        public string Database { get; private set; }
        public ConnectionState State { get; private set; }
    }
}


text:
var version = process.versions.node.split('.').map(Number);
if (version[0] > 0 || version[0] === 0 && version[1] >= 12) {
    process.exit(0);
}

console.log('incompatible version, HPC-Cloud requires >=0.12.0 ');
process.exit(1);


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "info.h"
#include "input.h"

#include "connection.h"
#include "transport.h"

#include <winpr/crt.h>

#include <freerdp/error.h>

/**
 *                                      Connection Sequence\n
 *     client                                                                    server\n
 *        |                                                                         |\n
 *        |-----------------------X.224 Connection Request PDU--------------------->|\n
 *        |<----------------------X.224 Connection Confirm PDU----------------------|\n
 *        |-------MCS Connect-Initial PDU with GCC Conference Create Request------->|\n
 *        |<-----MCS Connect-Response PDU with GCC Conference Create Response-------|\n
 *        |------------------------MCS Erect Domain Request PDU-------------------->|\n
 *        |------------------------MCS Attach User Request PDU--------------------->|\n
 *        |<-----------------------MCS Attach User Confirm PDU----------------------|\n
 *        |------------------------MCS Channel Join Request PDU-------------------->|\n
 *        |<-----------------------MCS Channel Join Confirm PDU---------------------|\n
 *        |----------------------------Security Exchange PDU----------------------->|\n
 *        |-------------------------------Client Info PDU-------------------------->|\n
 *        |<---------------------License Error PDU - Valid Client-------------------|\n
 *        |<-----------------------------Demand Active PDU--------------------------|\n
 *        |------------------------------Confirm Active PDU------------------------>|\n
 *        |-------------------------------Synchronize PDU-------------------------->|\n
 *        |---------------------------Control PDU - Cooperate---------------------->|\n
 *        |------------------------Control PDU - Request Control------------------->|\n
 *        |--------------------------Persistent Key List PDU(s)-------------------->|\n
 *        |--------------------------------Font List PDU--------------------------->|\n
 *        |<------------------------------Synchronize PDU---------------------------|\n
 *        |<--------------------------Control PDU - Cooperate-----------------------|\n
 *        |<-----------------------Control PDU - Granted Control--------------------|\n
 *        |<-------------------------------Font Map PDU-----------------------------|\n
 *
 */

/**
 * Establish RDP Connection based on the settings given in the 'rdp' parameter.
 * @msdn{cc240452}
 * @param rdp RDP module
 * @return true if the connection succeeded. FALSE otherwise.
 */

BOOL rdp_client_connect(rdpRdp* rdp)
{
	rdpSettings* settings = rdp->settings;

	nego_init(rdp->nego);
	nego_set_target(rdp->nego, settings->ServerHostname, settings->ServerPort);

	if (settings->GatewayUsageMethod)
	{
		char* user;
		char* domain;
		char* cookie;
		int user_length;
		int domain_length;
		int cookie_length;

		user = settings->Username;
		user_length = strlen(settings->Username);

		if (settings->Domain)
			domain = settings->Domain;
		else
			domain = settings->ComputerName;

		domain_length = strlen(domain);

		cookie_length = domain_length + 1 + user_length;
		cookie = (char*) malloc(cookie_length + 1);

		CopyMemory(cookie, domain, domain_length);
		CharUpperBuffA(cookie, domain_length);
		cookie[domain_length] = '\\';
		CopyMemory(&cookie[domain_length + 1], user, user_length);
		cookie[cookie_length] = '\0';

		nego_set_cookie(rdp->nego, cookie);
		free(cookie);

		settings->RdpSecurity = TRUE;
		settings->TlsSecurity = FALSE;
		settings->NlaSecurity = FALSE;
		settings->ExtSecurity = FALSE;

		//settings->TlsSecurity = TRUE;
		//settings->NlaSecurity = TRUE;
	}
	else
	{
		nego_set_cookie(rdp->nego, settings->Username);
	}

	nego_set_send_preconnection_pdu(rdp->nego, settings->SendPreconnectionPdu);
	nego_set_preconnection_id(rdp->nego, settings->PreconnectionId);
	nego_set_preconnection_blob(rdp->nego, settings->PreconnectionBlob);

	nego_set_negotiation_enabled(rdp->nego, settings->NegotiateSecurityLayer);

	nego_enable_rdp(rdp->nego, settings->RdpSecurity);
	nego_enable_tls(rdp->nego, settings->TlsSecurity);
	nego_enable_nla(rdp->nego, settings->NlaSecurity);
	nego_enable_ext(rdp->nego, settings->ExtSecurity);

	if (settings->MstscCookieMode)
		settings->CookieMaxLength = MSTSC_COOKIE_MAX_LENGTH;

	nego_set_cookie_max_length(rdp->nego, settings->CookieMaxLength);

	if (!nego_connect(rdp->nego))
	{
		printf("Error: protocol security negotiation or connection failure\n");
		return FALSE;
	}

	if ((rdp->nego->selected_protocol & PROTOCOL_TLS) || (rdp->nego->selected_protocol == PROTOCOL_RDP))
	{
		if ((settings->Username != NULL) && ((settings->Password != NULL) ||
				(settings->RedirectionPassword != NULL && settings->RedirectionPasswordLength > 0)))
			settings->AutoLogonEnabled = TRUE;
	}

	rdp_set_blocking_mode(rdp, FALSE);
	rdp->state = CONNECTION_STATE_NEGO;
	rdp->finalize_sc_pdus = 0;

	if (!mcs_send_connect_initial(rdp->mcs))
	{
		if (!connectErrorCode)
		{
			connectErrorCode = MCSCONNECTINITIALERROR;
		}
		printf("Error: unable to send MCS Connect Initial\n");
		return FALSE;
	}

	while (rdp->state != CONNECTION_STATE_ACTIVE)
	{
		if (rdp_check_fds(rdp) < 0)
			return FALSE;
	}

	return TRUE;
}

BOOL rdp_client_disconnect(rdpRdp* rdp)
{
	return transport_disconnect(rdp->transport);
}

BOOL rdp_client_redirect(rdpRdp* rdp)
{
	rdpSettings* settings = rdp->settings;
	rdpRedirection* redirection = rdp->redirection;

	rdp_client_disconnect(rdp);

	/* FIXME: this is a subset of rdp_free */
	crypto_rc4_free(rdp->rc4_decrypt_key);
	crypto_rc4_free(rdp->rc4_encrypt_key);
	crypto_des3_free(rdp->fips_encrypt);
	crypto_des3_free(rdp->fips_decrypt);
	crypto_hmac_free(rdp->fips_hmac);
	mcs_free(rdp->mcs);
	nego_free(rdp->nego);
	license_free(rdp->license);
	transport_free(rdp->transport);

	free(settings->ServerRandom);
	free(settings->ServerCertificate);
	free(settings->ClientAddress);

	rdp->transport = transport_new(settings);
	rdp->license = license_new(rdp);
	rdp->nego = nego_new(rdp->transport);
	rdp->mcs = mcs_new(rdp->transport);

	rdp->transport->layer = TRANSPORT_LAYER_TCP;
	settings->RedirectedSessionId = redirection->sessionID;

	if (redirection->flags & LB_LOAD_BALANCE_INFO)
	{
		nego_set_routing_token(rdp->nego, redirection->LoadBalanceInfo, redirection->LoadBalanceInfoLength);
	}
	else
	{
		if (redirection->flags & LB_TARGET_NET_ADDRESS)
		{
			free(settings->ServerHostname);
			settings->ServerHostname = _strdup(redirection->targetNetAddress.ascii);
		}
		else if (redirection->flags & LB_TARGET_FQDN)
		{
			free(settings->ServerHostname);
			settings->ServerHostname = _strdup(redirection->targetFQDN.ascii);
		}
		else if (redirection->flags & LB_TARGET_NETBIOS_NAME)
		{
			free(settings->ServerHostname);
			settings->ServerHostname = _strdup(redirection->targetNetBiosName.ascii);
		}
	}

	if (redirection->flags & LB_USERNAME)
	{
		free(settings->Username);
		settings->Username = _strdup(redirection->username.ascii);
	}

	if (redirection->flags & LB_DOMAIN)
	{
		free(settings->Domain);
		settings->Domain = _strdup(redirection->domain.ascii);
	}

	if (redirection->flags & LB_PASSWORD)
	{
		settings->RedirectionPassword = redirection->PasswordCookie;
		settings->RedirectionPasswordLength = redirection->PasswordCookieLength;
	}

	return rdp_client_connect(rdp);
}

static BOOL rdp_client_establish_keys(rdpRdp* rdp)
{
	BYTE* mod;
	BYTE* exp;
	STREAM* s;
	UINT32 length;
	UINT32 key_len;
	BYTE crypt_client_random[256 + 8];
	BYTE client_random[CLIENT_RANDOM_LENGTH];

	if (rdp->settings->DisableEncryption == FALSE)
	{
		/* no RDP encryption */
		return TRUE;
	}

	/* encrypt client random */
	memset(crypt_client_random, 0, sizeof(crypt_client_random));
	crypto_nonce(client_random, sizeof(client_random));
	key_len = rdp->settings->RdpServerCertificate->cert_info.ModulusLength;
	mod = rdp->settings->RdpServerCertificate->cert_info.Modulus;
	exp = rdp->settings->RdpServerCertificate->cert_info.exponent;
	crypto_rsa_public_encrypt(client_random, sizeof(client_random), key_len, mod, exp, crypt_client_random);

	/* send crypt client random to server */
	length = RDP_PACKET_HEADER_MAX_LENGTH + RDP_SECURITY_HEADER_LENGTH + 4 + key_len + 8;
	s = transport_send_stream_init(rdp->mcs->transport, length);

	rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID);
	rdp_write_security_header(s, SEC_EXCHANGE_PKT);
	length = key_len + 8;

	stream_write_UINT32(s, length);
	stream_write(s, crypt_client_random, length);

	if (transport_write(rdp->mcs->transport, s) < 0)
	{
		return FALSE;
	}

	/* now calculate encrypt / decrypt and update keys */
	if (!security_establish_keys(client_random, rdp))
	{
		return FALSE;
	}

	rdp->do_crypt = TRUE;
	if (rdp->settings->SaltedChecksum)
		rdp->do_secure_checksum = TRUE;

	if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
	{
		BYTE fips_ivec[8] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
		rdp->fips_encrypt = crypto_des3_encrypt_init(rdp->fips_encrypt_key, fips_ivec);
		rdp->fips_decrypt = crypto_des3_decrypt_init(rdp->fips_decrypt_key, fips_ivec);

		rdp->fips_hmac = crypto_hmac_new();
		return TRUE;
	}

	rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len);
	rdp->rc4_encrypt_key = crypto_rc4_init(rdp->encrypt_key, rdp->rc4_key_len);

	return TRUE;
}

static BOOL rdp_server_establish_keys(rdpRdp* rdp, STREAM* s)
{
	BYTE client_random[64]; /* Should be only 32 after successful decryption, but on failure might take up to 64 bytes. */
	BYTE crypt_client_random[256 + 8];
	UINT32 rand_len, key_len;
	UINT16 channel_id, length, sec_flags;
	BYTE* mod;
	BYTE* priv_exp;

	if (rdp->settings->DisableEncryption == FALSE)
	{
		/* No RDP Security. */
		return TRUE;
	}

	if (!rdp_read_header(rdp, s, &length, &channel_id))
	{
		printf("rdp_server_establish_keys: invalid RDP header\n");
		return FALSE;
	}

	if (!rdp_read_security_header(s, &sec_flags))
		return FALSE;

	if ((sec_flags & SEC_EXCHANGE_PKT) == 0)
	{
		printf("rdp_server_establish_keys: missing SEC_EXCHANGE_PKT in security header\n");
		return FALSE;
	}

	if(stream_get_left(s) < 4)
		return FALSE;
	stream_read_UINT32(s, rand_len);
	if(stream_get_left(s) < rand_len + 8)  /* include 8 bytes of padding */
		return FALSE;

	key_len = rdp->settings->RdpServerRsaKey->ModulusLength;

	if (rand_len != key_len + 8)
	{
		printf("rdp_server_establish_keys: invalid encrypted client random length\n");
		return FALSE;
	}

	memset(crypt_client_random, 0, sizeof(crypt_client_random));
	stream_read(s, crypt_client_random, rand_len);
	/* 8 zero bytes of padding */
	stream_seek(s, 8);
	mod = rdp->settings->RdpServerRsaKey->Modulus;
	priv_exp = rdp->settings->RdpServerRsaKey->PrivateExponent;
	crypto_rsa_private_decrypt(crypt_client_random, rand_len - 8, key_len, mod, priv_exp, client_random);

	/* now calculate encrypt / decrypt and update keys */
	if (!security_establish_keys(client_random, rdp))
	{
		return FALSE;
	}

	rdp->do_crypt = TRUE;
	if (rdp->settings->SaltedChecksum)
		rdp->do_secure_checksum = TRUE;

	if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
	{
		BYTE fips_ivec[8] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
		rdp->fips_encrypt = crypto_des3_encrypt_init(rdp->fips_encrypt_key, fips_ivec);
		rdp->fips_decrypt = crypto_des3_decrypt_init(rdp->fips_decrypt_key, fips_ivec);

		rdp->fips_hmac = crypto_hmac_new();
		return TRUE;
	}

	rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len);
	rdp->rc4_encrypt_key = crypto_rc4_init(rdp->encrypt_key, rdp->rc4_key_len);

	return TRUE;
}

BOOL rdp_client_connect_mcs_connect_response(rdpRdp* rdp, STREAM* s)
{
	if (!mcs_recv_connect_response(rdp->mcs, s))
	{
		printf("rdp_client_connect_mcs_connect_response: mcs_recv_connect_response failed\n");
		return FALSE;
	}

	if (!mcs_send_erect_domain_request(rdp->mcs))
		return FALSE;

	if (!mcs_send_attach_user_request(rdp->mcs))
		return FALSE;

	rdp->state = CONNECTION_STATE_MCS_ATTACH_USER;

	return TRUE;
}

BOOL rdp_client_connect_mcs_attach_user_confirm(rdpRdp* rdp, STREAM* s)
{
	if (!mcs_recv_attach_user_confirm(rdp->mcs, s))
		return FALSE;

	if (!mcs_send_channel_join_request(rdp->mcs, rdp->mcs->user_id))
		return FALSE;

	rdp->state = CONNECTION_STATE_MCS_CHANNEL_JOIN;

	return TRUE;
}

BOOL rdp_client_connect_mcs_channel_join_confirm(rdpRdp* rdp, STREAM* s)
{
	int i;
	UINT16 channel_id;
	BOOL all_joined = TRUE;

	if (!mcs_recv_channel_join_confirm(rdp->mcs, s, &channel_id))
		return FALSE;

	if (!rdp->mcs->user_channel_joined)
	{
		if (channel_id != rdp->mcs->user_id)
			return FALSE;
		rdp->mcs->user_channel_joined = TRUE;

		if (!mcs_send_channel_join_request(rdp->mcs, MCS_GLOBAL_CHANNEL_ID))
			return FALSE;
	}
	else if (!rdp->mcs->global_channel_joined)
	{
		if (channel_id != MCS_GLOBAL_CHANNEL_ID)
			return FALSE;
		rdp->mcs->global_channel_joined = TRUE;

		if (rdp->settings->ChannelCount > 0)
		{
			if (!mcs_send_channel_join_request(rdp->mcs, rdp->settings->ChannelDefArray[0].ChannelId))
				return FALSE;

			all_joined = FALSE;
		}
	}
	else
	{
		for (i = 0; i < rdp->settings->ChannelCount; i++)
		{
			if (rdp->settings->ChannelDefArray[i].joined)
				continue;

			if (rdp->settings->ChannelDefArray[i].ChannelId != channel_id)
				return FALSE;

			rdp->settings->ChannelDefArray[i].joined = TRUE;
			break;
		}
		if (i + 1 < rdp->settings->ChannelCount)
		{
			if (!mcs_send_channel_join_request(rdp->mcs, rdp->settings->ChannelDefArray[i + 1].ChannelId))
				return FALSE;

			all_joined = FALSE;
		}
	}

	if (rdp->mcs->user_channel_joined && rdp->mcs->global_channel_joined && all_joined)
	{
		if (!rdp_client_establish_keys(rdp))
			return FALSE;
		if (!rdp_send_client_info(rdp))
			return FALSE;
		rdp->state = CONNECTION_STATE_LICENSE;
	}

	return TRUE;
}

BOOL rdp_client_connect_license(rdpRdp* rdp, STREAM* s)
{
	if (!license_recv(rdp->license, s))
		return FALSE;

	if (rdp->license->state == LICENSE_STATE_ABORTED)
	{
		printf("license connection sequence aborted.\n");
		return FALSE;
	}

	if (rdp->license->state == LICENSE_STATE_COMPLETED)
	{
		rdp->state = CONNECTION_STATE_CAPABILITY;
	}

	return TRUE;
}

BOOL rdp_client_connect_demand_active(rdpRdp* rdp, STREAM* s)
{
	BYTE* mark;
	UINT16 width;
	UINT16 height;

	width = rdp->settings->DesktopWidth;
	height = rdp->settings->DesktopHeight;

	stream_get_mark(s, mark);

	if (!rdp_recv_demand_active(rdp, s))
	{
		stream_set_mark(s, mark);
		stream_seek(s, RDP_PACKET_HEADER_MAX_LENGTH);

		if (rdp_recv_out_of_sequence_pdu(rdp, s) != TRUE)
			return FALSE;

		return TRUE;
	}

	if (rdp->disconnect)
		return TRUE;

	if (!rdp_send_confirm_active(rdp))
		return FALSE;

	input_register_client_callbacks(rdp->input);

	/**
	 * The server may request a different desktop size during Deactivation-Reactivation sequence.
	 * In this case, the UI should be informed and do actual window resizing at this point.
	 */
	if (width != rdp->settings->DesktopWidth || height != rdp->settings->DesktopHeight)
	{
		IFCALL(rdp->update->DesktopResize, rdp->update->context);
	}

	rdp->state = CONNECTION_STATE_FINALIZATION;
	update_reset_state(rdp->update);

	return rdp_client_connect_finalize(rdp);
}

BOOL rdp_client_connect_finalize(rdpRdp* rdp)
{
	/**
	 * [MS-RDPBCGR] 1.3.1.1 - 8.
	 * The client-to-server PDUs sent during this phase have no dependencies on any of the server-to-
	 * client PDUs; they may be sent as a single batch, provided that sequencing is maintained.
	 */

	if (!rdp_send_client_synchronize_pdu(rdp))
		return FALSE;
	if (!rdp_send_client_control_pdu(rdp, CTRLACTION_COOPERATE))
		return FALSE;
	if (!rdp_send_client_control_pdu(rdp, CTRLACTION_REQUEST_CONTROL))
		return FALSE;
	if (!rdp_send_client_persistent_key_list_pdu(rdp))
		return FALSE;
	if (!rdp_send_client_font_list_pdu(rdp, FONTLIST_FIRST | FONTLIST_LAST))
		return FALSE;

	return TRUE;
}

BOOL rdp_server_accept_nego(rdpRdp* rdp, STREAM* s)
{
	BOOL status;
	rdpSettings* settings = rdp->settings;

	transport_set_blocking_mode(rdp->transport, TRUE);

	if (!nego_read_request(rdp->nego, s))
		return FALSE;

	rdp->nego->selected_protocol = 0;

	printf("Client Security: NLA:%d TLS:%d RDP:%d\n",
			(rdp->nego->requested_protocols & PROTOCOL_NLA) ? 1 : 0,
			(rdp->nego->requested_protocols & PROTOCOL_TLS)	? 1 : 0,
			(rdp->nego->requested_protocols == PROTOCOL_RDP) ? 1: 0);

	printf("Server Security: NLA:%d TLS:%d RDP:%d\n",
			settings->NlaSecurity, settings->TlsSecurity, settings->RdpSecurity);

	if ((settings->NlaSecurity) && (rdp->nego->requested_protocols & PROTOCOL_NLA))
	{
		rdp->nego->selected_protocol = PROTOCOL_NLA;
	}
	else if ((settings->TlsSecurity) && (rdp->nego->requested_protocols & PROTOCOL_TLS))
	{
		rdp->nego->selected_protocol = PROTOCOL_TLS;
	}
	else if ((settings->RdpSecurity) && (rdp->nego->selected_protocol == PROTOCOL_RDP))
	{
		rdp->nego->selected_protocol = PROTOCOL_RDP;
	}
	else
	{
		printf("Protocol security negotiation failure\n");
	}

	printf("Negotiated Security: NLA:%d TLS:%d RDP:%d\n",
			(rdp->nego->selected_protocol & PROTOCOL_NLA) ? 1 : 0,
			(rdp->nego->selected_protocol & PROTOCOL_TLS)	? 1 : 0,
			(rdp->nego->selected_protocol == PROTOCOL_RDP) ? 1: 0);

	if (!nego_send_negotiation_response(rdp->nego))
		return FALSE;

	status = FALSE;
	if (rdp->nego->selected_protocol & PROTOCOL_NLA)
		status = transport_accept_nla(rdp->transport);
	else if (rdp->nego->selected_protocol & PROTOCOL_TLS)
		status = transport_accept_tls(rdp->transport);
	else if (rdp->nego->selected_protocol == PROTOCOL_RDP) /* 0 */
		status = transport_accept_rdp(rdp->transport);

	if (!status)
		return FALSE;

	transport_set_blocking_mode(rdp->transport, FALSE);

	rdp->state = CONNECTION_STATE_NEGO;

	return TRUE;
}

BOOL rdp_server_accept_mcs_connect_initial(rdpRdp* rdp, STREAM* s)
{
	int i;

	if (!mcs_recv_connect_initial(rdp->mcs, s))
		return FALSE;

	printf("Accepted client: %s\n", rdp->settings->ClientHostname);
	printf("Accepted channels:");

	for (i = 0; i < rdp->settings->ChannelCount; i++)
	{
		printf(" %s", rdp->settings->ChannelDefArray[i].Name);
	}
	printf("\n");

	if (!mcs_send_connect_response(rdp->mcs))
		return FALSE;

	rdp->state = CONNECTION_STATE_MCS_CONNECT;

	return TRUE;
}

BOOL rdp_server_accept_mcs_erect_domain_request(rdpRdp* rdp, STREAM* s)
{
	if (!mcs_recv_erect_domain_request(rdp->mcs, s))
		return FALSE;

	rdp->state = CONNECTION_STATE_MCS_ERECT_DOMAIN;

	return TRUE;
}

BOOL rdp_server_accept_mcs_attach_user_request(rdpRdp* rdp, STREAM* s)
{
	if (!mcs_recv_attach_user_request(rdp->mcs, s))
		return FALSE;

	if (!mcs_send_attach_user_confirm(rdp->mcs))
		return FALSE;

	rdp->state = CONNECTION_STATE_MCS_ATTACH_USER;

	return TRUE;
}

BOOL rdp_server_accept_mcs_channel_join_request(rdpRdp* rdp, STREAM* s)
{
	int i;
	UINT16 channel_id;
	BOOL all_joined = TRUE;

	if (!mcs_recv_channel_join_request(rdp->mcs, s, &channel_id))
		return FALSE;

	if (!mcs_send_channel_join_confirm(rdp->mcs, channel_id))
		return FALSE;

	if (channel_id == rdp->mcs->user_id)
		rdp->mcs->user_channel_joined = TRUE;
	else if (channel_id == MCS_GLOBAL_CHANNEL_ID)
		rdp->mcs->global_channel_joined = TRUE;

	for (i = 0; i < rdp->settings->ChannelCount; i++)
	{
		if (rdp->settings->ChannelDefArray[i].ChannelId == channel_id)
			rdp->settings->ChannelDefArray[i].joined = TRUE;

		if (!rdp->settings->ChannelDefArray[i].joined)
			all_joined = FALSE;
	}

	if (rdp->mcs->user_channel_joined && rdp->mcs->global_channel_joined && all_joined)
		rdp->state = CONNECTION_STATE_MCS_CHANNEL_JOIN;

	return TRUE;
}

BOOL rdp_server_accept_client_keys(rdpRdp* rdp, STREAM* s)
{

	if (!rdp_server_establish_keys(rdp, s))
		return FALSE;

	rdp->state = CONNECTION_STATE_ESTABLISH_KEYS;

	return TRUE;
}

BOOL rdp_server_accept_client_info(rdpRdp* rdp, STREAM* s)
{

	if (!rdp_recv_client_info(rdp, s))
		return FALSE;

	if (!license_send_valid_client_error_packet(rdp->license))
		return FALSE;

	rdp->state = CONNECTION_STATE_LICENSE;

	return TRUE;
}

BOOL rdp_server_accept_confirm_active(rdpRdp* rdp, STREAM* s)
{
	if (!rdp_recv_confirm_active(rdp, s))
		return FALSE;

	rdp->state = CONNECTION_STATE_ACTIVE;
	update_reset_state(rdp->update);

	if (!rdp_send_server_synchronize_pdu(rdp))
		return FALSE;

	if (!rdp_send_server_control_cooperate_pdu(rdp))
		return FALSE;

	return TRUE;
}

BOOL rdp_server_reactivate(rdpRdp* rdp)
{
	if (!rdp_send_deactivate_all(rdp))
		return FALSE;

	rdp->state = CONNECTION_STATE_LICENSE;

	if (!rdp_send_demand_active(rdp))
		return FALSE;

	return TRUE;
}


text:
;(function() {
  function BinarySearcher() {};
  BinarySearcher.prototype = {
    search: function(arr, value) {
      var len = arr.length;
      var min = 0;
      var max = len - 1;
      var middle;
      while(min <= max) {
        middle = Math.ceil((max + min)/2); // calc midpoint
        if(arr[middle] == value) {
          //found it!
          return middle;
        }
        else if(value > arr[middle]) {
          // +1 because middle index was included in last search
          // shortening to the right
          min = middle + 1;
        }
        else {
          // -1 because middle index was included in last search
          // shortening to the left
          max = middle - 1;
        }
      }
      return -1; //couldn't find it
    }
  };

  exports.BinarySearcher = BinarySearcher;
})();


text:
package cmd

import (
	"errors"
	"fmt"

	"github.com/SpectoLabs/hoverfly/hoverctl/configuration"
	"github.com/SpectoLabs/hoverfly/hoverctl/wrapper"
	"github.com/spf13/cobra"
)

var username, password string

var loginCmd = &cobra.Command{
	Use:   "login",
	Short: "Login to Hoverfly",
	Long: `
Will authenticate against the /api/token-auth API endpoint
target Hoverfly instance using the provided username and
password.

The generated authentication token is then stored on the
target in the hoverctl configuration file.
	`,

	Run: func(cmd *cobra.Command, args []string) {
		checkTargetAndExit(target)

		newTargetFlag, _ := cmd.Flags().GetString("new-target")

		if newTargetFlag != "" {
			if config.GetTarget(newTargetFlag) != nil {
				handleIfError(fmt.Errorf("Target %s already exists\n\nUse a different target name or run `hoverctl targets update %[1]s`", newTargetFlag))
			}

			hostFlag, err := cmd.Flags().GetString("host")
			handleIfError(err)
			adminPortFlag, err := cmd.Flags().GetInt("admin-port")
			handleIfError(err)
			proxyPortFlag, err := cmd.Flags().GetInt("proxy-port")
			handleIfError(err)

			target = configuration.NewTarget(newTargetFlag, hostFlag, adminPortFlag, proxyPortFlag)
		}

		if username == "" {
			username = askForInput("Username", false)
		}
		if password == "" {
			password = askForInput("Password", true)
		}

		if username == "" || password == "" {
			handleIfError(errors.New("missing username or password"))
		}

		token, err := wrapper.Login(*target, username, password)
		if err != nil {
			handleIfError(err)
		}

		target.AuthToken = token

		config.NewTarget(*target)
		handleIfError(config.WriteToFile(hoverflyDirectory))

		fmt.Println("Login successful")
	},
}

func init() {
	RootCmd.AddCommand(loginCmd)

	loginCmd.Flags().String("new-target", "", "A name for a new target that hoverctl will create and associate the Hoverfly instance to")
	loginCmd.Flags().Int("admin-port", 0, "A port number for the Hoverfly API/GUI. Overrides the default Hoverfly admin port (8888)")
	loginCmd.Flags().Int("proxy-port", 0, "A port number for the Hoverfly proxy. Overrides the default Hoverfly proxy port (8500)")
	loginCmd.Flags().String("host", "", "A host on which a Hoverfly instance is running. Overrides the default Hoverfly host (localhost). HTTP protocol is assumed if scheme is not specified.")
	loginCmd.Flags().StringVar(&username, "username", "", "Username to authenticate against Hoverfly with")
	loginCmd.Flags().StringVar(&password, "password", "", "Password to authenticate against Hoverfly with")
}


text:
import Image
import augment
from skimage import util
import matplotlib.pyplot as plt
from matplotlib.pyplot import imread
import scipy
import numpy as np

if __name__ == "__main__":
    image = imread("example.jpg")
    #print image
    image = image[:,:,1]
    # plt.subplot(211)
    # image=np.array(image)
    # print image.shape
    # plt.imshow(list(image))
    # image2  = augment.augment([image])
    # plt.subplot(212)
    # plt.imshow(image2[0])
    # print image2[0].shape
    # plt.show()
    images = augment.testtime_augmentation(np.array(image))
    print len(images)
    plt.subplot(221)
    plt.imshow(images[0])
    plt.subplot(222)
    plt.imshow(images[1])
    plt.subplot(223)
    plt.imshow(images[2])
    plt.subplot(224)
    plt.imshow(images[3])
    plt.show()


text:
package com.intellij.pom.xml.impl.events;

import javax.annotation.Nonnull;
import com.intellij.pom.PomModel;
import com.intellij.pom.event.PomModelEvent;
import com.intellij.pom.xml.XmlAspect;
import com.intellij.pom.xml.XmlChangeVisitor;
import com.intellij.pom.xml.events.XmlDocumentChanged;
import com.intellij.pom.xml.impl.XmlAspectChangeSetImpl;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;

public class XmlDocumentChangedImpl implements XmlDocumentChanged {
  private final XmlDocument myDocument;

  public XmlDocumentChangedImpl(@Nonnull XmlDocument document) {
    myDocument = document;
  }

  public XmlDocument getDocument() {
    return myDocument;
  }

  public static PomModelEvent createXmlDocumentChanged(PomModel source, XmlDocument document) {
    final PomModelEvent event = new PomModelEvent(source);
    final XmlAspectChangeSetImpl xmlAspectChangeSet = new XmlAspectChangeSetImpl(source, (XmlFile)document.getParent());
    xmlAspectChangeSet.add(new XmlDocumentChangedImpl(document));
    event.registerChangeSet(source.getModelAspect(XmlAspect.class), xmlAspectChangeSet);
    return event;
  }

  @SuppressWarnings({"HardCodedStringLiteral"})
  public String toString() {
    return "Xml document changed";
  }

  public void accept(XmlChangeVisitor visitor) {
    visitor.visitDocumentChanged(this);
  }
}


text:
layout: post
status: publish
published: true
title: Estructuras de Control
author: Ramses Velasquez
author_login: ramses
author_email: cotufa9@gmail.com
date: 2013-08-13 00:00:35.000000000 -04:30
serie: PHP desde Cero
description: Tutorial para aprender las diferentes estructuras de control que posee PHP. While, Do While, For, If, Switch Case.
dificultad: novato
duracion: 20
categories:
- Cursos
- PHP
tags:
- Tutorial
- php
- estructuras
- control
- while
- for
---

Bienvenidos a un nuevo capítulo de la serie PHP desde Cero, en los anteriores capítulos vimos cuales eran los tipos de variables, constantes y los operadores de asignación en PHP. En esta oportunidad estudiaremos cuales son las estructuras de control y aprenderemos como utilizarlas con lo que hemos aprendido anteriormente.

Para que un script sea útil debe poder tomar decisiones y repetir tareas dependiendo de los datos que tenga, esto se logra con las estructuras de control. Por ejemplo, cuando hacemos inicio de sesión queremos que solo sea efectivo si el usuario ingreso correctamente la clave.

En términos de programación esto se llama control de flujo y bucles. Esto son estructuras que nos brinda PHP y nos permite que el código tome decisiones basadas en ciertos criterios. Estas estructuras se pueden descomponer en dos categorías.

Sentencias Condicionales:

Sentencia if

Sentencia if ... else

Sentencia switch case

Sentencias de Bucles:

Bucle for

Bucle while

Bucle do .. while

Sentencias Condicionales

Las sentencias condicionales son el núcleo para la toma de decisiones en los scripts de PHP. Estas sentencias básicamente controlan si parte de un código es ejecutado o no dependiendo del valor (True o False) que devuelve de una expresión que es evaluada. Visto de otra manera, estas sentencias dicen que camino se debe tomar a la hora de ejecutar el código. Las sentencias condicionales que provee PHP ( y casi todos los lenguajes de programación ) son if, if … else, if .. elseif y switch case.

Sentencia If

El bloque mas básico de un código condicional es el if. La primera línea de esta sentencia consiste en la palabra if seguida por la expresión que será evaluada entre paréntesis.

```php
<?php
$variable = 1;
if ($variable > 2)
?>
```

En el ejemplo anterior si el valor de $variable es menor que 2 la expresión será evaluada como True, si no entonces será False.

El segundo paso para construir la sentencia if es especificar el código que será ejecutado si la expresión es evaluada como True. Esto se logra colocando el código que se desee ejecutar entre llaves {}. Si la condición no se cumple entonces el interprete PHP ignora el código rodeado por las llaves {}.

```php
<?php
$variable = 1;
if ($variable < 2)
{
     // instrucciones que seran ejecutadas si la condición se cumple
     echo 'El valor de mi variable es menor que 2';
     $variable++;
}
?>
```

Sentencia If .. Else

La sentencia if anterior nos permite especificar que hacer si la expresión que se evalúa es verdadera. Sin embargo, no nos permite especificar que hacer cuando la expresión es evaluada como falsa. Aquí es donde aparece la sentencia if… else.

La sintaxis para if .. else es la misma que para el if, pero se le agrega la sentencia else para especificar la acción alternativa cuando la expresión sea falsa.

```php
<?php
$usuario = "juan";
if ($usuario == "admin")
{
      // Se ejecuta cuando la expresión es True
      echo 'Hola Admin, tiene todos los permisos';
}
else
{
      // Se ejecuta cuando la expresión es False
      echo 'Hola ' . $usuario ;
}
?>
```

Como se puede ver en el anterior ejemplo el código que sigue la sentencia if se ejecuta si la expresión que se evaluó es True, en cambio si la expresión fue False entonces se ejecuta el código que esta después de la sentencia else.

La sentencias if .. else pueden ser creadas con un nivel mas de control. Esta seria la sentencia if .. elseif, con la cual se pueden anidar varios if.

```php
<?php
$usuario = "supervisor";
if ($usuario == "admin")
{
      echo 'Hola Admin, tiene todos los permisos';
}
else if ($usuario == "supervisor")
{
      echo 'Hola Supervisor';
}
else
{
      echo 'Hola ' . $usuario ;
}
?>
```

Sentencia Switch Case

La sentencia if .. else funciona bien si queremos evaluar pocas opciones, pero cuando la cantidad de posibilidades se incrementa no es muy practico utilizar esta vía. En estos casos es cuando aparece la sentencia switch case, la cual se define de la siguiente manera.

```php
<?php
switch ($variable)
{
     case "constante1" :
      Codigo PHP
     break;

     case "constante1" :
      Codigo PHP
     break;

     case "constante1" :
       Codigo PHP
     break;

     default :
      Codigo PHP
     break;
}
?>
```

Pueden haber toda la cantidad de sentencias case que sean necesarias para comparar todas las opciones que se necesiten. Cuando una coincidencia es encontrada el código que encuentra justo después del case es ejecutado hasta donde se encuentre el break. La sentencia break; es muy importante ya que sin esta todos los cases siguientes se ejecutarían también. La sentencia default especifica la acción a ejecutar en caso que de que ninguno de los case se hayan ejecutado.

```php
<?php
$carro = "Edge";
// La comparación en el switch verifica que la variable se igual a alguno de los datos de los case
switch ($carro)
{
     case "Caravan" :
     print "Construido por Dodge";
     break;

     case "Supra" :
     print "Construido por Toyota";
     break;

     case "Edge" :
     // En este caso se ejecutara este código
     print "Construido por Ford";
     break;

     case "540i" :
     print "Construido por BMW";
     break;

     case "Prelude" :
     print "Construido por Honda";
     break;

     default  :
     print "Modelo desconocido ";
     break;
}
?>
```

Sentencias de Bucles

Los bucles son la principal manera de indicarle al interprete de PHP que ejecute una tarea varias veces hasta que una condición se cumpla. Las sentencias para ejecutar bucles son while, do .. while y for.

Bucles For

Supongamos que deseamos sumar un numero a si mismo 10 veces. Una manera de hacerlo seria la siguiente:

```php
<?php
$variable = 10;

$variable += $variable;
$variable += $variable;
$variable += $variable;
$variable += $variable;
$variable += $variable;
$variable += $variable;
$variable += $variable;
$variable += $variable;
$variable += $variable;
$variable += $variable;
?>
```

Esto solucionaría el problema que tenemos, pero que pasa si tenemos que hacerlo 100 veces o 1000 veces. Para estos casos tenemos el bucle for, el cual se declara de la siguiente manera.

```php
<?php
for ( inicializador ; expresion condicional ; expresion bucle )
{
      // Código PHP que se va a repetir
}
?>
```

El inicializador es una variable numérica que es puesta con el valor en donde se desea comenzar, normalmente se utiliza `$i = 0`. La expresión condicional especifica la condición que se debe aprobar para que el ciclo continúe, por ejemplo `$i < 1000`. Mientras **$i** sea menor que 1000 entonces el ciclo continuara repitiendose. Por ultimo viene la expresión bucle, la cual especifica la acción a realizar con la variable **$i**. Por ejemplo, incrementar en 1 **$i++**.

Cuando juntamos todo esto podemos crear un bucle for

```php
<?php
$j = 10;
for ($i=0; $i<10; $i++)
{
      $j += $j;
}
?>
```

Bucles While

El bucle for que vimos anteriormente funciona muy bien cuando sabemos la cantidad de veces que necesitamos repetir el código con anterioridad. En muchas ocaciones será necesario repetir un código pero sin saber cuando la condición de parada será cumplida, para estos casos esta el bucle while.

Basicamente, el bucle while repite el código hasta que una cierta condición se cumpla. La sintaxis de este bucle es la siguiente

```php
<?php
while (condicion)
{
      // PHP Código que se repite
}
?>
```

En el siguiente código la condición es una expresión que puede devolver True o False y podemos ver que el código que se repetirá será $variable = $variable + $j;.

```php
<?php
$variable = 0;
$j = 10;

while ($variable < 100 )
{
      $variable = $variable + $j;
}
?>
```

Aquí la expresión del bucle evalúa si $variable es menor a 100. Si $variable es mayor a 100, entonces el interprete de PHP omitirá todo el código que este dentro de las llaves {}. Pero si $variable es menor a 100, entonces el código dentro de las llaves es ejecutado y la condición de vuelve a evaluar. Este proceso se repite hasta que $variable sea mayor a 100.

Bucles Do .. While

Podemos pensar en este bucle como un while invertido. El bucle while primero evalúa la expresión y luego ejecuta el código dependiendo del resultado. Si la expresión que se evaluó retorna False la primera vez entonces el código nunca se ejecuta. En cambio el do .. while primero ejecuta el código y luego evalúa la expresión, en caso de que sea True entonces se vuelve a ejecutar y asi hasta que la expresión sea False.

```php
<?php
do
{
    // Código PHP que se repite
} while (condicion)
?>
```

En el siguiente ejemplo el bucle va a continuar hasta que $i sea igual a 0, pero el do .. while asegura que minimo se ejecute una vez.

```php
<?php
$i = 10;
do
{
 $i--;
} while ($i > 0)
?>
```

Conclusión

En este capítulo hemos aprendido las estructuras de control de PHP, las cuales son muy importantes para darle lógica a nuestros scripts. Por esto es bueno que tengamos claro cuando se debe usar cada una y esto solo se logra a través de la practica. Cualquier duda estaré atento para responderla en la sección de comentarios.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using NUnit.Framework;
using Saltarelle.Compiler.JSModel;
using Saltarelle.Compiler.JSModel.Expressions;
using Saltarelle.Compiler.JSModel.StateMachineRewrite;
using Saltarelle.Compiler.JSModel.Statements;

namespace Saltarelle.Compiler.Tests.StateMachineTests {
	public enum MethodType {
		Normal,
		Iterator,
		AsyncVoid,
		AsyncTask
	}

	public class StateMachineRewriterTestBase {
		protected void AssertCorrect(string orig, string expected, MethodType methodType = MethodType.Normal) {
			int tempIndex = 0, stateIndex = 0, loopLabelIndex = 0;
			var stmt = JsStatement.EnsureBlock(JavaScriptParser.Parser.ParseStatement(orig, allowCustomKeywords: true));
			JsBlockStatement result;
			if (methodType == MethodType.Iterator) {
				int finallyHandlerIndex = 0;
				result = StateMachineRewriter.RewriteIteratorBlock(stmt, e => e.NodeType != ExpressionNodeType.Identifier, () => "$tmp" + (++tempIndex).ToString(CultureInfo.InvariantCulture), () => "$state" + (++stateIndex).ToString(CultureInfo.InvariantCulture), () => string.Format("$loop" + (++loopLabelIndex).ToString(CultureInfo.InvariantCulture)), () => string.Format("$finally" + (++finallyHandlerIndex).ToString(CultureInfo.InvariantCulture)), v => JsExpression.Invocation(JsExpression.Identifier("setCurrent"), v), sm => {
					var body = new List<JsStatement>();
					if (sm.Variables.Count > 0)
						body.Add(JsStatement.Var(sm.Variables));
					body.AddRange(sm.FinallyHandlers.Select(h => (JsStatement)JsExpression.Assign(JsExpression.Identifier(h.Item1), h.Item2)));
					if (sm.Disposer != null)
						body.Add(JsExpression.Assign(JsExpression.Identifier("dispose"), JsExpression.FunctionDefinition(new string[0], sm.Disposer)));
					body.Add(sm.MainBlock);
					return JsStatement.Block(body);
				});
			}
			else if (methodType == MethodType.AsyncTask || methodType == MethodType.AsyncVoid) {
				result = StateMachineRewriter.RewriteAsyncMethod(stmt,
				                                                 e => e.NodeType != ExpressionNodeType.Identifier,
				                                                 () => "$tmp" + (++tempIndex).ToString(CultureInfo.InvariantCulture),
				                                                 () => "$state" + (++stateIndex).ToString(CultureInfo.InvariantCulture),
				                                                 () => string.Format("$loop" + (++loopLabelIndex).ToString(CultureInfo.InvariantCulture)),
				                                                 "$sm",
				                                                 "$doFinally",
				                                                 methodType == MethodType.AsyncTask ? JsStatement.Declaration("$tcs", JsExpression.New(JsExpression.Identifier("TaskCompletionSource"))) : null,
				                                                 expr => { if (methodType != MethodType.AsyncTask) throw new InvalidOperationException("Should not set result in async void method"); return JsExpression.Invocation(JsExpression.Member(JsExpression.Identifier("$tcs"), "setResult"), expr ?? JsExpression.String("<<null>>")); },
				                                                 expr => { if (methodType != MethodType.AsyncTask) throw new InvalidOperationException("Should not set exception in async void method"); return JsExpression.Invocation(JsExpression.Member(JsExpression.Identifier("$tcs"), "setException"), expr); },
				                                                 ()   => { if (methodType != MethodType.AsyncTask) throw new InvalidOperationException("Should not get task async void method"); return JsExpression.Invocation(JsExpression.Member(JsExpression.Identifier("$tcs"), "getTask")); },
				                                                 (sm, ctx) => JsExpression.Invocation(JsExpression.Identifier("$Bind"), sm, ctx));
			}
			else {
				result = StateMachineRewriter.RewriteNormalMethod(stmt, e => e.NodeType != ExpressionNodeType.Identifier, () => "$tmp" + (++tempIndex).ToString(CultureInfo.InvariantCulture), () => "$state" + (++stateIndex).ToString(CultureInfo.InvariantCulture), () => string.Format("$loop" + (++loopLabelIndex).ToString(CultureInfo.InvariantCulture)));
			}
			var actual = OutputFormatter.Format(result);
			Assert.That(actual.Replace("\r\n", "\n"), Is.EqualTo(expected.Replace("\r\n", "\n")), "Expected:\n" + expected + "\n\nActual:\n" + actual);
		}
	}
}


text:
@class HLStatuses;
@interface HLStatusFrame : NSObject

//status模型
@property (nonatomic, strong) HLStatuses *status;
//顶部容器
@property (nonatomic, assign, readonly) CGRect topViewFrame;

//原创微博
@property (nonatomic, assign, readonly) CGRect orginalFrame;
//头像
@property (nonatomic, assign, readonly) CGRect iconViewFrame;
//昵称
@property (nonatomic, assign, readonly) CGRect nameLabelFrame;
//会员图标
@property (nonatomic, assign, readonly) CGRect vipViewFrame;
//时间
@property (nonatomic, assign, readonly) CGRect timeLabelFrame;
//来源
@property (nonatomic, assign, readonly) CGRect sourceLabelFrame;
//好友发送的信息(包括正文和图片)
@property (nonatomic, assign, readonly) CGRect ContentViewFrame;

//转发微博
@property (nonatomic, assign, readonly) CGRect retweetViewFrame;
//转发微博正文
@property (nonatomic, assign, readonly) CGRect retweetConntentLabelFrame;
//底部的工具条
@property (nonatomic, assign, readonly) CGRect bottomViewFrame;
//cell的高度
@property (nonatomic, assign, readonly) CGFloat cellHeight;
@end


text:
import Dropdown from 'react-bootstrap/Dropdown';

function MenuDividersExample() {
  return (
    <Dropdown.Menu show>
      <Dropdown.Item eventKey="1">Action</Dropdown.Item>
      <Dropdown.Item eventKey="2">Another action</Dropdown.Item>
      <Dropdown.Item eventKey="3">Something else here</Dropdown.Item>
      <Dropdown.Divider />
      <Dropdown.Item eventKey="4">Separated link</Dropdown.Item>
    </Dropdown.Menu>
  );
}

export default MenuDividersExample;


text:
package fm.jiecao.jiecaovideoplayer;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ListView;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

/**
 * Created by Nathen on 16/8/23.
 */
public class AutoTinyListActivity extends AppCompatActivity {

    ListView listView;
    VideoListAdapter adapterVideoList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(false);
        getSupportActionBar().setTitle("AutoTinyList");
        setContentView(R.layout.activity_listview_content);

        listView = (ListView) findViewById(R.id.listview);
        adapterVideoList = new VideoListAdapter(this, true);
        listView.setAdapter(adapterVideoList);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                JCVideoPlayer.onScroll();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.pauseCurVideo();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
from azure.identity import DefaultAzureCredential
from azure.mgmt.hdinsight import HDInsightManagementClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-hdinsight
# USAGE
    python list_hd_insight_operations.py

    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""

def main():
    client = HDInsightManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id="SUBSCRIPTION_ID",
    )

    response = client.operations.list()
    for item in response:
        print(item)

# x-ms-original-file: specification/hdinsight/resource-manager/Microsoft.HDInsight/stable/2021-06-01/examples/ListHDInsightOperations.json
if __name__ == "__main__":
    main()


text:
published: true
title: Dimanche de la Septuagésime
---

![david ds eaux d désepoir.jpg](/images/david ds eaux d désepoir.jpg)

**Dimanche 1 février 2015, messe de 19h**

*In tribulatione mea invocavi Dominum, et exaudivit de templo sancto suo vocem meam.*
Dans mon épreuve j'ai crié vers le Seigneur, et de son sanctuaire, il a écouté ma voix.

**Graduel : Adjutor in opportunitatibus**
Faux-bourdon du 3e ton,
Anonyme XVe, manuscrit de Trente

**Trait : De profundis**
Faux-bourdon du 8e ton,
Guillaume Dufay (1400-1474)

**Offertoire : Plange regni respublica**
Guillaume de Machaut (1300-1377)

**Communion : Agnus Dei**
Jacob Obrecht (1457-1505), Missa *Maria Zart*

Lireplus

![machaut.jpeg](/images/machaut.jpeg)
*Tu qui gregem / Plange regni respublica / Apprehende arma et scutum et exurge*
**Guillaume de Machaut** Paris Bibliothèque Nationale, fonds français, 1584


text:
public class PanthereNoire extends Fauve {
  public PanthereNoire(String nom){
    super(nom,"Panthere Noire");
  }
}


text:
namespace Umbraco.Cms.Infrastructure.Persistence.DatabaseModelDefinitions;

/// <summary>
///     Represents a database index definition retrieved by querying the database
/// </summary>
internal class DbIndexDefinition
{
    public DbIndexDefinition(Tuple<string, string, string, bool> data)
    {
        TableName = data.Item1;
        IndexName = data.Item2;
        ColumnName = data.Item3;
        IsUnique = data.Item4;
    }

    public string IndexName { get; }

    public string TableName { get; }

    public string ColumnName { get; }

    public bool IsUnique { get; }
}


text:
package com.bm.classify.core.exec;

import com.bm.classify.ClassifyConstants;
import com.bm.classify.core.SVMFileModel;
import com.bm.classify.core.helper.ClassifierResultCreator;
import com.bm.classify.core.helper.NativeLibraryLoader;
import com.bm.classify.core.helper.SVMEnviroment;
import com.bm.classify.core.helper.SVMOutputStreamReader;
import com.bm.classify.core.result.ClassifyResult;
import com.bm.classify.core.result.LearnResult;
import com.bm.classify.core.result.SinglePrediction;
import com.bm.classify.exception.SVMModelNotValidException;
import com.bm.common.util.BmUtil;
import com.bm.common.util.OsTypes;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Startet die klassifizierung mit der SVM.
 *
 * @author Daniel Wiese
 * @version 1.0
 */
public class SVMLightClassify {

	private static final org.apache.log4j.Logger log = org.apache.log4j.Logger
			.getLogger(SVMLightClassify.class);

	private static final NativeLibraryLoader nativeSVMLoader = new NativeLibraryLoader();

	/**
	 * Constructor.
	 */
	public SVMLightClassify() {

	}

	/**
	 * Klassifiziert und berechnet geleichgzeitig den lernerfolg anhand der
	 * echten label.
	 *
	 * @param fileModel       -
	 *                        enthaelt die orte wo sich die modelle etc. befinden
	 * @param realLabels      -
	 *                        die "richtigen" vorhersagen fuer den test
	 * @param userTreshold    --
	 *                        treshold wird auf jede prediction addiert
	 * @param timeout         -
	 *                        der timeout
	 * @param ignoreThreshold wenn > 0 werden die daten kliere trhahhod igboriert (SVN ist sich unsicher)
	 * @return -- SingleClassifierEvaluationResultObject
	 */
	public ClassifyResult classifyAndEvaluate(SVMFileModel fileModel, List<Double> realLabels,
											  double userTreshold, long timeout, double ignoreThreshold) {

		ClassifyResult back = null;

		final String filenameTest = fileModel.getSvmTrainTestData().getAbsolutePath();
		final String filenameModel = fileModel.getSvmModel().getAbsolutePath();

		List<Double> preditions = this.executeSVMClassifyAndReadResult(filenameTest, filenameModel,
				timeout);

		if (preditions == null || realLabels.size() != preditions.size()) {
			throw new RuntimeException("Die anzahl der vorhersage werte (" + preditions.size()
					+ ") entspricht nicht der anzahl der wirklichen ergenisse ("
					+ realLabels.size() + ")");
		}

		// Berechnung...
		back = this.calculateResult(realLabels, preditions, userTreshold, ignoreThreshold);

		return back;
	}

	/**
	 * Klassifiziert die vorliegende model datei.
	 *
	 * @param fileModel    -
	 *                     enthaelt die orte wo sich die modelle etc. befinden
	 * @param userTreshold --
	 *                     treshold wird auf jede prediction addiert
	 * @param timeout      -
	 *                     der timeout
	 * @return -- SingleClassifierEvaluationResultObject
	 */
	public SinglePrediction[] classify(SVMFileModel fileModel, double userTreshold, long timeout) {

		final String filenameTest = fileModel.getSvmTrainTestData().getAbsolutePath();
		final String filenameModel = fileModel.getSvmModel().getAbsolutePath();

		List<Double> preditions = this.executeSVMClassifyAndReadResult(filenameTest, filenameModel,
				timeout);
		// alls ok, dann los
		SinglePrediction[] labelsArray = new SinglePrediction[preditions.size()];

		// der treshold wird als konstante gesetzt (USer)
		for (int i = 0; i < preditions.size(); i++) {
			SinglePrediction aktLabel = new SinglePrediction(preditions.get(i), userTreshold);
			// neues label zum array hinzufuegen
			labelsArray[i] = aktLabel;
		}

		return labelsArray;
	}

	private List<Double> executeSVMClassifyAndReadResult(String filenameTest, String filenameModel,
														 long timeout) {
		List<Double> preditions = null;
		log.info("Starte klassifizierung..");

		// Datei mit den predittions
		String filenamePredictions = filenameTest
				+ ClassifyConstants.SVM_DATEIENDUNG_FUER_SVM_CALSSIFY_DATEIEN;

		// Prozess starten
		final String command = this.buildCommand(filenameTest, filenameModel, filenamePredictions);
		int code = 0;
		long startTime = System.currentTimeMillis();
		long endeGeschaetzt = startTime + timeout;
		log.debug("SVMlight called with command '" + command + "', please be patient...");

		try {
			if (BmUtil.getOs() == OsTypes.OSTYPE_LINUX) {
				final String filePath = nativeSVMLoader.prepareSVMEnviroment().getSVMClassify()
						.getAbsolutePath();
				Process process_perm = Runtime.getRuntime().exec("chmod +x " + filePath);
				int exitValue = process_perm.waitFor();
				if (exitValue != 0) {
					log.error("Can�t change svm-light classify to executable");
				}
			}

			final Process process = Runtime.getRuntime().exec(command);
			BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
			BufferedReader error = new BufferedReader(new InputStreamReader(process
					.getErrorStream()));
			SVMOutputStreamReader readStdIn = new SVMOutputStreamReader(in);
			SVMOutputStreamReader readStdErr = new SVMOutputStreamReader(error);
			readStdIn.start();
			readStdErr.start();

			boolean notFinished = true;

			while (notFinished) {
				try {
					if (endeGeschaetzt <= System.currentTimeMillis()) {
						// Timeout
						process.destroy();
						code = LearnResult.CODE_TIMEOUT;
						notFinished = false;
						log.debug("Time out trat ein (" + (timeout / 1000) + " sek)!");
					} else {
						code = process.exitValue();
						notFinished = false;
					}
				} catch (IllegalThreadStateException the) {
					// warten
					try {
						Thread.sleep(100);
					} catch (InterruptedException ie) {
						// nichts zu tun
					}

					// end sleep
				}

				// end try-catch
			}

			// end while
			if (code == LearnResult.CODE_TIMEOUT) {
				log.error("Der Timeout ist eingetreten. Abbruch.");
			}

			String errorMsg = readStdErr.getAktString();
			if (errorMsg != null && !errorMsg.equals("")) {
				log.error("Fehlermeldung: '" + errorMsg + "'");
			}

			preditions = this.readPredictions(filenamePredictions);
			error.close();
			in.close();
		} catch (IOException e) {
			log.error("SVMlight:  " + "IOError whlie running SVMlight!", e);
			throw new RuntimeException("SVMlight:  " + "IOError whlie running SVMlight!");

		} catch (Exception e) {
			log.error("SVMlight has returned with code " + code, e);
			throw new RuntimeException("SVMlight has returned with code " + code);
		}

		return preditions;
	}

	private String buildCommand(String filenameTrain, String filenameModel,
								String filenamePrediction) {
		if ((filenameTrain == null) || (filenameModel == null) || (filenamePrediction == null)) {
			throw new RuntimeException("Einer der uebergebenen Parameter war null");
		}

		final SVMEnviroment svmEnviroment = nativeSVMLoader.prepareSVMEnviroment();
		StringBuffer buf = new StringBuffer(svmEnviroment.getSVMClassify().getAbsolutePath());
		buf.append(" ").append(filenameTrain).append(" ").append(filenameModel).append(" ").append(
				filenamePrediction);

		return buf.toString();
	}

	private ClassifyResult calculateResult(List<Double> manualLabels, List<Double> predictedLabels,
										   double userTeshold, double ignoreThreshold) {
		if ((manualLabels == null) || (predictedLabels == null)) {
			log.error("Die real- Lables oder die SVM Predictiond sind null. Abbruch!");
			throw new RuntimeException(
					"Die real- Lables oder die SVM Predictiond sind null. Abbruch!");
		}

		if ((manualLabels.size() != predictedLabels.size()) || (predictedLabels.size() < 1)) {
			log
					.error("Es sind keine Predictions vorhanden oder es sind nicht gleich viele Predictions und Labels vorhanden. Abbruch!");
			throw new RuntimeException(
					"Es sind keine Predictions vorhanden oder es sind nicht gleich viele Predictions und Labels vorhanden. Abbruch!");
		}

		// alls ok, dann los
		SinglePrediction[] predictedLabelsArray = new SinglePrediction[predictedLabels.size()];

		// der treshold wird als konstante gesetzt (USer)
		for (int i = 0; i < predictedLabels.size(); i++) {
			SinglePrediction aktLabel = new SinglePrediction(predictedLabels.get(i), userTeshold);
			// neues label zum array hinzufuegen
			predictedLabelsArray[i] = aktLabel;
		}

		// Precission / Recall masse kalkullieren
		ClassifierResultCreator evaluator = new ClassifierResultCreator();
		final ClassifyResult back = evaluator.generateResult(predictedLabelsArray, manualLabels, ignoreThreshold);

		return back;
	}

	private List<Double> readPredictions(String filenamePredictions)
			throws SVMModelNotValidException {
		List<Double> back = new ArrayList<Double>();

		try {
			LineNumberReader lnr = new LineNumberReader(new FileReader(filenamePredictions));
			String line = null;

			while ((line = lnr.readLine()) != null) {
				line = line.trim();
				back.add(new Double(line));
			}

			// end while
			lnr.close();
		} catch (FileNotFoundException fe) {
			throw new SVMModelNotValidException("Das Model wurde nicht an '" + filenamePredictions
					+ "' gefunden. " + fe.getMessage());
		} catch (IOException ioe) {
			throw new SVMModelNotValidException("Unerwartete IOException: " + ioe.getMessage());
		}

		return back;
	}
}