text:
package com.reyansh.audio.audioplayer.free.AsyncTasks;

import android.os.AsyncTask;
import android.widget.Toast;

import com.reyansh.audio.audioplayer.free.Common;
import com.reyansh.audio.audioplayer.free.Models.Song;
import com.reyansh.audio.audioplayer.free.R;
import com.reyansh.audio.audioplayer.free.Utils.PreferencesHelper;

import java.util.ArrayList;

/**
 * Created by REYANSH on 8/2/2017.
 */

/**
*Class to add songs into queue or to play next.
 * This could have been on the main the thread but its safe to to on background thread,
 * just to stay away from any kind of lag into the animation and stuff.
*/

public class AsyncAddTo extends AsyncTask<Void, Void, Boolean> {

    private boolean mAddToQueue = false;
    private ArrayList<Song> mSongs;
    private Song song;
    private Common mApp;
    private String mName;

    public AsyncAddTo(String name, boolean addToQueue, Song song) {
        mAddToQueue = addToQueue;
        this.song = song;
        mName = name;

    }

    public AsyncAddTo(String name, boolean addToQueue, ArrayList<Song> songs) {
        mAddToQueue = addToQueue;
        mSongs = songs;
        mName = name;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        mApp = (Common) Common.getInstance().getApplicationContext();
        if (mApp.isServiceRunning()) {
            if (mAddToQueue) {
                if (song != null) {
                    mApp.getService().getSongList().add(song);
                } else {
                    mApp.getService().getSongList().addAll(mSongs);
                }
            } else {
                if (song != null) {
                    mApp.getService().getSongList().add(mApp.getService().getCurrentSongIndex() + 1, song);
                } else {
                    mApp.getService().getSongList().addAll(mApp.getService().getCurrentSongIndex() + 1, mSongs);
                }
            }
        } else {
            ArrayList<Song> songs = mApp.getDBAccessHelper().getQueue();
            int pos = PreferencesHelper.getInstance().getInt(PreferencesHelper.Key.CURRENT_SONG_POSITION, 0);
            if (songs.size() == 0) {
                return false;
            }
            if (mAddToQueue) {
                if (song != null) {
                    songs.add(song);
                } else {
                    songs.addAll(mSongs);
                }
            } else {
                if (song != null) {
                    songs.add(pos + 1, song);
                } else {
                    songs.addAll(pos + 1, mSongs);
                }
            }
            mApp.getDBAccessHelper().saveQueue(songs);
        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean aVoid) {
        super.onPostExecute(aVoid);
        if (aVoid) {
            if (mAddToQueue) {
                String message = Common.getInstance().getString(R.string.added_to_queue);
                message = mName + " " + message;
                Toast.makeText(Common.getInstance(), message, Toast.LENGTH_SHORT).show();
            } else {
                String message = Common.getInstance().getString(R.string.will_be_played_next);
                message = mName + " " + message;
                Toast.makeText(Common.getInstance(), message, Toast.LENGTH_SHORT).show();

            }
        } else {
            Toast.makeText(Common.getInstance(), R.string.queue_is_empty, Toast.LENGTH_SHORT).show();
        }
    }
}


text:
<?php

include(dirname(__FILE__).'/../../bootstrap/functional.php');

$browser = new sfTestFunctional(new sfBrowser());

$browser->
  get('/addressBook/index')->

  with('request')->begin()->
    isParameter('module', 'addressBook')->
    isParameter('action', 'index')->
  end()->

  with('response')->begin()->
    isStatusCode(200)->
    checkElement('body', '!/This is a temporary page/')->
  end()
;

redpajama_set_name: RedPajamaGithub


text:
'''
@author: Dallas Fraser
@id: 20652186
@class: CS686
@date: 2016-04-02
@note: contains functions for creating networkx graphs with GraphNodes
'''
from os.path import isfile
from inducer.graph.graph_node import GraphNode
import networkx as nx

def is_colored(G, vertex):
    """Returns whether the vertex is colored or not"""
    return G.nodes[vertex]['node'].color is not None

def chromatic_number(G):
    """Returns the chromatic number of G

    Parameters:
        G: the networkx graph
    Returns:
        : the chromatic number of G (int)
    """
    colors = []
    for node in G:
        if G.nodes[node]['node'].color not in colors:
            colors.append(G.nodes[node]['node'].color)
    return len(colors)

def copy_graph_colors(G):
    """Returns a copy of the G while maintaining its colors
    """
    H = nx.Graph()
    for n in G.nodes():
        node = GraphNode(index=n,
                         logger=G.nodes[n]['node'].logger,
                         color=G.nodes[n]['node'].color,
                         )
        H.add_node(n, node=node)
    for edge in G.edges():
        H.add_edge(edge[0], edge[1])
    return H

def copy_graph(G):
    """Returns a copy of the G
    """
    return convert_to_networkx(convert_to_d3(G))

def color_vertex(G, vertex, color):
    """Colors a vertex of G

    Parameters:
        G: a networkx graph with Graph Nodes
        vertex: the vertex number (int)
        color: the color
    """
    G.nodes[vertex]['node'].color = color

def get_color(G, vertex):
    return G.nodes[vertex]['node'].color

def valid_coloring(G):
    """Returns True if G's coloring is valid

    Parameters:
        G: a networkx graph with Graph Nodes
    Return:
        valid: True if valid coloring (boolean)
    """
    valid = False
    if G is not None:
        valid = True
        for node in G.nodes():
            for neighbor in G.neighbors(node):
                if (G.nodes[neighbor]['node'].color ==
                        G.nodes[node]['node'].color):
                    valid = False
                    break
            if not valid:
                break
    return valid

def available_color(G, vertex, color):
    """Returns True if color is available or not

    Parameters:
        G: a networkx graph with Graph Nodes
        vertex: the vertex number (int)
        color: the color to see if available
    Returns:
        available: True if color is available (boolean)
    """
    available = True
    for neighbor in G.neighbors(vertex):
        if G.nodes[neighbor]['node'].color == color:
            available = False
            break
    return available

def available_colors(G, vertex, number_of_colors):
    """Returns all the available colors for vertex

    Parameters:
        G: a networkx graph with Graph Nodes
        vertex: the vertex number (int)
        number_of_colors: the number of colors (int)
    Returns:
        colors: list of available colors (list)
    """
    colors = [x for x in range(0, number_of_colors)]
    for neighbor in G.neighbors(vertex):
        try:
            index = colors.index(G.nodes[neighbor]['node'].color)
            colors.pop(index)
        except Exception:
            pass
    return colors

def create_graph(g=None, text_file=None, logger=None):
    """Returns a networkx Graph with GraphNodes

    Parameters:
        g: the dictionary representation of a graph (dictionary)
        text_file: the file path to a text file with the graph (file)
        logger: the logger the graph should use (logger)
    Returns:
        graph: the networkx graph
    """
    if g is not None and text_file is not None:
        raise Exception("Only g or text_file should be given")
    graph = nx.Graph()
    if g is not None:
        graph = convert_to_networkx(g, logger=logger)
    if text_file is not None:
        with open(text_file) as f:
            if not isfile(text_file):
                raise Exception("File not found")
            lines = []
            for line in f:
                lines.append(line)
            graph = convert_to_networkx(text_to_d3(lines))
    return graph

def convert_to_networkx(g, logger=None):
    ''' Returns a networkx graph

    Parameters:
        g: the python dictionary repesentation of a graph (dictionary)
    Returns:
        graph: the graph G (networkx)
    '''
    graph = nx.Graph()
    for node in g['nodes']:
        graph.add_node(node, node=GraphNode(index=node, logger=logger))
    for edge in g['edges']:
        graph.add_edge(edge[0], edge[1])
    return graph

def convert_to_d3(g):
    '''Returns a dictionary representation of a graph used for d3

    Parameters:
        g: the graph G (networkx)
    Returns:
        graph: python dictionary representation of a graph (dictionary)
                eg. {'nodes':[n1],'edges':[[n1,n2]]}
    '''
    graph = {'nodes': [], 'edges': []}
    for node in g.nodes():
        graph['nodes'].append(node)
    for edge in g.edges():
        graph['edges'].append(list(edge))
    return graph

def text_to_d3(lines):
    ''' Returns a dictionary representation of a graph used for d3

    Parameters:
        lines: a list of lines from the text file (list)
    Returns:
        d3: a d3 representation of the graph
    '''
    graph = {'nodes': [], 'edges': []}
    for line in lines:
        entries = line.split(":")
        try:
            node = int(entries[0])
        except Exception:
            node = None
        if (len(entries) > 1):
            entries[1] = entries[1].replace(" ", "")
            edges = entries[1].split(",")
            for edge in edges:
                if edge != '':
                    e = int(edge)
                    if [e, node] not in graph['edges'] and node != e:
                        # do not want to add an edges twice
                        graph['edges'].append([node, e])
        if node is not None:
            graph['nodes'].append(node)
    return graph

def d3_to_text(g):
    '''Returns a text string of a graph g (used for saving to files)

    Parameters:
        g: the d3 graph representation
    Returns:
        graph: list of text representation the graph (list)
    '''
    graph = []
    for node in g['nodes']:
        line = str(node) + ":"
        edges = []
        for edge in g['edges']:
            if node == edge[0]:
                edges.append(str(edge[1]))
            elif node == edge[1]:
                edges.append(str(edge[0]))
        line = line + ",".join(edges)
        graph.append(line)
    return graph


text:
namespace cc {
namespace {

// See AnimationPlayer tests on layer registration/unregistration in
// animation_player_unittest.cc.

TEST(AnimationHostTest, SyncTimelinesAddRemove) {
  scoped_ptr<AnimationHost> host(AnimationHost::Create(ThreadInstance::MAIN));
  scoped_ptr<AnimationHost> host_impl(
      AnimationHost::Create(ThreadInstance::IMPL));

  const int timeline_id = AnimationIdProvider::NextTimelineId();
  scoped_refptr<AnimationTimeline> timeline(
      AnimationTimeline::Create(timeline_id));
  host->AddAnimationTimeline(timeline.get());
  EXPECT_TRUE(timeline->animation_host());

  EXPECT_FALSE(host_impl->GetTimelineById(timeline_id));

  host->PushPropertiesTo(host_impl.get());

  scoped_refptr<AnimationTimeline> timeline_impl =
      host_impl->GetTimelineById(timeline_id);
  EXPECT_TRUE(timeline_impl);
  EXPECT_EQ(timeline_impl->id(), timeline_id);

  host->PushPropertiesTo(host_impl.get());
  EXPECT_EQ(timeline_impl, host_impl->GetTimelineById(timeline_id));

  host->RemoveAnimationTimeline(timeline.get());
  EXPECT_FALSE(timeline->animation_host());

  host->PushPropertiesTo(host_impl.get());
  EXPECT_FALSE(host_impl->GetTimelineById(timeline_id));

  EXPECT_FALSE(timeline_impl->animation_host());
}

TEST(AnimationHostTest, ImplOnlyTimeline) {
  scoped_ptr<AnimationHost> host(AnimationHost::Create(ThreadInstance::MAIN));
  scoped_ptr<AnimationHost> host_impl(
      AnimationHost::Create(ThreadInstance::IMPL));

  const int timeline_id1 = AnimationIdProvider::NextTimelineId();
  const int timeline_id2 = AnimationIdProvider::NextTimelineId();

  scoped_refptr<AnimationTimeline> timeline(
      AnimationTimeline::Create(timeline_id1));
  scoped_refptr<AnimationTimeline> timeline_impl(
      AnimationTimeline::Create(timeline_id2));
  timeline_impl->set_is_impl_only(true);

  host->AddAnimationTimeline(timeline.get());
  host_impl->AddAnimationTimeline(timeline_impl.get());

  host->PushPropertiesTo(host_impl.get());

  EXPECT_TRUE(host->GetTimelineById(timeline_id1));
  EXPECT_TRUE(host_impl->GetTimelineById(timeline_id2));
}

}  // namespace
}  // namespace cc


text:
package io.datarouter.auth.job;

import java.util.List;

import javax.inject.Inject;

import io.datarouter.auth.service.DatarouterAuthConfigScanner;
import io.datarouter.instrumentation.task.TaskTracker;
import io.datarouter.job.BaseJob;
import io.datarouter.job.service.ConfigurationScanReportService;
import io.datarouter.web.autoconfig.ConfigScanDto;

public class AuthConfigurationScanJob extends BaseJob{

	@Inject
	private DatarouterAuthConfigScanner configScanner;
	@Inject
	private ConfigurationScanReportService reportService;

	@Override
	public void run(TaskTracker tracker){
		List<ConfigScanDto> scans = List.of(
				configScanner.checkDatarouterAccountsWithDefaultKeys(),
				configScanner.checkForDefaultUserId());
		reportService.scanConfigurationAndSendEmail("AuthConfig Alert", scans);
	}

}


text:
describe("sandbox", () => {
    var root: HTMLDivElement;
    beforeEach(() => {
        root = document.createElement("div");
        root = <HTMLDivElement>document.body.appendChild(root);
    });
    afterEach(() => {
        document.body.removeChild(root);
    });
    it("works", () => {
        root.appendChild(document.createElement("div"));
        expect(root.innerHTML.toLowerCase()).toBe("

");
    });

    var startsWithGradient = /^(?:repeating\-)?(?:linear|radial)\-gradient/ig;
    var revdirs = { top: "bottom", bottom: "top", left: "right", right: "left" };
    function gradientWebkitter(style: any, value: any, name: string) {
        if (startsWithGradient.test(value)) {
            var pos = (<string>value).indexOf("(to ");
            if (pos > 0) {
                pos += 4;
                var posend = (<string>value).indexOf(",", pos);
                var dir = (<string>value).slice(pos, posend);
                dir = dir.split(" ").map(v=> (<any>revdirs)[v] || v).join(" ");
                value = (<string>value).slice(0, pos - 3) + dir + (<string>value).slice(posend);
            }
            value = "-webkit-" + value;
        }
        style[name] = value;
    };

    it("gradient", () => {
        var s = {};
        gradientWebkitter(s, "linear-gradient(to bottom,red,blue)", "background");
        expect((<any>s)["background"]).toBe("-webkit-linear-gradient(top,red,blue)");
    });
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->
	<bean id="myRealm" class="org.llh.ssl.common.MyRealm" />

	<!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->
	<!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->
	<!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="myRealm" />
	</bean>

	<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
	<!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- Shiro的核心安全接口,这个属性是必须的 -->
		<property name="securityManager" ref="securityManager" />
		<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
		<property name="loginUrl" value="/login" />
		<!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码为main.jsp了) -->
		<!-- <property name="successUrl" value="/user/index"/> -->
		<!-- 添加自己的filter -->
		<!--
		<property name="filters">
			<map>
				<entry key="authc" value-ref="shiro"></entry>
			</map>
		</property> -->
		<!-- 用户访问未对其授权的资源时,所显示的连接 -->
		<!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->
		<property name="unauthorizedUrl" value="/unauthorized" />

		<!-- Shiro连接约束配置,即过滤链的定义 -->
		<!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 -->
		<!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
		<!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->
		<!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
	</bean>

	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

	<!-- 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->
	<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
		depends-on="lifecycleBeanPostProcessor"/>
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager"/>
	</bean>
</beans>


text:
package com.metamx.common;

import com.google.common.base.Function;

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

/**
 */
public class MapUtils
{
  public static String getString(Map<String, Object> in, String key)
  {
    return getString(in, key, null);
  }

  public static String getString(Map<String, Object> in, String key, String defaultValue)
  {
    Object retVal = in.get(key);

    if (retVal == null) {
      if (defaultValue == null) {
        throw new IAE("Key[%s] is required in map[%s]", key, in);
      }

      return defaultValue;
    }

    return retVal.toString();
  }

  public static Function<Map<String, Object>, String> stringFromMapFn(final String key)
  {
    return new Function<Map<String, Object>, String>()
    {
      @Override
      public String apply(Map<String, Object> map)
      {
        return MapUtils.getString(map, key);
      }
    };
  }

  public static <RetVal> RetVal lookupStringValInMap(Map<String, Object> map, String key, Map<String, RetVal> lookupMap)
  {
    String lookupKey = getString(map, key);
    RetVal retVal = lookupMap.get(lookupKey);

    if (retVal == null) {
      throw new IAE("Unknown %s[%s], known values are%s", key, lookupKey, lookupMap.keySet());
    }

    return retVal;
  }

  public static int getInt(Map<String, Object> in, String key)
  {
    return getInt(in, key, null);
  }

  public static int getInt(Map<String, Object> in, String key, Integer defaultValue)
  {
    Object retVal = in.get(key);

    if (retVal == null) {
      if (defaultValue == null) {
        throw new IAE("Key[%s] is required in map[%s]", key, in);
      }

      return defaultValue;
    }

    try {
      return Integer.parseInt(retVal.toString());
    }
    catch (NumberFormatException e) {
      throw new IAE(e, "Key[%s] should be an int, was[%s]", key, retVal);
    }
  }

  public static long getLong(Map<String, Object> in, String key)
  {
    return getLong(in, key, null);
  }

  public static long getLong(Map<String, Object> in, String key, Long defaultValue)
  {
    Object retVal = in.get(key);

    if (retVal == null) {
      if (defaultValue == null) {
        throw new IAE("Key[%s] is required in map[%s]", key, in);
      }

      return defaultValue;
    }

    try {
      return Long.parseLong(retVal.toString());
    }
    catch (NumberFormatException e) {
      throw new IAE(e, "Key[%s] should be a long, was[%s]", key, retVal);
    }
  }

  public static double getDouble(Map<String, Object> in, String key)
  {
    return getDouble(in, key, null);
  }

  public static double getDouble(Map<String, Object> in, String key, Double defaultValue)
  {
    Object retVal = in.get(key);

    if (retVal == null) {
      if (defaultValue == null) {
        throw new IAE("Key[%s] is required in map[%s]", key, in);
      }

      return defaultValue;
    }

    try {
      return Double.parseDouble(retVal.toString());
    }
    catch (NumberFormatException e) {
      throw new IAE(e, "Key[%s] should be a double, was[%s]", key, retVal);
    }
  }

  public static List<Object> getList(Map<String, Object> in, String key)
  {
    return getList(in, key, null);
  }

  public static List<Object> getList(Map<String, Object> in, String key, List<Object> defaultValue)
  {
    Object retVal = in.get(key);

    if (retVal == null) {
      if (defaultValue == null) {
        throw new IAE("Key[%s] is required in map[%s]", key, in);
      }

      return defaultValue;
    }

    try {
      return (List<Object>) retVal;
    }
    catch (ClassCastException e) {
      throw new IAE("Key[%s] should be a list, was [%s]", key, retVal);
    }
  }

  public static Map<String, Object> getMap(Map<String, Object> in, String key)
  {
    return getMap(in, key, null);
  }

  public static Map<String, Object> getMap(Map<String, Object> in, String key, Map<String, Object> defaultValue)
  {
    Object retVal = in.get(key);

    if (retVal == null) {
      if (defaultValue == null) {
        throw new IAE("Key[%s] is required in map[%s]", key, in);
      }

      return defaultValue;
    }

    try {
      return (Map<String, Object>) retVal;
    }
    catch (ClassCastException e) {
      throw new IAE("Key[%s] should be a map, was [%s]", key, retVal);
    }
  }
}


text:
<?php

namespace SevenShores\Hubspot\Endpoints;

abstract class Endpoint
{
    /**
     * @var \SevenShores\Hubspot\Http\Client
     */
    protected $client;

    /**
     * Makin' a good old endpoint.
     *
     * @param \SevenShores\Hubspot\Http\Client $client
     */
    public function __construct($client)
    {
        $this->client = $client;
    }

    /**
     * Convert a time, DateTime, or string to a millisecond timestamp.
     *
     * @param null|\DateTime|int $time
     *
     * @return null|int
     */
    protected function timestamp($time)
    {
        return ms_timestamp($time);
    }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Microsoft.Owin.Host.HttpListener.Tests
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    /// These tests measure the results of the OwinHttpListenerRequest construction as presented through the OWIN interface.
    /// NOTE: These tests require SetupProject.bat to be run as admin from a VS command prompt once per machine.
    public class OwinHttpListenerRequestTests
    {
        private static readonly string[] HttpServerAddress = new string[] { "http", "localhost", "8080", "/BaseAddress/" };
        private const string HttpClientAddress = "http://localhost:8080/BaseAddress/";

        [Fact]
        public async Task CallParameters_EmptyGetRequest_NullBodyNonNullCollections()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    Assert.NotNull(env);
                    Assert.NotNull(env.Get<Stream>("owin.RequestBody"));
                    Assert.NotNull(env.Get<Stream>("owin.ResponseBody"));
                    Assert.NotNull(env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"));
                    Assert.NotNull(env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"));
                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            await SendGetRequest(listener, HttpClientAddress);
        }

        [Fact]
        public async Task Environment_EmptyGetRequest_RequiredKeysPresentAndCorrect()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    object ignored;
                    Assert.True(env.TryGetValue("owin.RequestMethod", out ignored));
                    Assert.Equal("GET", env["owin.RequestMethod"]);

                    Assert.True(env.TryGetValue("owin.RequestPath", out ignored));
                    Assert.Equal("/SubPath", env["owin.RequestPath"]);

                    Assert.True(env.TryGetValue("owin.RequestPathBase", out ignored));
                    Assert.Equal("/BaseAddress", env["owin.RequestPathBase"]);

                    Assert.True(env.TryGetValue("owin.RequestProtocol", out ignored));
                    Assert.Equal("HTTP/1.1", env["owin.RequestProtocol"]);

                    Assert.True(env.TryGetValue("owin.RequestQueryString", out ignored));
                    Assert.Equal("QueryString", env["owin.RequestQueryString"]);

                    Assert.True(env.TryGetValue("owin.RequestScheme", out ignored));
                    Assert.Equal("http", env["owin.RequestScheme"]);

                    Assert.True(env.TryGetValue("owin.Version", out ignored));
                    Assert.Equal("1.0", env["owin.Version"]);

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            await SendGetRequest(listener, HttpClientAddress + "SubPath?QueryString");
        }

        [Fact]
        public async Task Environment_Post10Request_ExpectedKeyValueChanges()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    object ignored;
                    Assert.True(env.TryGetValue("owin.RequestMethod", out ignored));
                    Assert.Equal("POST", (string)env["owin.RequestMethod"]);

                    Assert.True(env.TryGetValue("owin.RequestPath", out ignored));
                    Assert.Equal("/SubPath", (string)env["owin.RequestPath"]);

                    Assert.True(env.TryGetValue("owin.RequestPathBase", out ignored));
                    Assert.Equal("/BaseAddress", (string)env["owin.RequestPathBase"]);

                    Assert.True(env.TryGetValue("owin.RequestProtocol", out ignored));
                    Assert.Equal("HTTP/1.0", (string)env["owin.RequestProtocol"]);

                    Assert.True(env.TryGetValue("owin.RequestQueryString", out ignored));
                    Assert.Equal("QueryString", (string)env["owin.RequestQueryString"]);

                    Assert.True(env.TryGetValue("owin.RequestScheme", out ignored));
                    Assert.Equal("http", (string)env["owin.RequestScheme"]);

                    Assert.True(env.TryGetValue("owin.Version", out ignored));
                    Assert.Equal("1.0", (string)env["owin.Version"]);

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString");
            request.Content = new StringContent("Hello World");
            request.Version = new Version(1, 0);
            await SendRequest(listener, request);
        }

        [Fact]
        public async Task Headers_EmptyGetRequest_RequiredHeadersPresentAndCorrect()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");

                    string[] values;
                    Assert.True(requestHeaders.TryGetValue("host", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("localhost:8080", values[0]);

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            await SendGetRequest(listener, HttpClientAddress);
        }

        [Fact]
        public async Task Headers_PostContentLengthRequest_RequiredHeadersPresentAndCorrect()
        {
            string requestBody = "Hello World";

            OwinHttpListener listener = CreateServer(
                env =>
                {
                    var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");

                    string[] values;

                    Assert.True(requestHeaders.TryGetValue("host", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("localhost:8080", values[0]);

                    Assert.True(requestHeaders.TryGetValue("Content-length", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal(requestBody.Length.ToString(), values[0]);

                    Assert.True(requestHeaders.TryGetValue("exPect", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("100-continue", values[0]);

                    Assert.True(requestHeaders.TryGetValue("Content-Type", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("text/plain; charset=utf-8", values[0]);

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString");
            request.Content = new StringContent(requestBody);
            await SendRequest(listener, request);
        }

        [Fact]
        public async Task Headers_PostChunkedRequest_RequiredHeadersPresentAndCorrect()
        {
            string requestBody = "Hello World";

            OwinHttpListener listener = CreateServer(
                env =>
                {
                    var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");

                    string[] values;

                    Assert.True(requestHeaders.TryGetValue("host", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("localhost:8080", values[0]);

                    Assert.True(requestHeaders.TryGetValue("Transfer-encoding", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("chunked", values[0]);

                    Assert.True(requestHeaders.TryGetValue("exPect", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("100-continue", values[0]);

                    Assert.True(requestHeaders.TryGetValue("Content-Type", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("text/plain; charset=utf-8", values[0]);

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString");
            request.Headers.TransferEncodingChunked = true;
            request.Content = new StringContent(requestBody);
            await SendRequest(listener, request);
        }

        [Fact]
        public async Task Body_PostContentLengthZero_NullStream()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    string[] values;
                    var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");

                    Assert.True(requestHeaders.TryGetValue("Content-length", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("0", values[0]);

                    Assert.NotNull(env.Get<Stream>("owin.RequestBody"));

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
            request.Content = new StringContent(string.Empty);
            await SendRequest(listener, request);
        }

        [Fact]
        public async Task Body_PostContentLengthX_StreamWithXBytes()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    string[] values;
                    var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");

                    Assert.True(requestHeaders.TryGetValue("Content-length", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("11", values[0]);

                    var requestBody = env.Get<Stream>("owin.RequestBody");
                    Assert.NotNull(requestBody);

                    var buffer = new MemoryStream();
                    requestBody.CopyTo(buffer);
                    Assert.Equal(11, buffer.Length);

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
            request.Content = new StringContent("Hello World");
            await SendRequest(listener, request);
        }

        [Fact]
        public async Task Body_PostChunkedEmpty_StreamWithZeroBytes()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    string[] values;
                    var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");

                    Assert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("chunked", values[0]);

                    var requestBody = env.Get<Stream>("owin.RequestBody");
                    Assert.NotNull(requestBody);

                    var buffer = new MemoryStream();
                    requestBody.CopyTo(buffer);
                    Assert.Equal(0, buffer.Length);

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
            request.Headers.TransferEncodingChunked = true;
            request.Content = new StringContent(string.Empty);
            await SendRequest(listener, request);
        }

        [Fact]
        public async Task Body_PostChunkedX_StreamWithXBytes()
        {
            OwinHttpListener listener = CreateServer(
                env =>
                {
                    string[] values;
                    var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");

                    Assert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values));
                    Assert.Equal(1, values.Length);
                    Assert.Equal("chunked", values[0]);

                    var requestBody = env.Get<Stream>("owin.RequestBody");
                    Assert.NotNull(requestBody);

                    var buffer = new MemoryStream();
                    requestBody.CopyTo(buffer);
                    Assert.Equal(11, buffer.Length);

                    return TaskHelpers.Completed();
                },
                HttpServerAddress);

            var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
            request.Headers.TransferEncodingChunked = true;
            request.Content = new StringContent("Hello World");
            await SendRequest(listener, request);
        }

        private OwinHttpListener CreateServer(AppFunc app, string[] addressParts)
        {
            var wrapper = new OwinHttpListener();
            wrapper.Start(wrapper.Listener, app, CreateAddress(addressParts), null, null);
            return wrapper;
        }

        private static IList<IDictionary<string, object>> CreateAddress(string[] addressParts)
        {
            var address = new Dictionary<string, object>();
            address["scheme"] = addressParts[0];
            address["host"] = addressParts[1];
            address["port"] = addressParts[2];
            address["path"] = addressParts[3];

            IList<IDictionary<string, object>> list = new List<IDictionary<string, object>>();
            list.Add(address);
            return list;
        }

        private async Task SendGetRequest(OwinHttpListener listener, string address)
        {
            using (listener)
            {
                var client = new HttpClient();
                string result = await client.GetStringAsync(address);
            }
        }

        private async Task SendRequest(OwinHttpListener listener, HttpRequestMessage request)
        {
            using (listener)
            {
                var client = new HttpClient();
                HttpResponseMessage result = await client.SendAsync(request);
                result.EnsureSuccessStatusCode();
            }
        }
    }
}


text:
set -e

# The root directory for the git-lfs repository
ROOTDIR=$(cd $(dirname "$0")/.. && pwd)

# Where Git LFS outputs the compiled binaries
BINPATH="$ROOTDIR/bin"

# Put bin path on PATH
PATH="$BINPATH:$PATH"

# create a temporary work space
TMPDIR=${GIT_LFS_TEST_DIR:-"$(cd $(dirname "$0")/.. && pwd)/tmp"}

# This is unique to every test file, and cleared after every test run.
TRASHDIR="$TMPDIR/$(basename "$0")-$$"

# The directory that the test Git server works from.  This cleared at the
# beginning of every test run.
REMOTEDIR="$ROOTDIR/test/remote"

# This is the prefix for Git config files.  See the "Test Suite" section in
# test/README.md
LFS_CONFIG="$REMOTEDIR/config"

# This file contains the URL of the test Git server. See the "Test Suite"
# section in test/README.md
LFS_URL_FILE="$REMOTEDIR/url"

HOME="$REMOTEDIR/home"
GIT_CONFIG_NOSYSTEM=1

mkdir -p "$TRASHDIR"

. "test/testhelpers.sh"


text:
package ssh

import (
	"os"
	"os/user"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"unicode/utf8"

	"github.com/mutagen-io/mutagen/pkg/filesystem"
)

func TestCopy(t *testing.T) {
	// If localhost SSH support isn't available, then skip this test.
	if os.Getenv("MUTAGEN_TEST_SSH") != "true" {
		t.Skip()
	}

	// Compute source path.
	source := filepath.Join(t.TempDir(), "source")

	// Create contents.
	contents := []byte{0, 1, 2, 3, 4, 5, 6}

	// Attempt to write to a temporary file.
	if err := filesystem.WriteFileAtomic(source, contents, 0600); err != nil {
		t.Fatal("atomic file write failed:", err)
	}

	// Grab our username.
	user, err := user.Current()
	if err != nil {
		t.Fatal("unable to query user data:", err)
	}

	// Create a transport.
	transport := &sshTransport{
		user: user.Username,
		host: "localhost",
		port: 22,
	}

	// Compute the destination path.
	// HACK: Technically agent.Transport implementations only need to support
	// remote destination paths that are file names relative to the home
	// directory. For testing, however, we don't want to copy into the home
	// directory, and since we know our Copy implementation can support
	// arbitrary remote paths, we use one.
	destination := filepath.Join(t.TempDir(), "destination")

	// Copy the file.
	if err := transport.Copy(source, destination); err != nil {
		t.Fatal("unable to copy file:", err)
	}

	// Verify that the file exists.
	if _, err := os.Lstat(destination); err != nil {
		t.Error("unable to verify that destination exists")
	}
}

func TestCommandOutput(t *testing.T) {
	// If localhost SSH support isn't available, then skip this test.
	if os.Getenv("MUTAGEN_TEST_SSH") != "true" {
		t.Skip()
	}

	// Compute a command to run.
	command := "env"
	if runtime.GOOS == "windows" {
		command = "cmd /c set"
	}

	// Compute expected output content.
	content := "HOME="
	if runtime.GOOS == "windows" {
		content = "PROCESSOR_ARCHITECTURE="
	}

	// Grab our username.
	user, err := user.Current()
	if err != nil {
		t.Fatal("unable to query user data:", err)
	}

	// Create a transport.
	transport := &sshTransport{
		user: user.Username,
		host: "localhost",
		port: 22,
	}

	// Attempt to execute the command.
	// TODO: Should we also verify that an extracted HOME/USERPROFILE value
	// matches the expected home directory since we've already queried the user?
	if command, err := transport.Command(command); err != nil {
		t.Fatal("unable to create command:", err)
	} else if output, err := command.Output(); err != nil {
		t.Fatal("unable to run command:", err)
	} else if !strings.Contains(string(output), content) {
		t.Error("output does not contain expected content")
	} else if !utf8.Valid(output) {
		t.Error("output not in UTF-8 encoding")
	}
}


text:
using D360.Types;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace D360
{
    public class MouseMove
    {
        public CommandTarget commandTarget;
        public MouseMoveType moveType;
        public UIntVector moveScale;
    }
}


text:
<!DOCTYPE html>

  	<meta charset="utf-8">
  	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>histogram</title>


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#ifndef EIGEN_TRIANGULAR_SOLVER_MATRIX_H
#define EIGEN_TRIANGULAR_SOLVER_MATRIX_H

namespace internal {

// if the rhs is row major, let's transpose the product
template <typename Scalar, typename Index, int Side, int Mode, bool Conjugate, int TriStorageOrder>
struct triangular_solve_matrix<Scalar,Index,Side,Mode,Conjugate,TriStorageOrder,RowMajor>
{
  static EIGEN_DONT_INLINE void run(
    Index size, Index cols,
    const Scalar*  tri, Index triStride,
    Scalar* _other, Index otherStride)
  {
    triangular_solve_matrix<
      Scalar, Index, Side==OnTheLeft?OnTheRight:OnTheLeft,
      (Mode&UnitDiag) | ((Mode&Upper) ? Lower : Upper),
      NumTraits<Scalar>::IsComplex && Conjugate,
      TriStorageOrder==RowMajor ? ColMajor : RowMajor, ColMajor>
      ::run(size, cols, tri, triStride, _other, otherStride);
  }
};

/* Optimized triangular solver with multiple right hand side and the triangular matrix on the left
 */
template <typename Scalar, typename Index, int Mode, bool Conjugate, int TriStorageOrder>
struct triangular_solve_matrix<Scalar,Index,OnTheLeft,Mode,Conjugate,TriStorageOrder,ColMajor>
{
  static EIGEN_DONT_INLINE void run(
    Index size, Index otherSize,
    const Scalar* _tri, Index triStride,
    Scalar* _other, Index otherStride)
  {
    Index cols = otherSize;
    const_blas_data_mapper<Scalar, Index, TriStorageOrder> tri(_tri,triStride);
    blas_data_mapper<Scalar, Index, ColMajor> other(_other,otherStride);

    typedef gebp_traits<Scalar,Scalar> Traits;
    enum {
      SmallPanelWidth   = EIGEN_PLAIN_ENUM_MAX(Traits::mr,Traits::nr),
      IsLower = (Mode&Lower) == Lower
    };

    Index kc = size; // cache block size along the K direction
    Index mc = size;  // cache block size along the M direction
    Index nc = cols;  // cache block size along the N direction
    computeProductBlockingSizes<Scalar,Scalar,4>(kc, mc, nc);

    std::size_t sizeW = kc*Traits::WorkSpaceFactor;
    std::size_t sizeB = sizeW + kc*cols;
    ei_declare_aligned_stack_constructed_variable(Scalar, blockA, kc*mc, 0);
    ei_declare_aligned_stack_constructed_variable(Scalar, allocatedBlockB, sizeB, 0);
    Scalar* blockB = allocatedBlockB + sizeW;

    conj_if<Conjugate> conj;
    gebp_kernel<Scalar, Scalar, Index, Traits::mr, Traits::nr, Conjugate, false> gebp_kernel;
    gemm_pack_lhs<Scalar, Index, Traits::mr, Traits::LhsProgress, TriStorageOrder> pack_lhs;
    gemm_pack_rhs<Scalar, Index, Traits::nr, ColMajor, false, true> pack_rhs;

    for(Index k2=IsLower ? 0 : size;
        IsLower ? k2<size : k2>0;
        IsLower ? k2+=kc : k2-=kc)
    {
      const Index actual_kc = std::min(IsLower ? size-k2 : k2, kc);

      // We have selected and packed a big horizontal panel R1 of rhs. Let B be the packed copy of this panel,
      // and R2 the remaining part of rhs. The corresponding vertical panel of lhs is split into
      // A11 (the triangular part) and A21 the remaining rectangular part.
      // Then the high level algorithm is:
      //  - B = R1                    => general block copy (done during the next step)
      //  - R1 = L1^-1 B              => tricky part
      //  - update B from the new R1  => actually this has to be performed continuously during the above step
      //  - R2 = L2 * B               => GEPP

      // The tricky part: compute R1 = L1^-1 B while updating B from R1
      // The idea is to split L1 into multiple small vertical panels.
      // Each panel can be split into a small triangular part A1 which is processed without optimization,
      // and the remaining small part A2 which is processed using gebp with appropriate block strides
      {
        // for each small vertical panels of lhs
        for (Index k1=0; k1<actual_kc; k1+=SmallPanelWidth)
        {
          Index actualPanelWidth = std::min<Index>(actual_kc-k1, SmallPanelWidth);
          // tr solve
          for (Index k=0; k<actualPanelWidth; ++k)
          {
            // TODO write a small kernel handling this (can be shared with trsv)
            Index i  = IsLower ? k2+k1+k : k2-k1-k-1;
            Index s  = IsLower ? k2+k1 : i+1;
            Index rs = actualPanelWidth - k - 1; // remaining size

            Scalar a = (Mode & UnitDiag) ? Scalar(1) : Scalar(1)/conj(tri(i,i));
            for (Index j=0; j<cols; ++j)
            {
              if (TriStorageOrder==RowMajor)
              {
                Scalar b = 0;
                const Scalar* l = &tri(i,s);
                Scalar* r = &other(s,j);
                for (Index i3=0; i3<k; ++i3)
                  b += conj(l[i3]) * r[i3];

                other(i,j) = (other(i,j) - b)*a;
              }
              else
              {
                Index s = IsLower ? i+1 : i-rs;
                Scalar b = (other(i,j) *= a);
                Scalar* r = &other(s,j);
                const Scalar* l = &tri(s,i);
                for (Index i3=0;i3<rs;++i3)
                  r[i3] -= b * conj(l[i3]);
              }
            }
          }

          Index lengthTarget = actual_kc-k1-actualPanelWidth;
          Index startBlock   = IsLower ? k2+k1 : k2-k1-actualPanelWidth;
          Index blockBOffset = IsLower ? k1 : lengthTarget;

          // update the respective rows of B from other
          pack_rhs(blockB, _other+startBlock, otherStride, actualPanelWidth, cols, actual_kc, blockBOffset);

          // GEBP
          if (lengthTarget>0)
          {
            Index startTarget  = IsLower ? k2+k1+actualPanelWidth : k2-actual_kc;

            pack_lhs(blockA, &tri(startTarget,startBlock), triStride, actualPanelWidth, lengthTarget);

            gebp_kernel(_other+startTarget, otherStride, blockA, blockB, lengthTarget, actualPanelWidth, cols, Scalar(-1),
                        actualPanelWidth, actual_kc, 0, blockBOffset);
          }
        }
      }

      // R2 = A2 * B => GEPP
      {
        Index start = IsLower ? k2+kc : 0;
        Index end   = IsLower ? size : k2-kc;
        for(Index i2=start; i2<end; i2+=mc)
        {
          const Index actual_mc = std::min(mc,end-i2);
          if (actual_mc>0)
          {
            pack_lhs(blockA, &tri(i2, IsLower ? k2 : k2-kc), triStride, actual_kc, actual_mc);

            gebp_kernel(_other+i2, otherStride, blockA, blockB, actual_mc, actual_kc, cols, Scalar(-1));
          }
        }
      }
    }
  }
};

/* Optimized triangular solver with multiple left hand sides and the trinagular matrix on the right
 */
template <typename Scalar, typename Index, int Mode, bool Conjugate, int TriStorageOrder>
struct triangular_solve_matrix<Scalar,Index,OnTheRight,Mode,Conjugate,TriStorageOrder,ColMajor>
{
  static EIGEN_DONT_INLINE void run(
    Index size, Index otherSize,
    const Scalar* _tri, Index triStride,
    Scalar* _other, Index otherStride)
  {
    Index rows = otherSize;
    const_blas_data_mapper<Scalar, Index, TriStorageOrder> rhs(_tri,triStride);
    blas_data_mapper<Scalar, Index, ColMajor> lhs(_other,otherStride);

    typedef gebp_traits<Scalar,Scalar> Traits;
    enum {
      RhsStorageOrder   = TriStorageOrder,
      SmallPanelWidth   = EIGEN_PLAIN_ENUM_MAX(Traits::mr,Traits::nr),
      IsLower = (Mode&Lower) == Lower
    };

//     Index kc = std::min<Index>(Traits::Max_kc/4,size); // cache block size along the K direction
//     Index mc = std::min<Index>(Traits::Max_mc,size);   // cache block size along the M direction
    // check that !!!!
    Index kc = size; // cache block size along the K direction
    Index mc = size;  // cache block size along the M direction
    Index nc = rows;  // cache block size along the N direction
    computeProductBlockingSizes<Scalar,Scalar,4>(kc, mc, nc);

    std::size_t sizeW = kc*Traits::WorkSpaceFactor;
    std::size_t sizeB = sizeW + kc*size;
    ei_declare_aligned_stack_constructed_variable(Scalar, blockA, kc*mc, 0);
    ei_declare_aligned_stack_constructed_variable(Scalar, allocatedBlockB, sizeB, 0);
    Scalar* blockB = allocatedBlockB + sizeW;

    conj_if<Conjugate> conj;
    gebp_kernel<Scalar,Scalar, Index, Traits::mr, Traits::nr, false, Conjugate> gebp_kernel;
    gemm_pack_rhs<Scalar, Index, Traits::nr,RhsStorageOrder> pack_rhs;
    gemm_pack_rhs<Scalar, Index, Traits::nr,RhsStorageOrder,false,true> pack_rhs_panel;
    gemm_pack_lhs<Scalar, Index, Traits::mr, Traits::LhsProgress, ColMajor, false, true> pack_lhs_panel;

    for(Index k2=IsLower ? size : 0;
        IsLower ? k2>0 : k2<size;
        IsLower ? k2-=kc : k2+=kc)
    {
      const Index actual_kc = std::min(IsLower ? k2 : size-k2, kc);
      Index actual_k2 = IsLower ? k2-actual_kc : k2 ;

      Index startPanel = IsLower ? 0 : k2+actual_kc;
      Index rs = IsLower ? actual_k2 : size - actual_k2 - actual_kc;
      Scalar* geb = blockB+actual_kc*actual_kc;

      if (rs>0) pack_rhs(geb, &rhs(actual_k2,startPanel), triStride, actual_kc, rs);

      // triangular packing (we only pack the panels off the diagonal,
      // neglecting the blocks overlapping the diagonal
      {
        for (Index j2=0; j2<actual_kc; j2+=SmallPanelWidth)
        {
          Index actualPanelWidth = std::min<Index>(actual_kc-j2, SmallPanelWidth);
          Index actual_j2 = actual_k2 + j2;
          Index panelOffset = IsLower ? j2+actualPanelWidth : 0;
          Index panelLength = IsLower ? actual_kc-j2-actualPanelWidth : j2;

          if (panelLength>0)
          pack_rhs_panel(blockB+j2*actual_kc,
                         &rhs(actual_k2+panelOffset, actual_j2), triStride,
                         panelLength, actualPanelWidth,
                         actual_kc, panelOffset);
        }
      }

      for(Index i2=0; i2<rows; i2+=mc)
      {
        const Index actual_mc = std::min(mc,rows-i2);

        // triangular solver kernel
        {
          // for each small block of the diagonal (=> vertical panels of rhs)
          for (Index j2 = IsLower
                      ? (actual_kc - ((actual_kc%SmallPanelWidth) ? Index(actual_kc%SmallPanelWidth)
                                                                  : Index(SmallPanelWidth)))
                      : 0;
               IsLower ? j2>=0 : j2<actual_kc;
               IsLower ? j2-=SmallPanelWidth : j2+=SmallPanelWidth)
          {
            Index actualPanelWidth = std::min<Index>(actual_kc-j2, SmallPanelWidth);
            Index absolute_j2 = actual_k2 + j2;
            Index panelOffset = IsLower ? j2+actualPanelWidth : 0;
            Index panelLength = IsLower ? actual_kc - j2 - actualPanelWidth : j2;

            // GEBP
            if(panelLength>0)
            {
              gebp_kernel(&lhs(i2,absolute_j2), otherStride,
                          blockA, blockB+j2*actual_kc,
                          actual_mc, panelLength, actualPanelWidth,
                          Scalar(-1),
                          actual_kc, actual_kc, // strides
                          panelOffset, panelOffset, // offsets
                          allocatedBlockB);  // workspace
            }

            // unblocked triangular solve
            for (Index k=0; k<actualPanelWidth; ++k)
            {
              Index j = IsLower ? absolute_j2+actualPanelWidth-k-1 : absolute_j2+k;

              Scalar* r = &lhs(i2,j);
              for (Index k3=0; k3<k; ++k3)
              {
                Scalar b = conj(rhs(IsLower ? j+1+k3 : absolute_j2+k3,j));
                Scalar* a = &lhs(i2,IsLower ? j+1+k3 : absolute_j2+k3);
                for (Index i=0; i<actual_mc; ++i)
                  r[i] -= a[i] * b;
              }
              Scalar b = (Mode & UnitDiag) ? Scalar(1) : Scalar(1)/conj(rhs(j,j));
              for (Index i=0; i<actual_mc; ++i)
                r[i] *= b;
            }

            // pack the just computed part of lhs to A
            pack_lhs_panel(blockA, _other+absolute_j2*otherStride+i2, otherStride,
                           actualPanelWidth, actual_mc,
                           actual_kc, j2);
          }
        }

        if (rs>0)
          gebp_kernel(_other+i2+startPanel*otherStride, otherStride, blockA, geb,
                      actual_mc, actual_kc, rs, Scalar(-1),
                      -1, -1, 0, 0, allocatedBlockB);
      }
    }
  }
};

} // end namespace internal

#endif // EIGEN_TRIANGULAR_SOLVER_MATRIX_H


text:
require File.expand_path(File.dirname(__FILE__) + '../../../../test/test_helper')

class ActiveSupport::TestCase
  def simplify_on!(user)
    user.pref.simplify = true
    user.pref.save!
  end

  def simplify_off!(user)
    user.pref.simplify = false
    user.pref.save!
  end
end


text: import './Bubble.test';


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2013, Rogue.IO
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <!--
      AppEngine uses the Apache EL implementation that does not resolve properties from Annotations
      The below parameter, forces the use of a particular EL implementation
      -->
    <context-param>
        <param-name>com.sun.faces.expressionFactory</param-name>
        <param-value>com.sun.el.ExpressionFactoryImpl</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>server</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Production</param-value>
        <!--param-value>Development</param-value-->
    </context-param>
    <context-param>
        <param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
        <param-value>true</param-value>
    </context-param>
    <!-- Disable use of threading for single-threaded environments such as the Google AppEngine. -->
    <context-param>
        <description>
            When enabled, the runtime initialization and default ResourceHandler
            implementation will use threads to perform their functions. Set this
            value to false if threads aren't desired (as in the case of running
            within the Google Application Engine).

            Note that when this option is disabled, the ResourceHandler will not
            pick up new versions of resources when ProjectStage is development.
        </description>
        <param-name>com.sun.faces.enableThreading</param-name>
        <param-value>false</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>
    <context-param>
        <param-name>primefaces.UPLOADER</param-name>
        <param-value>commons</param-value>
    </context-param>
    <listener>
        <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
    </listener>

    <filter>
        <filter-name>FwkSupportFilter</filter-name>
        <filter-class>rogue.app.framework.support.appengine.servlet.FrameworkSupportFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FwkSupportFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    </servlet>
    <servlet>
        <display-name>SessionCleaner</display-name>
        <servlet-name>SessionCleaner</servlet-name>
        <servlet-class>rogue.app.framework.support.appengine.servlet.SessionCleaner</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <!-- Mappings for the system tasks -->
    <!-- If you update the URLs here, then you will need to update them in the code as well -->
    <servlet-mapping>
        <servlet-name>SessionCleaner</servlet-name>
        <url-pattern>/tasks/sessionCleaner</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>

    <error-page>
        <error-code>404</error-code>
        <location>/system/404.xhtml</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/system/500.xhtml</location>
    </error-page>

    <mime-mapping>
        <extension>ttf</extension>
        <mime-type>font/ttf</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>eot</extension>
        <mime-type>font/eot</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>otf</extension>
        <mime-type>font/otf</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>woff</extension>
        <mime-type>font/woff</mime-type>
    </mime-mapping>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>System Tasks</web-resource-name>
            <url-pattern>/tasks/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
</web-app>


text:
package org.apache.activemq.artemis.tests.smoke.quorum;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.activemq.artemis.utils.ThreadLeakCheckRule;
import org.apache.curator.test.InstanceSpec;
import org.apache.curator.test.TestingCluster;
import org.apache.curator.test.TestingZooKeeperServer;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;

public class ZookeeperPluggableQuorumSinglePairTest extends PluggableQuorumSinglePairTest {

   private static final Logger LOGGER = Logger.getLogger(ZookeeperPluggableQuorumSinglePairTest.class);
   private static final int BASE_SERVER_PORT = 6666;
   // Beware: the server tick must be small enough that to let the session to be correctly expired
   private static final int SERVER_TICK_MS = 100;

   private TestingCluster testingServer;
   private InstanceSpec[] clusterSpecs;
   private int nodes;

   @Before
   @Override
   public void setup() throws Exception {
      super.setup();
      nodes = 3;
      clusterSpecs = new InstanceSpec[nodes];
      for (int i = 0; i < nodes; i++) {
         clusterSpecs[i] = new InstanceSpec(temporaryFolder.newFolder(), BASE_SERVER_PORT + i, -1, -1, true, -1, SERVER_TICK_MS, -1);
      }
      testingServer = new TestingCluster(clusterSpecs);
      testingServer.start();
      Assert.assertEquals("127.0.0.1:6666,127.0.0.1:6667,127.0.0.1:6668", testingServer.getConnectString());
      LOGGER.infof("Cluster of %d nodes on: %s", 3, testingServer.getConnectString());
   }

   @Override
   @After
   public void after() throws Exception {
      // zk bits that leak from servers
      ThreadLeakCheckRule.addKownThread("ListenerHandler-");
      try {
         super.after();
      } finally {
         testingServer.close();
      }
   }

   public ZookeeperPluggableQuorumSinglePairTest() {
      super("zk");
   }

   @Override
   protected boolean awaitAsyncSetupCompleted(long timeout, TimeUnit unit) {
      return true;
   }

   protected boolean ensembleHasLeader() {
      return testingServer.getServers().stream().filter(ZookeeperPluggableQuorumSinglePairTest::isLeader).count() != 0;
   }

   private static boolean isLeader(TestingZooKeeperServer server) {
      long leaderId = server.getQuorumPeer().getLeaderId();
      long id = server.getQuorumPeer().getId();
      return id == leaderId;
   }

   @Override
   protected int[] stopMajority() throws Exception {
      List<TestingZooKeeperServer> followers = testingServer.getServers();
      final int quorum = (nodes / 2) + 1;
      final int[] stopped = new int[quorum];
      for (int i = 0; i < quorum; i++) {
         followers.get(i).stop();
         stopped[i] = i;
      }
      return stopped;
   }

   @Override
   protected void restart(int[] nodes) throws Exception {
      List<TestingZooKeeperServer> servers = testingServer.getServers();
      for (int nodeIndex : nodes) {
         servers.get(nodeIndex).restart();
      }
   }
}


text:
using extensions::Extension;
using extensions::WebAccessibleResourcesInfo;

class WebAccessibleResourcesManifestTest : public ExtensionManifestTest {
};

TEST_F(WebAccessibleResourcesManifestTest, WebAccessibleResources) {
  // Manifest version 2 with web accessible resources specified.
  scoped_refptr<Extension> extension1(
      LoadAndExpectSuccess("web_accessible_resources_1.json"));

  // Manifest version 2 with no web accessible resources.
  scoped_refptr<Extension> extension2(
      LoadAndExpectSuccess("web_accessible_resources_2.json"));

  // Default manifest version with web accessible resources specified.
  scoped_refptr<Extension> extension3(
      LoadAndExpectSuccess("web_accessible_resources_3.json"));

  // Default manifest version with no web accessible resources.
  scoped_refptr<Extension> extension4(
      LoadAndExpectSuccess("web_accessible_resources_4.json"));

  // Default manifest version with wildcard web accessible resource.
  scoped_refptr<Extension> extension5(
      LoadAndExpectSuccess("web_accessible_resources_5.json"));

  // Default manifest version with wildcard with specific path and extension.
  scoped_refptr<Extension> extension6(
      LoadAndExpectSuccess("web_accessible_resources_6.json"));

  EXPECT_TRUE(
      WebAccessibleResourcesInfo::HasWebAccessibleResources(extension1.get()));
  EXPECT_FALSE(
      WebAccessibleResourcesInfo::HasWebAccessibleResources(extension2.get()));
  EXPECT_TRUE(
      WebAccessibleResourcesInfo::HasWebAccessibleResources(extension3.get()));
  EXPECT_FALSE(
      WebAccessibleResourcesInfo::HasWebAccessibleResources(extension4.get()));
  EXPECT_TRUE(
      WebAccessibleResourcesInfo::HasWebAccessibleResources(extension5.get()));
  EXPECT_TRUE(
      WebAccessibleResourcesInfo::HasWebAccessibleResources(extension6.get()));

  EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension1.get(), "test"));
  EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension1.get(), "none"));

  EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension2.get(), "test"));

  EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension3.get(), "test"));
  EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension3.get(), "none"));

  EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension4.get(), "test"));
  EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension4.get(), "none"));

  EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension5.get(), "anything"));
  EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension5.get(), "path/anything"));

  EXPECT_TRUE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension6.get(), "path/anything.ext"));
  EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension6.get(), "anything.ext"));
  EXPECT_FALSE(WebAccessibleResourcesInfo::IsResourceWebAccessible(
      extension6.get(), "path/anything.badext"));
}


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements;
 * and to You under the Apache License, Version 2.0.
 */
package ch.sbb.releasetrain.config;

import ch.sbb.releasetrain.config.model.email.MailReceiver;
import ch.sbb.releasetrain.config.model.releaseconfig.ActionConfig;
import ch.sbb.releasetrain.config.model.releaseconfig.JenkinsActionConfig;
import ch.sbb.releasetrain.config.model.releaseconfig.ReleaseConfig;
import ch.sbb.releasetrain.utils.yaml.YamlModelAccessor;

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

import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

/**
 * Test
 *
 * @author u203244 (Daniel Marthaler)
 * @since 0.0.1, 2016
 */
public class YamlSerializerTest {

	@Rule
	public TemporaryFolder testFolder = new TemporaryFolder();

	private YamlModelAccessor<ReleaseConfig> configSerializer = new YamlModelAccessor<>();
	private YamlModelAccessor<MailReceiver> emailSerializer = new YamlModelAccessor<>();

	@Test
	public void testSerializeActionConfig() throws Exception {

		ReleaseConfig release = new ReleaseConfig();
		ActionConfig action = new JenkinsActionConfig();
		action.getProperties().put("myProp1", "Hallo Welt1");
		action.getProperties().put("myProp2", "Hallo Welt2");

		ActionConfig action2 = new JenkinsActionConfig();
		action2.getProperties().put("myProp2", "Hallo asxasxsxWelt");

		release.setTyp("demo-release");
		release.getActions().add(action);
		release.getActions().add(action2);

		File file = new File(testFolder.getRoot(), "action.yml");
		FileUtils.writeStringToFile(file, configSerializer.convertEntry(release), "UTF-8");

		ReleaseConfig release2 = configSerializer.convertEntry(FileUtils.readFileToString(file, "UTF-8"));
		Assert.assertNotNull(release2);
		Assert.assertEquals(release, release2);

	}

	@Test
	public void testSerializeMailReceiverConfig() throws Exception {

		List<MailReceiver> list = new ArrayList<>();
		list.add(createMailReceiver(1, "test"));
		list.add(createMailReceiver(2, "test"));
		list.add(createMailReceiver(3, "hallo"));
		list.add(createMailReceiver(4, "hallo"));

		File file = new File(testFolder.getRoot(), "mail.yml");
		FileUtils.writeStringToFile(file, emailSerializer.convertEntrys(list));

		List<MailReceiver> list2 = emailSerializer.convertEntrys(FileUtils.readFileToString(file));
		Assert.assertNotNull(list2);
		Assert.assertEquals(list.size(), list2.size());

		Assert.assertEquals(list.get(3), list2.get(3));

	}

	private MailReceiver createMailReceiver(int number, String mailinglist) {
		MailReceiver rec = new MailReceiver();
		rec.setEmail("test" + number + "@test.ch");
		rec.getMailinglist().add(mailinglist);
		rec.getMailinglist().add("default");
		rec.getMailinglist().add("default" + number);
		return rec;
	}
}


text:
DROP TABLE IF EXISTS home;
DROP TABLE IF EXISTS mention;
DROP TABLE IF EXISTS any_user;
DROP TABLE IF EXISTS fixed_query;
DROP TABLE IF EXISTS queryable;
DROP TABLE IF EXISTS any_list;
DROP TABLE IF EXISTS twitter_user;

CREATE TABLE home (
    id INTEGER NOT NULL,
    tweet_content VARCHAR(140) NOT NULL,
    screen_name VARCHAR(100) NOT NULL,
    name VARCHAR(100) NOT NULL,
    created_at INTEGER NOT NULL,
    profile_image_url VARCHAR(500) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE mention (
    id INTEGER NOT NULL,
    tweet_content VARCHAR(140) NOT NULL,
    screen_name VARCHAR(100) NOT NULL,
    name VARCHAR(100) NOT NULL,
    created_at INTEGER NOT NULL,
    profile_image_url VARCHAR(500) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE any_user (
    id INTEGER NOT NULL,
    tweet_content VARCHAR(140) NOT NULL,
    screen_name VARCHAR(100) NOT NULL,
    name VARCHAR(100) NOT NULL,
    created_at INTEGER NOT NULL,
    profile_image_url VARCHAR(500) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE fixed_query (
    id INTEGER NOT NULL,
    tweet_content VARCHAR(140) NOT NULL,
    screen_name VARCHAR(100) NOT NULL,
    name VARCHAR(100) NOT NULL,
    created_at INTEGER NOT NULL,
    profile_image_url VARCHAR(500) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE queryable (
    id INTEGER NOT NULL,
    tweet_content VARCHAR(140) NOT NULL,
    screen_name VARCHAR(100) NOT NULL,
    name VARCHAR(100) NOT NULL,
    created_at INTEGER NOT NULL,
    profile_image_url VARCHAR(500) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE any_list (
    id INTEGER NOT NULL,
    list_id INTEGER NOT NULL,
    tweet_content VARCHAR(140) NOT NULL,
    screen_name VARCHAR(100) NOT NULL,
    name VARCHAR(100) NOT NULL,
    created_at INTEGER NOT NULL,
    profile_image_url VARCHAR(500) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE twitter_user (
	id INTEGER NOT NULL,
	name VARCHAR(100) NOT NULL,
	screen_name VARCHAR(100) NOT NULL,
    profile_image_url VARCHAR(500) NOT NULL,
    profile_banner_url VARCHAR(500) NULL,
    url VARCHAR(500) NULL,
    description VARCHAR(140) NULL,
    location VARCHAR(200) NULL,
    PRIMARY KEY (id),
    UNIQUE (screen_name)
);

CREATE INDEX home_created_at_idx ON home (created_at DESC);
CREATE INDEX mention_created_at_idx ON mention (created_at DESC);
CREATE INDEX fixed_query_created_at_idx ON fixed_query (created_at DESC);
CREATE INDEX any_user_created_at_idx ON any_user (created_at DESC);
CREATE INDEX queryable_created_at_idx ON queryable (created_at DESC);
CREATE INDEX any_list_created_at_idx ON any_list (created_at DESC);


text:
package org.apache.pulsar.common.policies.data;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;

public class BookiesRackConfiguration extends TreeMap<String, Map<String, BookieInfo>> {

    public boolean removeBookie(String address) {
        for (Map<String, BookieInfo> m : values()) {
            if (m.remove(address) != null ) {
                return true;
            }
        }

        return false;
    }

    public Optional<BookieInfo> getBookie(String address) {
        for (Map<String, BookieInfo> m : values()) {
            BookieInfo bi = m.get(address);
            if (bi != null) {
                return Optional.of(bi);
            }
        }
        return Optional.empty();
    }

    public void updateBookie(String group, String address, BookieInfo bookieInfo) {
        checkNotNull(group);
        checkNotNull(address);
        checkNotNull(bookieInfo);

        // Remove from any group first
        removeBookie(address);
        computeIfAbsent(group, key -> new TreeMap<>()).put(address, bookieInfo);
    }
}


text:
package com.microsoft.azure.management.apimanagement.v2018_06_01_preview;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;

/**
 * Email Template update Parameters.
 */
@JsonFlatten
public class EmailTemplateUpdateParameters {
    /**
     * Subject of the Template.
     */
    @JsonProperty(value = "properties.subject")
    private String subject;

    /**
     * Title of the Template.
     */
    @JsonProperty(value = "properties.title")
    private String title;

    /**
     * Description of the Email Template.
     */
    @JsonProperty(value = "properties.description")
    private String description;

    /**
     * Email Template Body. This should be a valid XDocument.
     */
    @JsonProperty(value = "properties.body")
    private String body;

    /**
     * Email Template Parameter values.
     */
    @JsonProperty(value = "properties.parameters")
    private List<EmailTemplateParametersContractProperties> parameters;

    /**
     * Get subject of the Template.
     *
     * @return the subject value
     */
    public String subject() {
        return this.subject;
    }

    /**
     * Set subject of the Template.
     *
     * @param subject the subject value to set
     * @return the EmailTemplateUpdateParameters object itself.
     */
    public EmailTemplateUpdateParameters withSubject(String subject) {
        this.subject = subject;
        return this;
    }

    /**
     * Get title of the Template.
     *
     * @return the title value
     */
    public String title() {
        return this.title;
    }

    /**
     * Set title of the Template.
     *
     * @param title the title value to set
     * @return the EmailTemplateUpdateParameters object itself.
     */
    public EmailTemplateUpdateParameters withTitle(String title) {
        this.title = title;
        return this;
    }

    /**
     * Get description of the Email Template.
     *
     * @return the description value
     */
    public String description() {
        return this.description;
    }

    /**
     * Set description of the Email Template.
     *
     * @param description the description value to set
     * @return the EmailTemplateUpdateParameters object itself.
     */
    public EmailTemplateUpdateParameters withDescription(String description) {
        this.description = description;
        return this;
    }

    /**
     * Get email Template Body. This should be a valid XDocument.
     *
     * @return the body value
     */
    public String body() {
        return this.body;
    }

    /**
     * Set email Template Body. This should be a valid XDocument.
     *
     * @param body the body value to set
     * @return the EmailTemplateUpdateParameters object itself.
     */
    public EmailTemplateUpdateParameters withBody(String body) {
        this.body = body;
        return this;
    }

    /**
     * Get email Template Parameter values.
     *
     * @return the parameters value
     */
    public List<EmailTemplateParametersContractProperties> parameters() {
        return this.parameters;
    }

    /**
     * Set email Template Parameter values.
     *
     * @param parameters the parameters value to set
     * @return the EmailTemplateUpdateParameters object itself.
     */
    public EmailTemplateUpdateParameters withParameters(List<EmailTemplateParametersContractProperties> parameters) {
        this.parameters = parameters;
        return this;
    }

}


text:
/* ==========================================================================
   8. Pagination - Tools to let you flick between pages
   ========================================================================== */
/* The main wrapper for our pagination links */
.pagination {
  position: relative;
  width: 80%;
  max-width: 710px;
  margin: 4rem auto;
  font-family: "Open Sans", sans-serif;
  font-size: 1.3rem;
  color: #9EABB3;
  text-align: center; }

.pagination a {
  color: #9EABB3;
  transition: all 0.2s ease; }

/* Push the previous/next links out to the left/right */
.older-posts,
.newer-posts {
  position: absolute;
  display: inline-block;
  padding: 0 15px;
  border: #bfc8cd 1px solid;
  text-decoration: none;
  border-radius: 4px;
  transition: border ease 0.3s; }

.older-posts {
  right: 0; }

.page-number {
  display: inline-block;
  padding: 2px 0;
  min-width: 100px; }

.newer-posts {
  left: 0; }

.older-posts:hover,
.newer-posts:hover {
  color: #889093;
  border-color: #98a0a4; }

.extra-pagination {
  display: none;
  border-bottom: #EBF2F6 1px solid; }

.extra-pagination:after {
  display: block;
  content: "";
  width: 7px;
  height: 7px;
  border: #E7EEF2 1px solid;
  position: absolute;
  bottom: -5px;
  left: 50%;
  margin-left: -5px;
  background: #FFF;
  -webkit-border-radius: 100%;
  -moz-border-radius: 100%;
  border-radius: 100%;
  box-shadow: #FFF 0 0 0 5px; }

.extra-pagination .pagination {
  width: auto; }

/* On page2+ make all the headers smaller */
.archive-template .main-header {
  max-height: 30%; }

/* On page2+ show extra pagination controls at the top of post list */
.archive-template .extra-pagination {
  display: block; }


text:
// Copyright (c) 2015, Alexander Endris
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of RosMockLyn nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System.Collections.Generic;
using System.Linq;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

using RosMockLyn.Core.Interfaces;

namespace RosMockLyn.Core.Preparation
{
    internal sealed class InterfaceExtractor : IInterfaceExtractor
    {
        public IEnumerable<SyntaxTree> Extract(Project project)
        {
            var compilation = project.GetCompilationAsync().Result;

            return compilation.SyntaxTrees.Where(HasInterfaceDeclaration).Where(NotRosMockLyn);
        }

        public IEnumerable<string> GetUsedInterfaceNames(Project project)
        {
            var compilation = project.GetCompilationAsync().Result;

            return compilation.SyntaxTrees.SelectMany(GetUsedInterfaceNames).Distinct();
        }

        private bool NotRosMockLyn(SyntaxTree tree)
        {
            var root = tree.GetRoot();

            var interfaceBlockSyntaxs = from node in root.DescendantNodes().OfType<NamespaceDeclarationSyntax>()
                                        where node.Name.ToString().Contains("RosMockLyn.Mocking")
                                        select node;

            return !interfaceBlockSyntaxs.Any();
        }

        private bool HasInterfaceDeclaration(SyntaxTree tree)
        {
            var root = tree.GetRoot();

            var interfaceBlockSyntaxs = from node in root.DescendantNodes().OfType<InterfaceDeclarationSyntax>() select node;

            return interfaceBlockSyntaxs.Any();
        }

        private IEnumerable<string> GetUsedInterfaceNames(SyntaxTree tree)
        {
            var root = tree.GetRoot();

            return from node in root.DescendantNodes().OfType<TypeArgumentListSyntax>()
                                     where node.Ancestors().OfType<GenericNameSyntax>().Any(x => x.Identifier.ToString() == "For")
                                     select node.Arguments.OfType<IdentifierNameSyntax>().First().Identifier.ToString();
        }
    }
}


text:
<a href="<?php echo site_url("inicio/index") ?>">Inicio

Movimientos: Entradas

Entradas a almacén

                <?php echo form_open("movimientos/registrarEntrada", ["class" => "form-horizontal", "id" => "frmEntradas"]) ?>

Registrar una entada a almacén

                        Almacén

                            <select name="almacen" id="cmbAlmacen" class="select2-element" style="width: 100%;">
                                <option value="0">Seleccione un almacén</option>
                                <?php
                                foreach ($almacenes as $almacen) {
                                    echo '<option value="' . $almacen["id"] . '">' . $almacen["nombre"] . '</option>';
                                }
                                ?>
                            </select>

                                 Debe seleccionar un almacén

                        Producto

                            <select name="producto" id="cmbProducto" class="select2-element" style="width: 100%;">
                                <option value="0">Seleccione un producto</option>
                                <?php
                                foreach ($productos as $producto) {
                                    echo '<option value="' . $producto["id"] . '">' . $producto["nombre"] . '</option>';
                                }
                                ?>
                            </select>

                                 Debe seleccionar un producto

                        Cantidad

                            <input type="number" name="cantidad" id="txtCantidad" class="form-control" min="1" value="1" placeholder="¿Qué cantidad va a entrar al almacén?">

                                 La cantidad mínima es 1

                        Observaciones

                            <textarea name="observaciones"
                                      id="txtObservaciones"
                                      class="form-control"
                                      cols="30"
                                      rows="5"
                                      placeholder="Agrega tus comentarios"></textarea>

                                Guardar

                <?php echo form_close() ?>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Resources</title>
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/skeleton.css">
    <link href='https://fonts.googleapis.com/css?family=Teko:300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/style.css">

Home

About us

Recycle this

Resources

RESOURCES FOR REUSE

Recycling and reuse can help business and individuals save money while decreasing their ecological footprint.  Proper waste disposal can also help the community. Businesses can donate old materials and products to schools, creative art centers, or any number of reuse organizations. This tool can help you find the best way to dispose of waste in the city of Seattle.

          <form id="ziptake">

Find Reuse Resources Near You!

              <input id="zipPut" type="text" name="zip" placeholder="Enter your Zip Code"/>
              <input id ="button1" type="submit" name="submit" value="submit">
          </form>

Home

About us

Recycle this

Resources


text:
from base import Base
import helper

class BoolOp(Base):
    def compile(self):
        return  (' %s ' % self.op).join(self.values)

class BinOp(Base):
    def compile(self):
        return '%s.%s(%s)' % (self.left, self.op, self.right)

class UnaryOp(Base):
    def compile(self):
        return '%s.%s()' % (self.operand, self.op)

class Lambda(Base):
    def compile(self):
        return helper.format(
            '''
            function(%(args)s) {
                return %(body)s;
            }
            ''', self
        )

class IfExp(Base):
    def compile(self):
        condition = self.test.compile()
        ifBody = self.body.compile()
        elseBody = self.orelse.compile()
        return '%s ? %s : %s' % (condition, ifBody, elseBody)

class Dict(Base):
    def compile(self):
        return 'new Dict({%s})' % (', '.join('%s: %s' % (key, value) for (key, value) in zip(self.keys, self.values)))

class Set(Base):
    def compile(self):
        return 'new Set(%s)' % self.elts

#**To-do**
#
# Handle multi-comprehensions:
#
# * `seq1 = ['a', 'b', 'c']`
# * `seq2 = [1, 2, 3]`
# * `[(x, y) for x in seq1 for y in seq2]`
class ListComp(Base):
    def compile(self):
        element = str(self.elt)
        iter = self.generators[0].iter
        isMultiTargeted = hasattr(self.generators[0].target, 'elts') is True
        if isMultiTargeted:
            targets = self.generators[0].target.elts
            numTargets = len(targets)
            for i in range(numTargets):
                mappedTarget = "x[%d]" % i
                element = element.replace(targets[i], mappedTarget)
            return "%s.map(function(x){return %s;})" % (iter, element)
        else:
            target = self.generators[0].target
            return "%s.map(function(%s){return %s;})" % (iter, target, element)

# **Unimplemented**
class SetComp(Base):
    def compile(self):
        pass

class DictComp(Base):
    def compile(self):
        keyElement = str(self.key)
        valueElement = str(self.value.compile())
        iter = self.generators[0].iter
        isMultiTargeted = hasattr(self.generators[0].target, 'elts') is True
        if isMultiTargeted:
            '''
            Multi-target for cases such as:
                print {x: y + x for x, y in [('hello', 5), ('world', 2)]}
                    x, y are the targets
                print {x: y + z for x, y, z in [(5, 2, 7), (8, 9, 4)]}
                    x, y, z are targets
            '''
            targets = self.generators[0].target.elts
            numTargets = len(targets)
            for i in range(numTargets):
                mappedTarget = "x[%d]" % i
                keyElement = keyElement.replace(targets[i], mappedTarget)
                valueElement = valueElement.replace(targets[i], mappedTarget)
            return helper.format(
                '''
                (function(){
                    var obj = {};
                    var translated = %(iter)s.map(function(x){
                        return [%(keyElement)s, %(valueElement)s];
                    });
                    for(var i = 0; i < translated.length; i++){
                        var key = translated[i][0];
                        obj[key] = translated[i][1];
                    }
                    return obj;
                })()
                ''', self
            )
        else:
            '''
            Single target for cases such as:
                k = 4
                print {x: x + k for x in [5, 67, 2]}
                x is the single target
            '''
            target = self.generators[0].target
            return helper.format(
                '''
                (function(){
                    var obj = {};
                    var translated = %(iter)s.map(function(%(target)s){
                        return [%(keyElement)s,%(valueElement)s];
                    });
                    for(var i = 0; i < translated.length; i++){
                        var key = translated[i][0];
                        obj[key] = translated[i][1];
                    }
                    return obj;
                })()
                ''', self
            )

# **Unimplemented**
class GeneratorExpr(Base):
    def compile(self):
        pass

# **Unimplemented**
class Yield(Base):
    def compile(self):
        pass

class Compare(Base):
    def compile(self):
        allComparators = [self.left.compile()]
        allComparators.extend(self.comparators[:])
        leftComparators = allComparators[:-1]
        rightComparators = allComparators[1:]
        return ' && '.join('%s.%s(%s)' % (left, op, right) for (left, op, right) in zip(leftComparators, self.ops, rightComparators))

class Call(Base):
    def compile(self):
        argument = ', '.join(arg for arg in self.args)
        return '%s(%s)' % (self.func, argument)

# **Unimplemented**
class Repr(Base):
    def compile(self):
        pass

class Num(Base):
    def compile(self):
        value = self.n
        # Floats and integers have different meanings for division!
        if ('.' in str(value)):
            return 'new Num(%s)' % value
        else:
            return 'new Int(%s)' % value

class Str(Base):
    def compile(self):
        stringValue = self.s
        if (stringValue.startswith('"')):
            stringValue = "'%s'" % stringValue
        else:
            stringValue = '"%s"' % stringValue
        return 'new Str(%s)' % stringValue

class Attribute(Base):
    def compile(self):
        return "%s.%s" % (self.value, self.attr)

# **Consideration**
#
# ctx, Ellipsis, ExtSlice form of slice
class Subscript(Base):
    def compile(self):
        return '%s.%s' % (self.value, self.slice)

class Name(Base):
    def compile(self):
        # Keywords in Python, such as None, True, and False, are parsed as
        # variables.
        try:
            conversion = {
                'None': 'null',
                'True': 'true',
                'False': 'false'
            }
            self.id = conversion[self.id]
        except KeyError:
            pass

        return '%s' % self.id

class List(Base):
    def compile(self):
        return 'new List([%s])' % ', '.join(self.elts)

class Tuple(Base):
    def compile(self):
        return 'new Tuple([%s])' % ', '.join(self.elts)


text:
var request = require('request');
var streamBuffers = require("stream-buffers");
/**
 * Escape special characters in the given string of html.
 *
 * @param  {String} languageLocale = the target locale language (example : en)
 * @param  {String} word = the word to translate to speech
 * @param  {function({'audio' : String, 'message' : String })} callback = function invoked on translate completed with two
 * arguments : audio data as base64 and success true for translated ok and false otherwise
 */
module.exports = {
  translate: function(languageLocale, word, callback) {
      var url = "http://translate.google.com/translate_tts?tl=" + languageLocale + "&q=" + word;

      var myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer({
          initialSize: (100 * 1024),      // start as 100 kilobytes.
          incrementAmount: (10 * 1024)    // grow by 10 kilobytes each time buffer overflows.
      });

      var r = request(url, function (error, response, buffer) {
        if (!error && response.statusCode == 200) {
            var data = myWritableStreamBuffer.getContents().toString('base64');
            var result = {'audio' : data, 'success' : true };
            callback(result);
         } else {
           var result = {'success' : false, 'error' : error, 'responseCode' : response.statusCode };
           callback(result);
         }
      }).pipe(myWritableStreamBuffer);
  }
};


text:
//  IController.hpp
//  PureMVC_C++
//
//  PureMVC Port to C++ by Tang Khai Phuong <phuong.tang@puremvc.org>
//  PureMVC - Copyright(c) 2006-2011 Futurescale, Inc., Some rights reserved.
//  Your reuse is governed by the Creative Commons Attribution 3.0 License
//

#if !defined(__PUREMVC_INTERFACES_ICONTROLLER_HPP__)
#define __PUREMVC_INTERFACES_ICONTROLLER_HPP__

// STL include
#include <string>
// PureMVC include
#if !defined(__PUREMVC_HPP__)
#define __PUREMVC_INCLUDE__
#include "../PureMVC.hpp"
#endif /* __PUREMVC_HPP__ */

#include "INotification.hpp"
#include "ICommand.hpp"
#include "IAggregate.hpp"

namespace PureMVC
{
    namespace Interfaces
    {
        /**
         * The interface definition for a PureMVC Controller.
         *
         *

         * In PureMVC, an IController implementor
         * follows the 'Command and Controller' strategy, and
         * assumes these responsibilities:
         *

         *
 Remembering which ICommands
         * are intended to handle which INotifications.

         *
 Registering itself as an IObserver with
         * the View for each INotification
         * that it has an ICommand mapping for.

         *
 Creating a new instance of the proper ICommand
         * to handle a given INotification when notified by the View.

         *
 Calling the ICommand's execute
         * method, passing in the INotification.

         *

         *
         * @see Interfaces/INotification.hpp PureMVC::Interfaces::INotification
         * @see Interfaces/INotification.hpp PureMVC::Interfaces::ICommand
         * @see Interfaces/IIterator.hpp PureMVC::Interfaces::IIterator
         * @see Interfaces/IAggregate.hpp PureMVC::Interfaces::IAggregate
         */
        struct PUREMVC_API IController
        {
#if defined(PUREMVC_USES_TR1)
            typedef std::unique_ptr<IAggregate<std::string> > NotificationNames;
#else
            typedef std::auto_ptr<IAggregate<std::string> > NotificationNames;
#endif

            /**
             * Register a particular ICommand class as the handler
             * for a particular INotification.
             *
             * @param notification_name the name of the INotification
             * @param command the command of the ICommand
             */
            virtual void registerCommand(std::string const& notification_name, ICommand* command) = 0;

            /**
             * Execute the ICommand previously registered as the
             * handler for INotifications with the given notification name.
             *
             * @param notification the INotification to execute the associated ICommand for
             */
            virtual void executeCommand(INotification const& notification) = 0;

            /**
             * Retrieve an ICommand instance from the Controller.
             *
             * @param notification_name the name of the INotification
             * @return the ICommand instance previously registered with the given notification.
             */
            virtual ICommand const& retrieveCommand(std::string const& notification_name) const = 0;

            /**
             * Retrieve an ICommand instance from the Controller.
             *
             * @param notification_name the name of the INotification
             * @return the ICommand instance previously registered with the given notification.
             */
            virtual ICommand& retrieveCommand(std::string const& notification_name) = 0;

            /**
             * Remove a previously registered ICommand to INotification mapping.
             *
             * @param notification_name the name of the INotification to remove the ICommand mapping for
             * @return the ICommand that was removed from the Controller
             */
            virtual ICommand* removeCommand(std::string const& notification_name) = 0;

            /**
             * Check if a Command is registered for a given Notification
             *
             * @param notification_name
             * @return whether a Command is currently registered for the given notification_name.
             */
            virtual bool hasCommand(std::string const& notification_name) const = 0;

            /**
             * List all notification name
             *
             * @return the aggregate container of notification_name.
             */
            virtual NotificationNames listNotificationNames(void) const = 0;

            /**
             * Virtual destructor.
             */
            virtual ~IController(void);
        };
    }
}

#endif /* __PUREMVC_INTERFACES_ICONTROLLER_HPP__ */


text:
sample_launch_request:
	curl -H "Content-Type: application/json" -X POST \
		-d @sample_launch_request.json \
		http://localhost:8080/api/v1/alexa/skill

sample_intent_request:
	curl -H "Content-Type: application/json" -X POST \
		-d @sample_intent_request.json \
		http://localhost:8080/api/v1/alexa/skill

sample_session_ended_request:
	curl -H "Content-Type: application/json" -X POST \
		-d @sample_session_ended_request.json \
		http://localhost:8080/api/v1/alexa/skill


text:
namespace wgt
{
class TestMethodsObject
{
	DECLARE_REFLECTED

public:
	void testMethod1();
	std::string testMethod2();
	std::string testMethod3(int parameter);
	std::string testMethod4(const std::string& parameter1, int parameter2);
	std::string testMethod5(std::string& parameter);
	void testMethod6(std::string* parameter);
	int testMethod7(int parameter);
	double testMethod8(double parameter);
	const std::string& testMethod9(const std::string& parameter);
	const std::string* testMethod10(const std::string* parameter);
	std::string& testMethod11(std::string& parameter);
	std::string* testMethod12(std::string* parameter);

private:
	std::string testMethod9Str_;
	std::string testMethod10Str_;
	std::string testMethod11Str_;
	std::string testMethod12Str_;
};
} // end namespace wgt
#endif // TEST_METHODS_OBJECT