text:
package io.rsocket.frame;

import io.netty.buffer.ByteBuf;
import io.rsocket.FrameType;

public class RequestFrameFlyweight {

  private RequestFrameFlyweight() {}

  // relative to start of passed offset
  private static final int INITIAL_REQUEST_N_FIELD_OFFSET =
      FrameHeaderFlyweight.FRAME_HEADER_LENGTH;

  public static int computeFrameLength(
      final FrameType type, final int metadataLength, final int dataLength) {
    int length = FrameHeaderFlyweight.computeFrameHeaderLength(type, metadataLength, dataLength);

    if (type.hasInitialRequestN()) {
      length += Integer.BYTES;
    }

    return length;
  }

  public static int encode(
      final ByteBuf byteBuf,
      final int streamId,
      int flags,
      final FrameType type,
      final int initialRequestN,
      final ByteBuf metadata,
      final ByteBuf data) {
    final int frameLength =
        computeFrameLength(type, metadata.readableBytes(), data.readableBytes());

    int length =
        FrameHeaderFlyweight.encodeFrameHeader(byteBuf, frameLength, flags, type, streamId);

    byteBuf.setInt(INITIAL_REQUEST_N_FIELD_OFFSET, initialRequestN);
    length += Integer.BYTES;

    length += FrameHeaderFlyweight.encodeMetadata(byteBuf, type, length, metadata);
    length += FrameHeaderFlyweight.encodeData(byteBuf, length, data);

    return length;
  }

  public static int encode(
      final ByteBuf byteBuf,
      final int streamId,
      final int flags,
      final FrameType type,
      final ByteBuf metadata,
      final ByteBuf data) {
    if (type.hasInitialRequestN()) {
      throw new AssertionError(type + " must not be encoded without initial request N");
    }
    final int frameLength =
        computeFrameLength(type, metadata.readableBytes(), data.readableBytes());

    int length =
        FrameHeaderFlyweight.encodeFrameHeader(byteBuf, frameLength, flags, type, streamId);

    length += FrameHeaderFlyweight.encodeMetadata(byteBuf, type, length, metadata);
    length += FrameHeaderFlyweight.encodeData(byteBuf, length, data);

    return length;
  }

  public static int initialRequestN(final ByteBuf byteBuf) {
    return byteBuf.getInt(INITIAL_REQUEST_N_FIELD_OFFSET);
  }

  public static int payloadOffset(final FrameType type, final ByteBuf byteBuf) {
    int result = FrameHeaderFlyweight.FRAME_HEADER_LENGTH;

    if (type.hasInitialRequestN()) {
      result += Integer.BYTES;
    }

    return result;
  }
}


text:
@(content: Html)
<!DOCTYPE html>

    <title>prout - pull request deployment monitor</title>
    <link rel="stylesheet" media="screen" href="@routes.Assets.at("lib/bootstrap/css/bootstrap.min.css")" />
    <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
    <link rel="stylesheet" href="@routes.Assets.at("lib/octicons/octicons/octicons.css")">

        prout - is your pull request out?

        @content

GitHub

·

Guardian blogpost

·

gu:who (audit your GitHub org)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;

namespace Reporting.Rdl
{
	///
	/// ColumnGroupings definition and processing.
	///
	[Serializable]
	internal class ColumnGroupings : ReportLink
	{
        List<ColumnGrouping> _Items;			// list of report items
		int _StaticCount;

		internal ColumnGroupings(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
		{
			ColumnGrouping g;
            _Items = new List<ColumnGrouping>();
			// Loop thru all the child nodes
			foreach(XmlNode xNodeLoop in xNode.ChildNodes)
			{
				if (xNodeLoop.NodeType != XmlNodeType.Element)
					continue;
				switch (xNodeLoop.Name)
				{
					case "ColumnGrouping":
						g = new ColumnGrouping(r, this, xNodeLoop);
						break;
					default:
						g=null;		// don't know what this is
						// don't know this element - log it
						OwnerReport.rl.LogError(4, "Unknown ColumnGroupings element '" + xNodeLoop.Name + "' ignored.");
						break;
				}
				if (g != null)
					_Items.Add(g);
			}
			if (_Items.Count == 0)
				OwnerReport.rl.LogError(8, "For ColumnGroups at least one ColumnGrouping is required.");
			else
			{
                _Items.TrimExcess();
				_StaticCount = GetStaticCount();
			}
		}

		override internal void FinalPass()
		{
			foreach (ColumnGrouping g in _Items)
			{
				g.FinalPass();
			}
			return;
		}

		internal float DefnHeight()
		{
			float height=0;
			foreach (ColumnGrouping g in _Items)
			{
				height += g.Height.ToPoints();
			}
			return height;
		}
///
/// Calculates the number of static columns
///
/// <returns></returns>
		private int GetStaticCount()
		{
			// Find the static column
			foreach (ColumnGrouping cg in _Items)
			{
				if (cg.StaticColumns == null)
					continue;
				return cg.StaticColumns.Items.Count;
			}
			return 0;
		}
///
/// # of static columns;  0 if no static columns defined
///
		internal int StaticCount
		{
			get {return _StaticCount;}
		}

        internal List<ColumnGrouping> Items
		{
			get { return  _Items; }
		}

		internal MatrixEntry GetME(Report rpt)
		{
			WorkClass wc = GetWC(rpt);
			return wc.ME;
		}

		internal void SetME(Report rpt, MatrixEntry me)
		{
			WorkClass wc = GetWC(rpt);
			wc.ME = me;
		}

		private WorkClass GetWC(Report rpt)
		{
			if (rpt == null)
				return new WorkClass();

			WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass;
			if (wc == null)
			{
				wc = new WorkClass();
				rpt.Cache.Add(this, "wc", wc);
			}
			return wc;
		}

		private void RemoveWC(Report rpt)
		{
			rpt.Cache.Remove(this, "wc");
		}

		class WorkClass
		{
			internal MatrixEntry ME;	// Used at runtime to contain data values
			internal WorkClass()
			{
				ME=null;
			}
		}
	}

    ///
    /// ColumnGrouping definition and processing.
    ///
    [Serializable]
    internal class ColumnGrouping : ReportLink
    {
        RSize _Height;		// Height of the column header
        DynamicColumns _DynamicColumns;	// Dynamic column headings for this grouping
        StaticColumns _StaticColumns;		// Static column headings for this grouping

        internal ColumnGrouping(ReportDefn r, ReportLink p, XmlNode xNode)
            : base(r, p)
        {
            _Height = null;
            _DynamicColumns = null;
            _StaticColumns = null;

            // Loop thru all the child nodes
            foreach (XmlNode xNodeLoop in xNode.ChildNodes)
            {
                if (xNodeLoop.NodeType != XmlNodeType.Element)
                    continue;
                switch (xNodeLoop.Name)
                {
                    case "Height":
                        _Height = new RSize(r, xNodeLoop);
                        break;
                    case "DynamicColumns":
                        _DynamicColumns = new DynamicColumns(r, this, xNodeLoop);
                        break;
                    case "StaticColumns":
                        _StaticColumns = new StaticColumns(r, this, xNodeLoop);
                        break;
                    default:
                        break;
                }
            }
            if (_Height == null)
                OwnerReport.rl.LogError(8, "ColumnGrouping requires the Height element to be specified.");

            if ((_DynamicColumns != null && _StaticColumns != null) ||
                (_DynamicColumns == null && _StaticColumns == null))
                OwnerReport.rl.LogError(8, "ColumnGrouping requires either the DynamicColumns element or StaticColumns element but not both.");
        }

        override internal void FinalPass()
        {
            if (_DynamicColumns != null)
                _DynamicColumns.FinalPass();
            if (_StaticColumns != null)
                _StaticColumns.FinalPass();
            return;
        }

        internal RSize Height
        {
            get { return _Height; }
            set { _Height = value; }
        }

        internal DynamicColumns DynamicColumns
        {
            get { return _DynamicColumns; }
            set { _DynamicColumns = value; }
        }

        internal StaticColumns StaticColumns
        {
            get { return _StaticColumns; }
            set { _StaticColumns = value; }
        }
    }
}


text:
namespace gpu {
struct ContextCreationAttribs;

namespace gles2 {
class ContextGroup;

GPU_GLES2_EXPORT gl::GLContextAttribs GenerateGLContextAttribs(
    const ContextCreationAttribs& attribs_helper,
    const ContextGroup* context_group);

GPU_GLES2_EXPORT gl::GLContextAttribs GenerateGLContextAttribs(
    const ContextCreationAttribs& attribs_helper,
    bool use_passthrough_cmd_decoder);

// Returns true if the passthrough command decoder has been requested
GPU_GLES2_EXPORT bool UsePassthroughCommandDecoder(
    const base::CommandLine* command_line);

// Returns true if the driver supports creating passthrough command decoders
GPU_GLES2_EXPORT bool PassthroughCommandDecoderSupported();

GPU_GLES2_EXPORT GpuPreferences
ParseGpuPreferences(const base::CommandLine* command_line);

// Determine which Skia GrContext backend will be used for GPU compositing and
// rasterization (if enabled) by checking the feature flags for Vulkan and
// Metal. If they are not enabled, default to GL.
GPU_GLES2_EXPORT GrContextType ParseGrContextType();

// Parse the value of --use-vulkan from the command line. If unspecified and
// features::kVulkan is enabled (GrContext is going to use vulkan), default to
// the native implementation.
GPU_GLES2_EXPORT VulkanImplementationName
ParseVulkanImplementationName(const base::CommandLine* command_line);

}  // namespace gles2
}  // namespace gpu

#endif  // GPU_COMMAND_BUFFER_SERVICE_SERVICE_UTILS_H_


text:
/**
 * Created by darsal on 4/7/15.
 */
function validateTicketForm(){
    var flag = true;
    var elements = document.getElementById( 'ticketForm').elements;

    for( var x in elements ){
        if( elements[ x].value == '' ){
            $( '#'+elements[ x].name+'_error').addClass( 'has-error');
            flag = false;
        }
        else{
            $( '#'+elements[ x].name+'_error').removeClass( 'has-error');
        }
    }

    return flag;
}


text:
using System.Net.Http.Headers;

namespace Redmine.Net.Api
{
    public interface IAuthentication
    {
        string Type { get; }
        AuthenticationHeaderValue Build();
    }
}


text:
from __future__ import with_statement
import asyncio
import re
import time

# rediscluster imports
from aredis import StrictRedisCluster, StrictRedis
from aredis.pool import ClusterConnectionPool
from aredis.exceptions import (
    RedisClusterException, MovedError, AskError, ClusterDownError,
)
from aredis.utils import b
from aredis.nodemanager import NodeManager
from tests.cluster.conftest import _get_client, skip_if_server_version_lt, skip_if_not_password_protected_nodes

# 3rd party imports
from mock import patch, Mock, MagicMock
import pytest

pytestmark = skip_if_server_version_lt('2.9.0')

class DummyConnectionPool(ClusterConnectionPool):
    pass

class DummyConnection:
    pass

# def test_representation(r):
#     assert re.search('^StrictRedisCluster<[0-9\.\:\,].+>$', str(r))
#
#
# def test_blocked_strict_redis_args():
#     """
#     Some arguments should explicitly be blocked because they will not work in a cluster setup
#     """
#     params = {'startup_nodes': [{'host': '127.0.0.1', 'port': 7000}]}
#     c = StrictRedisCluster(**params)
#     assert c.connection_pool.connection_kwargs["stream_timeout"] == ClusterConnectionPool.RedisClusterDefaultTimeout
#
#     with pytest.raises(RedisClusterException) as ex:
#         _get_client(db=1)
#     assert str(ex.value).startswith("Argument 'db' is not possible to use in cluster mode")
#
#
# @skip_if_not_password_protected_nodes()
# def test_password_procted_nodes():
#     """
#     Test that it is possible to connect to password protected nodes
#     """
#     startup_nodes = [{"host": "127.0.0.1", "port": "7000"}]
#     password_protected_startup_nodes = [{"host": "127.0.0.1", "port": "7100"}]
#     with pytest.raises(RedisClusterException) as ex:
#         _get_client(startup_nodes=password_protected_startup_nodes)
#     assert str(ex.value).startswith("ERROR sending 'cluster slots' command to redis server:")
#     _get_client(startup_nodes=password_protected_startup_nodes, password='password_is_protected')
#
#     with pytest.raises(RedisClusterException) as ex:
#         _get_client(startup_nodes=startup_nodes, password='password_is_protected')
#     assert str(ex.value).startswith("ERROR sending 'cluster slots' command to redis server:")
#     _get_client(startup_nodes=startup_nodes)
#
#
# def test_host_port_startup_node():
#     """
#     Test that it is possible to use host & port arguments as startup node args
#     """
#     h = "192.168.0.1"
#     p = 7000
#     c = StrictRedisCluster(host=h, port=p)
#     assert {"host": h, "port": p} in c.connection_pool.nodes.startup_nodes
#
#
# def test_empty_startup_nodes():
#     """
#     Test that exception is raised when empty providing empty startup_nodes
#     """
#     with pytest.raises(RedisClusterException) as ex:
#         _get_client(init_slot_cache=False, startup_nodes=[])
#
#     assert str(ex.value).startswith("No startup nodes provided"), str(ex.value)
#
#
# def test_readonly_instance(ro):
#     """
#     Test that readonly_mode=True instance has ClusterReadOnlyConnectionPool
#     """
#     assert ro.connection_pool.readonly is True
#
#
# def test_custom_connectionpool():
#     """
#     Test that a custom connection pool will be used by StrictRedisCluster
#     """
#     h = "192.168.0.1"
#     p = 7001
#     pool = DummyConnectionPool(host=h, port=p, connection_class=DummyConnection,
#                                startup_nodes=[{'host': h, 'port': p}])
#     c = StrictRedisCluster(connection_pool=pool)
#     assert c.connection_pool is pool
#     assert c.connection_pool.connection_class == DummyConnection
#     assert {"host": h, "port": p} in c.connection_pool.nodes.startup_nodes
#
#
# @patch('aredis.StrictRedis', new=MagicMock())
# def test_skip_full_coverage_check():
#     """
#     Test if the cluster_require_full_coverage NodeManager method was not called with the flag activated
#     """
#     c = StrictRedisCluster("192.168.0.1", 7001, skip_full_coverage_check=True)
#     c.connection_pool.nodes.cluster_require_full_coverage = MagicMock()
#     c.connection_pool.nodes.initialize()
#     assert not c.connection_pool.nodes.cluster_require_full_coverage.called
#
#
# @pytest.mark.asyncio
# async def test_blocked_commands(r):
#     """
#     These commands should be blocked and raise RedisClusterException
#     """
#     blocked_commands = [
#         "CLIENT SETNAME", "SENTINEL GET-MASTER-ADDR-BY-NAME", 'SENTINEL MASTER', 'SENTINEL MASTERS',
#         'SENTINEL MONITOR', 'SENTINEL REMOVE', 'SENTINEL SENTINELS', 'SENTINEL SET',
#         'SENTINEL SLAVES', 'SHUTDOWN', 'SLAVEOF', 'SCRIPT KILL', 'MOVE', 'BITOP',
#     ]
#
#     for command in blocked_commands:
#         try:
#             await r.execute_command(command)
#         except RedisClusterException:
#             pass
#         else:
#             raise AssertionError("'RedisClusterException' not raised for method : {0}".format(command))
#
# @pytest.mark.asyncio
# async def test_blocked_transaction(r):
#     """
#     Method transaction is blocked/NYI and should raise exception on use
#     """
#     with pytest.raises(RedisClusterException) as ex:
#         await r.transaction(None)
#     assert str(ex.value).startswith("method StrictRedisCluster.transaction() is not implemented"), str(ex.value)
#
#
# @pytest.mark.asyncio
# async def test_cluster_of_one_instance():
#     """
#     Test a cluster that starts with only one redis server and ends up with
#     one server.
#
#     There is another redis server joining the cluster, hold slot 0, and
#     eventually quit the cluster. The StrictRedisCluster instance may get confused
#     when slots mapping and nodes change during the test.
#     """
#     with patch.object(StrictRedisCluster, 'parse_response') as parse_response_mock:
#         with patch.object(NodeManager, 'initialize', autospec=True) as init_mock:
#             async def side_effect(self, *args, **kwargs):
#                 async def ok_call(self, *args, **kwargs):
#                     assert self.port == 7007
#                     return "OK"
#                 parse_response_mock.side_effect = ok_call
#
#                 raise ClusterDownError('CLUSTERDOWN The cluster is down. Use CLUSTER INFO for more information')
#
#             async def side_effect_rebuild_slots_cache(self):
#                 # make new node cache that points to 7007 instead of 7006
#                 self.nodes = [{'host': '127.0.0.1', 'server_type': 'master', 'port': 7006, 'name': '127.0.0.1:7006'}]
#                 self.slots = {}
#
#                 for i in range(0, 16383):
#                     self.slots[i] = [{
#                         'host': '127.0.0.1',
#                         'server_type': 'master',
#                         'port': 7006,
#                         'name': '127.0.0.1:7006',
#                     }]
#
#                 # Second call should map all to 7007
#                 async def map_7007(self):
#                     self.nodes = [{'host': '127.0.0.1', 'server_type': 'master', 'port': 7007, 'name': '127.0.0.1:7007'}]
#                     self.slots = {}
#
#                     for i in range(0, 16383):
#                         self.slots[i] = [{
#                             'host': '127.0.0.1',
#                             'server_type': 'master',
#                             'port': 7007,
#                             'name': '127.0.0.1:7007',
#                         }]
#
#                 # First call should map all to 7006
#                 init_mock.side_effect = map_7007
#
#             parse_response_mock.side_effect = side_effect
#             init_mock.side_effect = side_effect_rebuild_slots_cache
#
#             rc = StrictRedisCluster(host='127.0.0.1', port=7006)
#             await rc.set('bar', 'foo')
#
#
# @pytest.mark.asyncio
# async def test_execute_command_errors(r):
#     """
#     If no command is given to `_determine_nodes` then exception
#     should be raised.
#
#     Test that if no key is provided then exception should be raised.
#     """
#     with pytest.raises(RedisClusterException) as ex:
#         await r.execute_command()
#     assert str(ex.value).startswith("Unable to determine command to use")
#
#     with pytest.raises(RedisClusterException) as ex:
#         await r.execute_command("GET")
#     assert str(ex.value).startswith("No way to dispatch this command to Redis Cluster. Missing key.")
#
#
# @pytest.mark.asyncio
# async def test_refresh_table_asap(monkeypatch):
#     """
#     If this variable is set externally, initialize() should be called.
#     """
#     async def return_none(*args, **kwargs):
#         return None
#     monkeypatch.setattr(ClusterConnectionPool, 'initialize', return_none)
#     monkeypatch.setattr(StrictRedisCluster, 'parse_response', return_none)
#     r = StrictRedisCluster(host="127.0.0.1", port=7000)
#     r.connection_pool.nodes.slots[12182] = [{
#         "host": "127.0.0.1",
#         "port": 7002,
#         "name": "127.0.0.1:7002",
#         "server_type": "master",
#     }]
#     r.refresh_table_asap = True
#
#     await r.set("foo", "bar")
#     assert r.refresh_table_asap is False
#     await r.flushdb()
#
#
# def find_node_ip_based_on_port(cluster_client, port):
#     for node_name, node_data in cluster_client.connection_pool.nodes.nodes.items():
#         if node_name.endswith(port):
#             return node_data['host']
#
# @pytest.mark.asyncio
# async def test_ask_redirection():
#     """
#     Test that the server handles ASK response.
#
#     At first call it should return a ASK ResponseError that will point
#     the client to the next server it should talk to.
#
#     Important thing to verify is that it tries to talk to the second node.
#     """
#     r = StrictRedisCluster(host="127.0.0.1", port=7000)
#     await r.connection_pool.initialize()
#     r.connection_pool.nodes.nodes['127.0.0.1:7001'] = {
#         'host': u'127.0.0.1',
#         'server_type': 'master',
#         'port': 7001,
#         'name': '127.0.0.1:7001'
#     }
#     with patch.object(StrictRedisCluster,
#                       'parse_response') as parse_response:
#
#         host_ip = find_node_ip_based_on_port(r, '7001')
#
#         async def ask_redirect_effect(connection, *args, **options):
#             async def ok_response(connection, *args, **options):
#                 assert connection.host == host_ip
#                 assert connection.port == 7001
#
#                 return "MOCK_OK"
#             parse_response.side_effect = ok_response
#             raise AskError("1337 {0}:7001".format(host_ip))
#
#         parse_response.side_effect = ask_redirect_effect
#         assert await r.set("foo", "bar") == "MOCK_OK"

@pytest.mark.asyncio
async def test_pipeline_ask_redirection():
    """
    Test that the server handles ASK response when used in pipeline.

    At first call it should return a ASK ResponseError that will point
    the client to the next server it should talk to.

    Important thing to verify is that it tries to talk to the second node.
    """
    r = StrictRedisCluster(host="127.0.0.1", port=7000)
    with patch.object(StrictRedisCluster,
                      'parse_response') as parse_response:

        async def response(connection, *args, **options):
            async def response(connection, *args, **options):
                async def response(connection, *args, **options):
                    assert connection.host == "127.0.0.1"
                    assert connection.port == 7001
                    return "MOCK_OK"

                parse_response.side_effect = response
                raise AskError("12182 127.0.0.1:7001")

            parse_response.side_effect = response
            raise AskError("12182 127.0.0.1:7001")

        parse_response.side_effect = response

        p = await r.pipeline()
        await p.connection_pool.initialize()
        p.connection_pool.nodes.nodes['127.0.0.1:7001'] = {
            'host': u'127.0.0.1',
            'server_type': 'master',
            'port': 7001,
            'name': '127.0.0.1:7001'
        }
        await p.set("foo", "bar")
        assert await p.execute() == ["MOCK_OK"]

@pytest.mark.asyncio
async def test_moved_redirection():
    """
    Test that the client handles MOVED response.

    At first call it should return a MOVED ResponseError that will point
    the client to the next server it should talk to.

    Important thing to verify is that it tries to talk to the second node.
    """
    r0 = StrictRedisCluster(host="127.0.0.1", port=7000)
    r2 = StrictRedisCluster(host='127.0.0.1', port=7002)
    await r0.flushdb()
    await r2.flushdb()
    assert await r0.set("foo", "bar")
    assert await r2.get('foo') == b'bar'

@pytest.mark.asyncio
async def test_moved_redirection_pipeline(monkeypatch):
    """
    Test that the server handles MOVED response when used in pipeline.

    At first call it should return a MOVED ResponseError that will point
    the client to the next server it should talk to.

    Important thing to verify is that it tries to talk to the second node.
    """
    r0 = StrictRedisCluster(host="127.0.0.1", port=7000)
    r2 = StrictRedisCluster(host='127.0.0.1', port=7002)
    await r0.flushdb()
    await r2.flushdb()
    p = await r0.pipeline()
    await p.set("foo", "bar")
    assert await p.execute() == [True]
    assert await r2.get('foo') == b'bar'

async def assert_moved_redirection_on_slave(sr, connection_pool_cls, cluster_obj):
    """
    """
    # we assume this key is set on 127.0.0.1:7000(7003)
    await sr.set('foo16706', 'foo')
    await asyncio.sleep(1)
    with patch.object(connection_pool_cls, 'get_node_by_slot') as return_slave_mock:
        return_slave_mock.return_value = {
            'name': '127.0.0.1:7004',
            'host': '127.0.0.1',
            'port': 7004,
            'server_type': 'slave',
        }

        master_value = {'host': '127.0.0.1', 'name': '127.0.0.1:7000', 'port': 7000, 'server_type': 'master'}
        with patch.object(ClusterConnectionPool, 'get_master_node_by_slot') as return_master_mock:
            return_master_mock.return_value = master_value
            assert await cluster_obj.get('foo16706') == b('foo')
            assert return_slave_mock.call_count == 1

@pytest.mark.asyncio
async def test_moved_redirection_on_slave_with_default_client(sr):
    """
    Test that the client is redirected normally with default
    (readonly_mode=False) client even when we connect always to slave.
    """
    await assert_moved_redirection_on_slave(
        sr,
        ClusterConnectionPool,
        StrictRedisCluster(host="127.0.0.1", port=7000, reinitialize_steps=1)
    )

@pytest.mark.asyncio
async def test_moved_redirection_on_slave_with_readonly_mode_client(sr):
    """
    Ditto with READONLY mode.
    """
    await assert_moved_redirection_on_slave(
        sr,
        ClusterConnectionPool,
        StrictRedisCluster(host="127.0.0.1", port=7000, readonly=True, reinitialize_steps=1)
    )

@pytest.mark.asyncio
async def test_access_correct_slave_with_readonly_mode_client(sr):
    """
    Test that the client can get value normally with readonly mode
    when we connect to correct slave.
    """

    # we assume this key is set on 127.0.0.1:7000(7003)
    await sr.set('foo16706', 'foo')
    await asyncio.sleep(1)

    with patch.object(ClusterConnectionPool, 'get_node_by_slot') as return_slave_mock:
        return_slave_mock.return_value = {
            'name': '127.0.0.1:7004',
            'host': '127.0.0.1',
            'port': 7004,
            'server_type': 'slave',
        }

        master_value = {'host': '127.0.0.1', 'name': '127.0.0.1:7000', 'port': 7000, 'server_type': 'master'}
        with patch.object(
                ClusterConnectionPool,
                'get_master_node_by_slot',
                return_value=master_value) as return_master_mock:
            readonly_client = StrictRedisCluster(host="127.0.0.1", port=7000, readonly=True)
            assert b('foo') == await readonly_client.get('foo16706')
            readonly_client = StrictRedisCluster.from_url(url="redis://127.0.0.1:7000/0", readonly=True)
            assert b('foo') == await readonly_client.get('foo16706')


text:
#include "IoState.h"
#include "IoObject.h"
#include "IoSystem.h"

void IoState_show(IoState *self)
{
	printf("--- state ----------------------------------\n");
	printf("State:\n");
	/*
	printf("black:\n");
	IoObjectGroup_show(self->blackGroup);
	printf("\n");

	printf("gray:\n");
	IoObjectGroup_show(self->grayGroup);
	printf("\n");

	printf("white:\n");
	IoObjectGroup_show(self->whiteGroup);
	printf("\n");
	*/
	printf("stacks:\n");
	printf("\n");
}

IoObject *IoState_replacePerformFunc_with_(IoState *self,
								   IoTagPerformFunc *oldFunc,
								   IoTagPerformFunc *newFunc)
{
	POINTERHASH_FOREACH(self->primitives, k, v,
		{
		IoObject *proto = v;
		IoTag *tag = IoObject_tag(proto);
		if (tag->performFunc == oldFunc || !tag->performFunc)
		{
			tag->performFunc = newFunc;
		}
		}
	);

	return NULL;
}

void IoState_debuggingOn(IoState *self)
{
	IoState_replacePerformFunc_with_(self,
							   (IoTagPerformFunc *)IoObject_perform,
							   (IoTagPerformFunc *)IoObject_performWithDebugger);
}

void IoState_debuggingOff(IoState *self)
{
	IoState_replacePerformFunc_with_(self,
							   (IoTagPerformFunc *)IoObject_performWithDebugger,
							   (IoTagPerformFunc *)IoObject_perform);
}

int IoState_hasDebuggingCoroutine(IoState *self)
{
	return 1; // hack awaiting decision on how to change this
}

void IoState_updateDebuggingMode(IoState *self)
{
	if (IoState_hasDebuggingCoroutine(self))
	{
		IoState_debuggingOn(self);
	}
	else
	{
		IoState_debuggingOff(self);
	}
}

#include <signal.h>

static IoState *stateToReceiveControlC = NULL;
static int multipleIoStates = 0;

void IoState_UserInterruptHandler(int sig)
{
	printf("\nIOVM:\n");

	if(multipleIoStates)
	{
		// what could we do here to tell which IoState we are in?
		// send the interrupt to all of them? interactively let the user choose one? interrupt the first stat created
		printf("	Received signal but since multiple Io states are in use\n");
		printf("	we don't know which state to send the signal to. Exiting.\n");
		exit(0);
	}
	else
	{
		IoState *self = stateToReceiveControlC;

		if (self->receivedSignal)
		{
			printf("	Second signal received before first was handled. \n");
			printf("	Assuming control is stuck in a C call and isn't returning\n");
			printf("	to Io so we're exiting without stack trace.\n\n");
			exit(-1);
		}
		else
		{
			self->receivedSignal = 1;

			/*
			IoObject *system = IoState_protoWithName_(self, "System");
			if (system)
			{
				IoObject *handlerMethod = IoObject_rawGetSlot_(system, IOSYMBOL("interuptHandler"));
				if (handlerMethod)
				{
					return;
				}
			}
			*/

			printf("	Received signal. Setting interrupt flag.\n");
		}
	}
}

void IoState_callUserInterruptHandler(IoState *self)
{
	self->receivedSignal = 0;

	{
		IoObject *system = IoState_doCString_(self, "System");
		IoMessage *m = IoMessage_newWithName_(self, SIOSYMBOL("userInterruptHandler"));
		IoMessage_locals_performOn_(m, system, system);
	}
}

void IoState_setupUserInterruptHandler(IoState *self)
{
	if(stateToReceiveControlC)
	{
		multipleIoStates = 1;
	}

	stateToReceiveControlC = self;
	signal(SIGINT, IoState_UserInterruptHandler);
	signal(SIGTERM, IoState_UserInterruptHandler);
}


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

namespace Studiotaiha.Hanbura
{
	internal sealed class LoggingService
	{
		static LoggingService current_;

		private LoggingService(ILogger logger)
		{
			if (logger == null) { throw new ArgumentNullException("logger"); }
			Logger = logger;
		}

		public static void Initialize(ILogger logger)
		{
			current_ = new LoggingService(logger);
		}

		public static LoggingService Current
		{
			get
			{
				if (current_ == null) { throw new InvalidOperationException("LoggingService is not initialized."); }
				return current_;
			}
		}

		public ILogger Logger { get; private set; }

		public ILogger GetLogger(string tag)
		{
			if (tag == null) { throw new ArgumentNullException("tag"); }
			return Logger.CreateChild(tag);
		}

		public ILogger GetLogger(object owner)
		{
			if (owner == null) { throw new ArgumentNullException("owner"); }
			var type = owner.GetType();
			return GetLogger(type.Name);
		}
	}
}


text:
var Crawler = require("crawler");
var client = require("./db");

module.exports = function (url) {
    var c = new Crawler({
        maxConnections: 20,
        forceUTF8: true,
        callback: function (error, res, done) {
            var $ = res.$;
            let data = {};
            data.qtitle = $("#question-header h1 a").text();
            data.acontext = $("#question .post-text").html();
            data.acontext = $("div[id^='answer-'] .post-text").html();
            data.url=url;

            client(function (db) {
                var col = db.collection('answer');
                col.insert(data, function (err, r) {
                    db.close();
                    done();
                });
            })
        }
    });
    c.queue(url);
}


text:
using System.Runtime.Serialization;

namespace KissTechFlightSheets
{
    [DataContract]
    public class FlightSheetData
    {
        [DataMember]
        public string begin_date { get; set; }

        [DataMember]
        public string query_type { get; set; }

        [DataMember]
        public Sorty[] sorties { get; set; }
    }

    public class Sorty
    {
        public string id { get; set; }
        public string cs { get; set; }
        public string tow_id { get; set; }
        public string tow_name { get; set; }
        public int type { get; set; }
        public string date { get; set; }
        public Tkof tkof { get; set; }
        public Ldg ldg { get; set; }
        public string dalt { get; set; }
        public string dt { get; set; }
    }

    public class Tkof
    {
        public string time { get; set; }
        public string loc { get; set; }
        public string rwy { get; set; }
    }

    public class Ldg
    {
        public string time { get; set; }
        public string loc { get; set; }
        public string rwy { get; set; }
    }
}


text:
from supplement.watcher import DummyMonitor

def test_watcher_must_call_uniq_handlers_on_file_change(tmpdir):
    fname = 'test.py'

    # Wrap list with hashable object
    class Holder(object):
        def __init__(self):
            self.data = []

    def on_change(fname, l):
        l.data.append(fname)

    def change_on(fname, l):
        l.data.append(fname)

    changed1 = Holder()
    changed2 = Holder()

    watcher = DummyMonitor()
    watcher.monitor(fname, on_change, changed1)
    watcher.monitor(fname, on_change, changed1)
    watcher.monitor(fname, on_change, changed2)
    watcher.monitor(fname, change_on, changed2)

    watcher.boo()

    assert changed1.data == [fname]
    assert changed2.data == [fname, fname]

def test_watcher_must_call_uniq_method_handlers_on_file_change():
    fname = 'test.py'

    class Handler(object):
        def __init__(self):
            self.changed = []

        def on_change(self, filename):
            self.changed.append(filename)

    h1 = Handler()
    h2 = Handler()

    watcher = DummyMonitor()
    watcher.monitor(fname, h1.on_change)
    watcher.monitor(fname, h1.on_change)
    watcher.monitor(fname, h2.on_change)
    watcher.boo()

    assert h1.changed == [fname]
    assert h2.changed == [fname]


text:
Installation notes for Eclipse:

* Install Eclipse J2EE (Or any version with Eclipse Marketplace): http://www.eclipse.org/downloads/

* Install Maven

* Install Maven from Eclipse Marketplace: Eclipse > Help > Eclipse Marketplace > Search: Maven > Install: Maven Integration for Eclipse

* Install EGit from Eclipse Marketplace: Eclipse > Help > Eclipse Marketplace > Search: EGit > Install: EGit - Git Team Provider

* Add git connector to Maven: Eclipse > Window > Preferences > Maven > Discovery > Open Catalog > Check: m2e-egit > Finish

* Install CloudSim as a Maven Project

* Install OnlineBroker as a Maven Project

Reference: [CloudSimEx](https://github.com/Cloudslab/CloudSimEx/wiki/Installation)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- The file 'new_aggregate.xml' is actually in the subdirectory 'subdir', so you have to tell the converter to look there, or this model cannot be flattened.-->
<?xml-model href="../../../../../RelaxNG/sbml_comp.rng" type="application/xml" schematypens="http://relaxng.org/ns/structure/1.0"?>
<sbml xmlns="http://www.sbml.org/sbml/level3/version1/core" xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" level="3" version="1" comp:required="true">
  <model>
    <comp:listOfSubmodels>
      <comp:submodel comp:id="A" comp:modelRef="EM1"/>
    </comp:listOfSubmodels>
  </model>
  <comp:listOfExternalModelDefinitions>
    <comp:externalModelDefinition comp:id="EM1" comp:source="1//jjj/lllkl:jjkj" comp:modelRef="nonexistingid"/>
  </comp:listOfExternalModelDefinitions>
</sbml>


text:
<?php

#    IRM - The Information Resource Manager
#    Copyright (C) 2001 Yann Ramin
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License (in file COPYING) for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

require_once 'include/irm.inc';
require_once 'include/User.php';
require_once 'include/functions.php';

$_SESSION['_sess_database'] = $_REQUEST['dbuse'];
$_SESSION['_sess_username'] = @$_REQUEST['name'];

if (!$_REQUEST['name'])
{
	header('Location: index.php');
	echo _('Redirecting to').' '._('the login page');
}

// The sooper-sekrit anonymous user IRMConnect gets a free pass
if (($_REQUEST['name'] != 'IRMConnect')
	&& (!User::Authenticate($_REQUEST['name'], $_REQUEST['password'])))
{
 	logevent(-1, "IRM", 1, "login",
			_(sprintf(_("Failed login: '%s', database '%s'"),
					$_REQUEST['name'],
					$_SESSION['_sess_database'])));
 	$dest = urlencode(@$_REQUEST['redirect']);
	header('Location: index.php?auth=fail&redirect='.$dest);
	echo _('Redirecting to').' '._('the login page').'';
	exit;
}

if ($_REQUEST['redirect'])
{
	if ($_REQUEST['ID']){
		header("Location: ".Config::AbsLoc($_REQUEST['redirect']. $_REQUEST['ID']));
	} else {
		header("Location: ".Config::AbsLoc($_REQUEST['redirect']));
	}
} else {
	header("Location: ".Config::AbsLoc('users/index.php'));
}

echo _('Redirecting to').' '._('the system index').'';


text:
package org.home.whatsfordinner.domain.ingredient;

import org.home.whatsfordinner.common.EqualsJUnitTest;
import org.home.whatsfordinner.common.HashCodeJUnitTest;
import org.junit.Test;

public class IngredientJUnitTest {

    @Test
    public void testEqualsSameObject() {
        EqualsJUnitTest.testEqualsSameObject(new Ingredient());
    }

    @Test
    public void testEqualsNull() {
        EqualsJUnitTest.testEqualsNull(new Ingredient());
    }

    @Test
    public void testEqualsOtherClass() {
        EqualsJUnitTest.testEqualsOtherClass(new Ingredient());
    }

    @Test
    public void testEqualsId() {
        EqualsJUnitTest.testEqualsId(new Ingredient(), new Ingredient());
    }

    @Test
    public void testHashCode() {
        final Ingredient ingredient = new Ingredient();
        HashCodeJUnitTest.testHashCode(ingredient, 111);
        ingredient.setId(3L);
        HashCodeJUnitTest.testHashCode(ingredient, 114);
    }
}


text:
© Tristano Ajmone, 2015

v. Alpha 1 — 30th March 2015

Released under BSD 2-clause "Simplified" License.

## Introduction

Evennia Docstringer is a Windows standalone application aimed at simplifying and (in future editions) automate the creation of ANSI-formatted MUD-text for Evennia by line-wrapping text at 80 columns (ANSI/Xterm256 tags excluded) and offering a color-preview of how it will look like in MUD output.

## About Evennia

*Evennia* is a modern library for creating [online multiplayer text games][] (MUD, MUSH, MUX, MOO etc) in pure Python. It allows game creators to design and flesh out their games with great freedom. Evennia is made available under the very friendly [BSD license][].

-   [http://www.evennia.com][]

-   <https://github.com/evennia/evennia>

## Features

In it's present Alpha stage it offers the functionality of breaking text, by line-wrapping, into 80-characters long lines — all wrapping calculations are based on the actual characters that will display on the MUD-client screen, so ANSI tags are left out of the calculation.

This comes handy when formatting Cmds autohelp dosctrings: Evennia autohelp generator will take ordinary Python docstrings and extrapolate from them the text that will be shown via the `help` command. Evennia Docstringer will output wrapped text that can be directly pasted as Python docstring into the Cmds module. Output could also be used anywhere custom MUD-text is required.

The user doesn't have to worry about manually wrapping at 80: in Evennia Docstringer the «raw» input and the «docstringed» output are separated; therefore raw text can have long unwrapped lines, and adding and deleting text won't require manually retouching lines to be within 80 characters.

For the time being, 80 columns-wrapping is a fixed value. In future editions it will be customizable via settings.

When wrapping a line that had trailing white-spaces, Evennia Docstringer will carry-on the same spacing on the wrapped lines.

Evennia Docstringer also has a nice color previewer which replicated Evennia's handling of ANSI and Xterm256 tags as close as possible. This feature is quite handy when handling text with lots of ANSI/Xterm256 codes outside of Evennia.

For the moment being, the app offers only clipboard-export functionality, no saving or loading.

## Up-Coming Features

In future editions, this tool will grow with automation in mind: the idea is to manage within a single file more than one docstring, each one being associated with a specific Python class in an external module, so that from a single file it will be possible to handle all the «raw» docstrings of many modules (Cmds, etc.) and inject their formatted version directly into their destination files.

Other upcoming features will relate to the creation/injection of Evennia batch commands and batch codes. This could be used to create server-startup scripts that add custom (non-Cmd related) items to help system.

Also, word-wrapping (hyphened syllabation) options and custom tags for simplifying docstring formatting are on the way — they will be placed in the raw input, and convert into appropriate formatting in the final docstring. Something similar to MarkDown syntax.

Being an open project, ideas are welcomed. So, anything that might be of general help for the creation of MUD-related texts (books, magazines, ecc.) could be proposed and become part of Evennia Docstringer.

For the next updates, the focus will be on file handling: saving, retriving, allowing multiple docstrings per file, associating docstrings to external files, ecc. That achieved, I'll be heading to implement Python modules-injection functionalities. So, stay tuned for updates.

## Supported Tags

The following Evennia ANSI tags/escape-sequences are supported:

-   `{#` and `{[#` where \# stands for any ANSI color (rgybmcwxRGYBMCWX).

-   `{!#` where \# stands for any normal/dark foreground ANSI color (RGYBMCWX).

-   `{###` and `{[###` Xterm colors, where each \# stands for a 0-5 digit.

-   `{n` back to normal mode.

-   `{*` invert foreground and background colors.

-   `{_` tab character (previewed as a single space).

-   `{-` non-strippable whitespace.

-   `{^` blink (taken into account but not previewed).

-   `{h` and `{H` highlight on/off tags.

-   escaped tags, any tag preceded by `{` (eg. `{{r`).

The following tags are not supported:

-   `{/` linebreak (ignored); you shouldn't need that in docstrings anyway.

-   `{lc`, `{lt` and `{le` cliccable-links (ignored); might be implemented in the future.

-   Inline functions. No plans to implement them.

Any invalid tags (eg: `{Q`, `{!r`, `{666`) will simply be ignored and treated as normal text.

For detailed information of supported tags and their use, consult Evennia Wiki page:

-   <https://github.com/evennia/evennia/wiki/TextTags>

## Using and Compiling

Evennia Docstringer comes with both sourcecode and pre-compiled binary file. You don't need to compile it yourself.

It was created using AutoIt version 3.3.12.0, a freeware BASIC-like scripting language:

-   <https://www.autoitscript.com>

The compiled binary doesn't use UPX compression because some anti-virus might give false-positive alerts (see below). Some anti-virus (for example, Gmail's) might complain about the non-packaged version instead.

### UPX Warning

When AutoIt compiles executable files it offers the option to compress them with UPX ([Ultimate Packer for Executables][]). UPX packaged files can be reduced around 40-50% in size. UPX is good, and it's free.

It is wellknown that a number of anti-virus programs give false-positive alerts for UPX-packaged files, and for other packagers too. If after compiling you experience problems with your anti-virus, recompile it trying different compression options.

The reasoning behind these false-positive alarms is that since many hackers use opensource packagers to hide viruses, some anti-virus programs will prevent *any *program compressed with those packagers to run, even though the use of opensource packagers is common good practice in the world of opensource software development. Of course, commercial packagers created by large corporations don't rise false-positives, even though they *might *be carrying malicious code too.

Packaging has nothing to do with malicious contents, it's about compressing binary code, like when you use WinZip. Malicious code is almost always compressed because it tries to avoid fingerprinting, but compressed code is *not *always malicious (on the contrary). There is no direct relation between packaging and malicious-code.

Unfortunately, many programmers had to give-up using good packagers like UPX because of these bad-practices in (rubbish) anti-virus softwares — the problem being that many users think that those antivirus are *better *because they catch viruses that others miss; on the contrary: good antiviruses don't raise false-positives.

So, I apologise for not packaging Evennia Docstringer with UPX. You can still do it yourself though.

For more information:

-   <https://www.autoitscript.com/wiki/AutoIt_and_Malware>

  [online multiplayer text games]: http://en.wikipedia.org/wiki/MUD
  [BSD license]: https://github.com/evennia/evennia/wiki/Licensing
  [http://www.evennia.com]: http://www.evennia.com/
  [Ultimate Packer for Executables]: http://en.wikipedia.org/wiki/UPX


text:
<!doctype html>

    <meta charset="utf-8">

<title>  Preslav Rachev</title>
<meta name="description" content="This is my first official post on the microblog. And, believe it or not, one that I created on the fly, using only my iPhone and a clever Workflow/WorkingCopy contraption I designed for posting. How cool is that? 🎉">

<meta property="og:type" content="article">
<meta property="og:locale" content="en_US">
<meta property="og:site_name" content="Preslav Rachev">
<meta property="og:title" content="Preslav Rachev">
<meta property="og:url" content="https://preslav.me/micro/2018/09160903/">

  <meta property="og:description" content="This is my first official post on the microblog. And, believe it or not, one that I created on the fly, using only my iPhone and a clever Workflow/WorkingCopy contraption I designed for posting. How cool is that? 🎉">

  <meta property="article:published_time" content="2018-09-16T09:03:00+02:00">

<link rel="canonical" href="https://preslav.me/micro/2018/09160903/">

<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Preslav Rachev Feed">

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

<link rel="stylesheet" href="/assets/css/main.css">

<link href="https://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700|PT+Serif:400,700,400italic" rel="stylesheet" type="text/css">
<link href="https://micro.blog/preslavrachev" rel="me" />

        Preslav Rachev

              About

              Microblog

              Archive

              Contact

        <button class="search__toggle" type="button">
          <svg class="icon" width="16" height="16" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15.99 16">
            <path d="M15.5,13.12L13.19,10.8a1.69,1.69,0,0,0-1.28-.55l-0.06-.06A6.5,6.5,0,0,0,5.77,0,6.5,6.5,0,0,0,2.46,11.59a6.47,6.47,0,0,0,7.74.26l0.05,0.05a1.65,1.65,0,0,0,.5,1.24l2.38,2.38A1.68,1.68,0,0,0,15.5,13.12ZM6.4,2A4.41,4.41,0,1,1,2,6.4,4.43,4.43,0,0,1,6.4,2Z" transform="translate(-.01)"></path>
          </svg>
        </button>

        <button class="greedy-nav__toggle hidden" type="button">
          Toggle menu

        </button>

Preslav Rachev

        A runner and a programming / data science polymath. A Bulgarian living in Germany. Bridging the gap between software engineering and data science.

    <button class="btn btn--inverse">Follow</button>

           Munich, Germany

     Twitter

     GitHub

     LinkedIn

     Mastodon

    <meta itemprop="headline" content="">
    <meta itemprop="description" content="This is my first official post on the microblog. And, believe it or not, one that I created on the fly, using only my iPhone and a clever Workflow/WorkingCopy contraption I designed for posting. How cool is that? 🎉">
    <meta itemprop="datePublished" content="September 16, 2018">

This is my first official post on the microblog. And, believe it or not, one that I created on the fly, using only my iPhone and a clever Workflow/WorkingCopy contraption I designed for posting. How cool is that? 🎉

There are so many things that are still not here, like the ability to post images, or refer to past posts, there is also no RSS feed specific to the microblog yet. I guess, I will just have to be patient for a while and start adding those one by one.

 Updated: <time datetime="2018-09-16T09:03:00+02:00">September 16, 2018</time>

Share on

   Twitter

   Facebook

   Google+

   LinkedIn

      Previous

      Next

<input type="text" id="search" class="search-input" tabindex="-1" placeholder="Enter your search term..." />

Follow:

 Feed

© 2019 Your Name. Powered by Jekyll & Minimal Mistakes.


text:
<tool id='usher' name='UShER' version='@TOOL_VERSION@+@GALAXY_TOOL_VERSION@' profile='20.01'>
    <description>ultrafast sample placement on existing trees</description>
    <macros>
        <import>macros.xml</import>
    </macros>
    <expand macro='edam_ontology' />
    <expand macro='requirements' />
    <version_command>usher --version</version_command>
    <command detect_errors='exit_code'><![CDATA[
        #if $vcf.ext == 'vcf_bgzip':
            ln -s '$vcf' input.vcf.gz &&
            ln -s '$vcf.metadata.tabix_index' input.vcf.gz.tbi &&
            #set $input_vcf = 'input.vcf.gz'
        #else:
            ln -s '$vcf' input.vcf &&
            #set $input_vcf = 'input.vcf'
        #end if

        usher
        -v '$input_vcf'
        #if $tree
            -t '${tree}'
        #end if
        #if $load_mutation_annotated_tree
            -i '${load_mutation_annotated_tree}'
        #end if
        $output_options.save_mutation_annotated_tree
        $sort_mode
        $collapse_options.collapse_tree
        $collapse_options.collapse_output_tree
        #if $max_uncertainty_per_sample
            -e $max_uncertainty_per_sample
        #end if
        $output_options.write_uncondensed_final_tree
        #if $output_options.write_subtrees_size
            -k $output_options.write_subtrees_size
        #end if
        #if $output_options.write_single_subtree
            -K $output_options.write_single_subtree
        #end if
        $output_options.write_parsimony_scores_per_node
        #if $output_options.multiple_placements
            -M $output_options.multiple_placements
        #end if
        #if $retain_input_branch_lengths
            $retain_input_branch_lengths
        #end if
        -T \${GALAXY_SLOTS:-1}
        -d ./
        #if $output_options.write_subtrees_size
            && mkdir -p out_subtrees out_subtrees_expanded out_subtrees_mutations
            && mv subtree*expanded.txt ./out_subtrees_expanded
            && mv subtree*mutations.txt ./out_subtrees_mutations
            && mv subtree*.nh ./out_subtrees
        #end if
    ]]>    </command>
    <inputs>
        <param name="vcf" type="data" format="vcf,vcf_bgzip" label="VCF file" help="Input VCF file."/>
        <param name="tree" type="data" format="newick" optional="True" label="Tree file" help="Input tree file in Newick format."/>
        <param argument="--load-mutation-annotated-tree" type="data" format="protobuf3" optional="True" label="Mutation-annotated tree object" help="Load a mutation annotated tree file, in protocol-buffers format (protobuf3)."/>
        <param name="sort_mode" type="select" label="Mode of sorting new samples">
            <option value="">Default sorting</option>
            <option value="--sort-before-placement-1">Sort based on computed parsimony score and then number of optimal placements before the actual placement (-s)</option>
            <option value="--sort-before-placement-1 --reverse-sort">Sort based on computed parsimony score and then number of optimal placements before the actual placement [reversed] (-s -r)</option>
            <option value="--sort-before-placement-2">Sort based on the number of optimal placements and then the parsimony score before the actual placement (-S)</option>
            <option value="--sort-before-placement-2 --reverse-sort">Sort based on the number of optimal placements and then the parsimony score before the actual placement [reversed] (-S -r)</option>
            <option value="--sort-before-placement-3">Sort based on the number of ambiguous bases (-A)</option>
        </param>
        <param argument="--max-uncertainty-per-sample" type="integer" optional="True" min="0" max="10000000" value="" label="Maximum number of equally parsimonious placements" help="Maximum number of equally parsimonious placements allowed per sample beyond which the sample is ignored." />
        <param argument="--retain-input-branch-lengths" type="boolean" truevalue="--retain-input-branch-lengths" falsevalue="" label="Retain the branch lengths" help="Retain the branch lengths from the input tree in out newick files instead of using number of mutations for the branch lengths." />

            <param argument="--collapse-tree" type="boolean" truevalue="--collapse-tree" falsevalue="" label="Collapse internal nodes of the input tree" help="Collapse internal nodes of the input tree with no mutations and condense identical sequences in polytomies into a single node and the save the tree to file condensed-tree.nh in outdir." />
            <param argument="--collapse-output-tree" type="boolean" truevalue="--collapse-output-tree" falsevalue="" label="Collapse internal nodes of the output tree" help="Collapse internal nodes of the output tree with no mutations before the saving the tree to file final-tree.nh in outdir." />

            <param argument="--save-mutation-annotated-tree" type="boolean" truevalue="--save-mutation-annotated-tree annotated-tree.pb" falsevalue="" label="Save the new mutation-annotated tree object" help="Save output mutation-annotated tree object to the file new_global_assignments.pb." />
            <param argument="--write-uncondensed-final-tree" type="boolean" truevalue="--write-uncondensed-final-tree" falsevalue="" label="Uncondensed final tree" help="Write the final tree in uncondensed format and save to file uncondensed-final-tree.nh in outdir." />
            <param argument="--write-subtrees-size" type="integer" optional="True" min="0" max="100" value="" label="Generate multiple subtrees" help="Write minimum set of subtrees covering the newly added samples of size equal to this value." />
            <param argument="--write-single-subtree" type="integer" optional="True" min="0" max="100" value="" label="Generate a single subtree" help="Similar to write-subtrees-size but produces a single subtree with all newly added samples along with random samples up to the value specified by this argument." />
            <param argument="--write-parsimony-scores-per-node" type="boolean" truevalue="--write-parsimony-scores-per-node" falsevalue="" label="Generate parsimony scores per node" help="Write the parsimony scores for adding new samples at each existing node in the tree without modifying the tree in a file names parsimony-scores.tsv in outdir." />
            <param argument="--multiple-placements" type="integer" optional="True" min="0" max="100" value="" label="Multiple placements" help="Create a new tree up to this limit for each possibility of parsimony-optimal placement." />

    </inputs>
    <outputs>
        <data name="annotated_tree" format="protobuf3" from_work_dir="annotated-tree.pb" label="${tool.name} on ${on_string}: mutation annotated tree">
            <filter>output_options['save_mutation_annotated_tree'] is True</filter>
        </data>
        <data name="condensed_tree" format="newick" from_work_dir="condensed-tree.nh" label="${tool.name} on ${on_string}: condensed tree">
            <filter>collapse_options['collapse_tree'] is True</filter>
        </data>
        <data name="final_tree" format="newick" from_work_dir="final-tree.nh" label="${tool.name} on ${on_string}: final tree">
            <filter>output_options['write_uncondensed_final_tree'] is False and output_options['write_parsimony_scores_per_node'] is False</filter>
        </data>
        <data name="uncondensed_tree" format="newick" from_work_dir="uncondensed-final-tree.nh" label="${tool.name} on ${on_string}: uncondensed tree">
            <filter>output_options['write_uncondensed_final_tree'] is True</filter>
        </data>
        <data name="mutation_paths" format="txt" from_work_dir="mutation-paths.txt" label="${tool.name} on ${on_string}: mutation paths">
            <filter>output_options['save_mutation_annotated_tree'] is False and output_options['write_parsimony_scores_per_node'] is False</filter>
        </data>
        <data name="clades" format="txt" from_work_dir="clades.txt" label="${tool.name} on ${on_string}: clades">
            <filter>output_options['save_mutation_annotated_tree'] is False and output_options['write_parsimony_scores_per_node'] is False</filter>
        </data>
        <collection name='subtrees' type='list' label='${tool.name} on ${on_string}: subtrees'>
            <discover_datasets pattern='__designation_and_ext__' format="newick" directory='out_subtrees'/>
            <filter>output_options['write_subtrees_size']</filter>
        </collection>
        <collection name='subtrees_expanded' type='list' label='${tool.name} on ${on_string}: subtrees expanded'>
            <discover_datasets pattern='__designation_and_ext__' format='txt' directory='out_subtrees_expanded'/>
            <filter>output_options['write_subtrees_size']</filter>
        </collection>
        <collection name='subtrees_mutations' type='list' label='${tool.name} on ${on_string}: subtrees mutations'>
            <discover_datasets pattern='__designation_and_ext__' format='txt' directory='out_subtrees_mutations'/>
            <filter>output_options['write_subtrees_size']</filter>
        </collection>
        <data name="current_tree" format="newick" from_work_dir="current-tree.nh" label="${tool.name} on ${on_string}: current tree">
            <filter>output_options['write_parsimony_scores_per_node'] is True</filter>
        </data>
        <data name="parsimony_scores" format="tabular" from_work_dir="parsimony-scores.tsv" label="${tool.name} on ${on_string}: parsimony scores per node">
            <filter>output_options['write_parsimony_scores_per_node'] is True</filter>
        </data>
        <data name="single_subtree" format="newick" from_work_dir="single-subtree.nh" label="${tool.name} on ${on_string}: single subtree">
            <filter>output_options['write_single_subtree']</filter>
        </data>
        <data name="single_subtree_expanded" format="txt" from_work_dir="single-subtree-expanded.txt" label="${tool.name} on ${on_string}: single subtree expanded">
            <filter>output_options['write_single_subtree']</filter>
        </data>
        <data name="single_subtree_mutations" format="txt" from_work_dir="single-subtree-mutations.txt" label="${tool.name} on ${on_string}: single subtree mutations">
            <filter>output_options['write_single_subtree']</filter>
        </data>
    </outputs>
    <tests>
        <test expect_num_outputs="3">
            <param name="vcf" value="global_samples.vcf.gz" ftype="vcf_bgzip" />
            <param name="tree" value="global_phylo.nh"/>

                <param name="collapse_tree" value="true"/>

                <param name="save_mutation_annotated_tree" value="true"/>

            <output name="annotated_tree" file="test_01_annotated_tree.pb" ftype="protobuf3">
                <assert_contents>
                    <has_size value="26100" delta="100"/>
                </assert_contents>
            </output>
            <output name="condensed_tree" file="test_01_condensed_tree.nh" ftype="newick"/>
            <output name="final_tree" file="test_01_final_tree.nh" ftype="newick"/>
        </test>
        <test expect_num_outputs="3">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>

                <param name="write_uncondensed_final_tree" value="true"/>

            <output name="uncondensed_tree" file="test_02_uncondensed_tree.nh" ftype="newick"/>
            <output name="mutation_paths" file="test_02_mutation_path.nh" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0" delta="0"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="4">
            <param name="vcf" value="global_samples.vcf.gz" ftye="vcf_bgzip" />
            <param name="tree" value="global_phylo.nh"/>
            <param name="sort_mode" value="--sort-before-placement-1"/>

                <param name="collapse_tree" value="true"/>

            <output name="condensed_tree" file="test_03_condensed_tree.nh" ftype="newick"/>
            <output name="final_tree" file="test_03_final_tree.nh" ftype="newick"/>
            <output name="mutation_paths" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="6">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>

                <param name="write_uncondensed_final_tree" value="true"/>
                <param name="write_subtrees_size" value="20"/>

            <output name="uncondensed_tree" file="test_04_uncondensed_tree.nh" ftype="newick"/>
            <output name="mutation_paths" file="test_04_mutation_paths.txt" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
            <output_collection name="subtrees" type="list" count="1">
                <element name="subtree-1" file="test_04_subtree_1.nh"/>
            </output_collection>
            <output_collection name="subtrees_expanded" type="list" count="1">
                <element name="subtree-1-expanded" file="test_04_subtree_1_expanded.txt" ftype="txt"/>
            </output_collection>
            <output_collection name="subtrees_mutations" type="list" count="1">
                <element name="subtree-1-mutations" file="test_04_subtree_1_mutations.txt" ftype="txt"/>
            </output_collection>
        </test>
        <test expect_num_outputs="2">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>

                <param name="write_parsimony_scores_per_node" value="true"/>

            <output name="current_tree" file="test_05_current_tree.nw" ftype="newick"/>
            <output name="parsimony_scores" file="test_05_parsimony_scores.tabular" ftype="tabular"/>
        </test>
        <test expect_num_outputs="3">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>

                <param name="multiple_placements" value="2"/>

            <output name="final_tree" file="test_06_final_tree.nh" ftype="newick"/>
            <output name="mutation_paths" file="test_06_mutation_paths.txt" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="6">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>

                <param name="write_single_subtree" value="2"/>

            <output name="final_tree" file="test_06_final_tree.nh" ftype="newick"/>
            <output name="mutation_paths" file="test_06_mutation_paths.txt" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
            <output name="single_subtree" file="test_07_single_subtree.nh" ftype="newick"/>
            <output name="single_subtree_mutations" file="test_07_single_subtree_mutations.txt" ftype="txt"/>
            <output name="single_subtree_expanded" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="3">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>
            <param name="sort_mode" value="--sort-before-placement-2"/>
            <output name="final_tree" file="test_08_final_tree.nh" ftype="newick"/>
            <output name="mutation_paths" file="test_08_mutation_path.nh" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="3">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>
            <param name="sort_mode" value="--sort-before-placement-3"/>
            <output name="final_tree" file="test_09_final_tree.nh" ftype="newick"/>
            <output name="mutation_paths" file="test_09_mutation_path.nh" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="3">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>
            <param name="sort_mode" value="--sort-before-placement-1 --reverse-sort"/>
            <output name="final_tree" file="test_10_final_tree.nh" ftype="newick"/>
            <output name="mutation_paths" file="test_10_mutation_path.nh" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="3">
            <param name="vcf" value="new_samples.vcf.gz"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>
            <param name="sort_mode" value="--sort-before-placement-2 --reverse-sort"/>
            <output name="final_tree" file="test_11_final_tree.nh" ftype="newick"/>
            <output name="mutation_paths" file="test_11_mutation_path.nh" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="3">
            <param name="vcf" value="new_samples.vcf.gz" ftype="vcf_bgzip"/>
            <param name="load_mutation_annotated_tree" value="test_01_annotated_tree.pb"/>
            <param name="retain_input_branch" value="true"/>
            <output name="final_tree" file="test_12_final_tree.nh" ftype="newick" lines_diff="2"/>
            <output name="mutation_paths" file="test_12_mutation_path.nh" ftype="txt"/>
            <output name="clades" ftype="txt">
                <assert_contents>
                    <has_size value="0"/>
                </assert_contents>
            </output>
        </test>
    </tests>
    <help><![CDATA[
.. class:: infomark

**Purpose**

UShER is a program for rapid, accurate placement of samples to existing phylogenies. While not restricted to SARS-CoV-2 phylogenetic analyses, it has enabled real-time phylogenetic analyses and genomic contact tracing in that its placement is orders of magnitude faster and more memory-efficient than previous methods, and is being widely used by several SARS-CoV-2 research groups, including the UCSC Genome Browser team and Rob Lanfear's global phylogeny releases.

----

.. class:: infomark

**How UShER works?**

Given existing samples, whose genotypes and phylogenetic tree is known, and the genotypes of new samples, UShER aims to incorporate new samples into the phylogenetic tree while preserving the topology of existing samples and maximizing parsimony. UShER's algorithm consists of two phases: (i) the pre-processing phase and (ii) the placement phase.

In the pre-processing phase, UShER accepts the phylogenetic tree of existing samples in a Newick format and their genotypes, specified as a set of single-nucleotide variants with respect to a reference sequence (UShER currently ignores indels), in a VCF format. For each site in the VCF, UShER uses `Fitch-Sankoff algorithm <https://evolution.gs.washington.edu/gs541/2010/lecture1.pdf>`_ to find the most parsimonious nucleotide assignment for every node of the tree (UShER automatically labels internal tree nodes).

When a sample contains ambiguous genotypes, multiple nucleotides may be most parsimonious at a node. To resolve these, UShER assigns it any one of the most parsimonious nucleotides with preference, when possible, given to the reference base. UShER also allows the VCF to specify ambiguous bases in samples using `IUPAC format <https://www.bioinformatics.org/sms/iupac.html>`_, which are also resolved to a unique base using the above strategy. When a node is found to carry a mutation, i.e. the base assigned to the node differs from its parent, the mutation gets added to a list of mutations corresponding to that node. Finally, UShER uses `protocol buffers <https://developers.google.com/protocol-buffers>`_ to store in a file, the Newick string corresponding to the input tree and a list of lists of node mutation, which we refer to as mutation-annotated tree object.

The mutation-annotated tree object carries sufficient information to derive parsimony-resolved genotypes for any tip of the tree using the sequence of mutations from the root to that tip. Compared to other tools that use full multiple-sequence alignment (MSA) to guide the placement, UShER's mutation-annotated tree object is compact and is what helps make it fast.

In the placement phase, UShER loads the pre-processed mutation-annotated tree object and the genotypes of new samples in a VCF format and sequentially adds the new samples to the tree. For each new sample, UShER computes the additional parsimony score required for placing it at every node in the current tree while considering the full path of mutations from the root of the tree to that node.

Next, UShER places the new sample at the node that results in the smallest additional parsimony score. When multiple node placements are equally parsimonious, UShER picks the node with a greater number of descendant leaves for placement. If the choice is between a parent and its child node, the parent node would always be selected by this rule. However, a more accurate placement should reflect the number of leaves uniquely attributable to the child versus parent node. Therefore, in these cases, UShER picks the parent node if the number of descendant leaves of the parent that are not shared with the child node exceed the number of descendant leaves of the child.

UShER also automatically imputes and reports ambiguous genotypes for the newly added samples and ignores missing bases, such as 'N' or '.' (i.e. missing bases never contribute to the parsimony score).

At the end of the placement phase, UShER allows the user to create another protocol-buffer (protobuf) file containing the mutation-annotated tree object for the newly generated tree including added samples. This allows for another round of placements to be carried out over and above the newly added samples.

    ]]>    </help>
    <expand macro="citations" />
</tool>


text:
id: 5900f3f51000cf542c50ff07
challengeType: 5
title: 'Problem 136: Singleton difference'
forumTopicId: 301764
localeTitle: 'Задача 136: разность Синглтона'
---

## Description

Положительные целые числа x, y и z являются последовательными членами арифметической прогрессии. Учитывая, что n является положительным целым числом, уравнение x2 - y2 - z2 = n имеет ровно одно решение, когда n = 20: 132 - 102 - 72 = 20 Фактически, существует двадцать пять значений n ниже ста, для которых уравнение имеет единственное решение. Сколько значений n менее пятидесяти миллионов имеет ровно одно решение?

## Instructions

## Tests

```yml
tests:
  - text: <code>euler136()</code> should return 2544559.
    testString: assert.strictEqual(euler136(), 2544559);

```

## Challenge Seed

```js
function euler136() {
  // Good luck!
  return true;
}

euler136();

```

## Solution

```js
// solution required
```


text:
/*
 * hclib-internal.h
 *
 *      Author: Vivek Kumar (vivekk@rice.edu)
 *      Acknowledgments: https://wiki.rice.edu/confluence/display/HABANERO/People
 */

#ifndef HCLIB_INTERNAL_H_
#define HCLIB_INTERNAL_H_

#include <stdarg.h>
#include <stdint.h>
#include "hclib-tree.h"
#include "hclib-deque.h"
#include "hclib.h"
#include "litectx.h"
#include "hclib-locality-graph.h"

#define LOG_LEVEL_FATAL         1
#define LOG_LEVEL_WARN          2
#define LOG_LEVEL_INFO          3
#define LOG_LEVEL_DEBUG         4
#define LOG_LEVEL_TRACE         5

/* set the current log level */
#define LOG_LEVEL LOG_LEVEL_FATAL

#define WHEREARG __FILE__,__LINE__

#define LOG_(level, ...) if (level<=LOG_LEVEL) log_(WHEREARG, CURRENT_WS_INTERNAL, __VA_ARGS__);

/* We more or less mimic log4c without the ERROR level */
#define LOG_FATAL(...)  LOG_(LOG_LEVEL_FATAL, __VA_ARGS__)
#define LOG_WARN(...)   LOG_(LOG_LEVEL_WARN,  __VA_ARGS__)
#define LOG_INFO(...)   LOG_(LOG_LEVEL_INFO,  __VA_ARGS__)
#define LOG_DEBUG(...)  LOG_(LOG_LEVEL_DEBUG, __VA_ARGS__)
#define LOG_TRACE(...)  LOG_(LOG_LEVEL_TRACE, __VA_ARGS__)

/* log the msg using the fatal logger and abort the program */
#define log_die(... ) { LOG_FATAL(__VA_ARGS__); abort(); }
#define check_log_die(cond, ... ) if(cond) { log_die(__VA_ARGS__) }

#define CACHE_LINE_L1 8

// Default value of a promise datum
#define UNINITIALIZED_PROMISE_DATA_PTR NULL

// For waiting frontier (last element of the list)
#define SATISFIED_FUTURE_WAITLIST_PTR NULL
#define SENTINEL_FUTURE_WAITLIST_PTR ((void*) -1)

typedef struct {
    volatile int flag;
    int padding;
    void * pad[CACHE_LINE_L1 - 1];
} worker_done_t;

/*
 * Global context information for the HC runtime, shared by all worker threads.
 */
typedef struct hclib_context {
    struct _hclib_worker_state** workers; /* all workers */
    hclib_locality_graph *graph;
    hclib_worker_paths *worker_paths;
    int nworkers; /* # of worker threads created */
    int ncores; /* physical number of cores detected */
    /* a simple implementation of wait/wakeup condition */
    volatile int workers_wait_cond;
    worker_done_t *done_flags;
#ifdef HC_CUDA
    hclib_memory_tree_node *pinned_host_allocs;
    cudaStream_t stream;
#endif
} hclib_context;

#include "hclib-finish.h"

typedef struct _hclib_deque_t {
    /* The actual deque, WARNING: do not move declaration !
     * Other parts of the runtime rely on it being the first one. */
    hclib_internal_deque_t deque;
    struct _hclib_worker_state * ws;
    struct _hclib_deque_t *nnext;
    struct _hclib_deque_t *prev; /* the deque list of the worker */
    hclib_locale_t *locale;
} hclib_deque_t;

void log_(const char * file, int line, hclib_worker_state * ws, const char * format,
        ...);

// promise
int register_on_all_promise_dependencies(hclib_task_t *wrapper_task);
void try_schedule_async(hclib_task_t * async_task, hclib_worker_state *ws);

int static inline _hclib_promise_is_satisfied(hclib_promise_t *p) {
    return p->wait_list_head == SATISFIED_FUTURE_WAITLIST_PTR;
}

#endif /* HCLIB_INTERNAL_H_ */


text:
package de.adesso.wickedcharts.highcharts.options;

import de.adesso.wickedcharts.highcharts.json.LowercaseEnum;

/**
 * Possible styles for dashed lines.
 *
 * @author Tom Hombergs (tom.hombergs@gmail.com)
 *
 */
public enum GridLineDashStyle implements LowercaseEnum {

	SOLID,

	SHORTDASH,

	SHORTDOT,

	SHORTDASHDOT,

	SHORTDASHDOTDOT,

	DOT,

	DASH,

	LONGDASH,

	DASHDOT,

	LONGDASHDOT,

	LONGDASHDOTDOT;

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>References</title>
<link rel='stylesheet' type='text/css' href='./spec.css' />
<link rel='stylesheet' type='text/css' href='W3C-REC.css' />
<link rel='next' href='def-index.html' />
<link rel='contents' href='Overview.html#contents' />
<link rel='index' href='def-index.html' />
<link rel='previous' href='glossary.html' />

previous   next   contents   index

13 November,
2000

References

For the latest version of any W3C specification please consult
the list of W3C Technical
Reports available at http://www.w3.org/TR.

F.1: Normative
references

DOM Level 2 Core

W3C (World Wide Web Consortium) Document
Object Model Level 2 Core Specification, November 2000.
Available at
http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113

ECMAScript

ECMA (European Computer Manufacturers Association) ECMAScript
Language Specification. Available at
http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM

Java

Sun Microsystems Inc. The Java Language
Specification, James Gosling, Bill Joy, and Guy Steele,
September 1996. Available at
http://java.sun.com/docs/books/jls

OMGIDL

OMG (Object Management Group)
IDL (Interface Definition Language) defined in The Common Object
Request Broker: Architecture and Specification, version 2.3.1,
October 1999. Available from http://www.omg.org/

DOM Level 2
Views

W3C (World Wide Web Consortium) Document
Object Model Level 2 Views Specification, November 2000.
Available at
http://www.w3.org/TR/2000/REC-DOM-Level-2-Views-20001113

XML

W3C (World Wide Web Consortium) Extensible Markup
Language (XML) 1.0, February 1998. Available at
http://www.w3.org/TR/1998/REC-xml-19980210

previous   next   contents   index


text:
<?php
/**
 * File river view.
 */

$object = $vars['item']->getObjectEntity();
$excerpt = strip_tags($object->description);
$excerpt = thewire_filter($excerpt);

$subject = $vars['item']->getSubjectEntity();
$subject_link = elgg_view('output/url', array(
	'href' => $subject->getURL(),
	'text' => $subject->name,
	'class' => 'elgg-river-subject',
	'is_trusted' => true,
));

$object_link = elgg_view('output/url', array(
	'href' => "thewire/owner/$subject->username",
	'text' => elgg_echo('thewire:wire'),
	'class' => 'elgg-river-object',
	'is_trusted' => true,
));

$summary = elgg_echo("river:create:object:thewire", array($subject_link, $object_link));

echo elgg_view('river/elements/layout', array(
	'item' => $vars['item'],
	'message' => $excerpt,
	'summary' => $summary,
));


text:
<!DOCTYPE html>

    <title>Virtual Vinilo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <<<<<<< Updated upstream <link type="text/css" rel="stylesheet" href="css/bootstraptheme.css" />
    <link type="text/css" rel="stylesheet" href="estilos.css" /> >>>>>>> Stashed changes

    <!header>

            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

            </button>

                        <form class="navbar-form">
                            <button type="button" class="btn btn-default">

                            </button>
                        </form>

                        OFERTAS

                    {{#unlogged}}

                        USUARIO

Iniciar Sesión

Registrarse

                    {{/unlogged}}

                    {{#logged}}

                        {{#user}} {{ name }} {{/user}}

Mi Perfil

                            {{#admin}}

Administrador

                            {{/admin}}

Cerrar sesion

                    {{/logged}}

Ofertas y cupones
                    Copia el código y utiliza nuestras ofertas y cupones

       {{#ofertas}} {{>listItems2}} {{/ofertas}}

       <button id="moreArticulos"type="button" class="btn btn-primary btn-lg btn-block btn-view-more">Ver mas</button>

         {{#ofertasDescuento}} {{> listItems3}}  {{/ofertasDescuento}}

        <button id ="moreOfertasDescuento"type="button" class="btn btn-primary btn-lg btn-block btn-view-more">Ver mas</button>

Copyright © VirtualVinilo

Guillermo Urbano, Ilia Ramírez, Jorge Galindo, Daniel Camacho

Quienes Somos


text:
package com.josketres.rfcfacil;

import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;

public class HomoclaveCalculatorTest {

    @Test
    public void should_calculate_homoclave_for_simple_test_case() {

        assertThat(homoclave("Juan", "Perez", "Garcia"), equalTo("LN"));
    }

    @Test
    public void should_calculate_same_homoclave_for_names_with_and_without_accents() {

        assertThat(homoclave("Juan", "Perez", "Garcia"),
                equalTo(homoclave("Juan", "Pérez", "García")));
    }

    @Test
    public void should_calculate_homoclave_for_person_with_more_than_one_name() {

        assertThat(homoclave("Jose Antonio", "Del real", "Anzures"), equalTo("N9"));
    }

    @Test
    public void should_calculate_homoclave_for_name_with_n_with_tilde() {

        assertThat(homoclave("Juan", "Muñoz", "Ortega"), equalTo("T6"));
    }

    @Test
    public void should_calculate_homoclave_for_name_with_multiple_n_with_tilde() {

        assertThat(homoclave("Juan", "Muñoz", "Muñoz"), equalTo("RZ"));
    }

    @Test
    public void should_calculate_different_homoclave_for_name_with_n_with_tilde_and_without() {

        assertThat(homoclave("Juan", "Muñoz", "Ortega"),
                not(equalTo(homoclave("Juan", "Munoz", "Ortega"))));
    }

    @Test
    public void should_calculate_homoclave_for_name_with_u_with_umlaut() {

        assertThat(homoclave("Jesus", "Argüelles", "Ortega"), equalTo("JF"));
    }

    @Test
    public void should_calculate_same_homoclave_for_name_with_u_with_umlaut_and_without() {

        assertThat(homoclave("Jesus", "Argüelles", "Ortega"),
                equalTo(homoclave("Jesus", "Arguelles", "Ortega")));
    }

    @Test
    public void should_calculate_homoclave_for_name_with_ampersand() {

        assertThat(homoclave("Juan", "Perez&Gomez", "Garcia"), equalTo("2R"));
    }

    @Test
    public void should_calculate_same_homoclave_for_name_with_and_without_special_characters() {

        assertThat(homoclave("Juan", "Mc.Gregor", "O'Connor-Juarez"),
                equalTo(homoclave("Juan", "McGregor", "OConnorJuarez")));
    }

    @Test
    public void should_calculate_different_homoclave_for_names_with_and_without_ampersand() {

        assertThat(homoclave("Juan", "Perez&Gomez", "Garcia"),
                not(equalTo(homoclave("Juan", "PerezGomez", "Garcia"))));
    }

    @Test
    public void should_calculate_same_homoclave_for_different_birthdays() {

        assertThat(new HomoclaveCalculator(
                        new NaturalPerson("Juan", "Perez", "Garcia", 1, 1, 1901)).calculate(),
                equalTo(new HomoclaveCalculator(
                        new NaturalPerson("Juan", "Perez", "Garcia", 5, 8, 1987)).calculate()));
    }

    private String homoclave(String name, String firstLastName, String secondLastName) {

        return new HomoclaveCalculator(
                new NaturalPerson(name, firstLastName, secondLastName, 1, 1, 1901)).calculate();
    }

}


text:
using MasterDevs.ChromeDevTools;

namespace MasterDevs.ChromeDevTools.Protocol.Console
{
	/// <summary>
	/// Is not issued. Will be gone in the future versions of the protocol.
	/// </summary>
	[Event(ProtocolName.Console.MessageRepeatCountUpdated)]
	public class MessageRepeatCountUpdatedEvent
	{
		/// <summary>
		/// Gets or sets New repeat count value.
		/// </summary>
		public long Count { get; set; }
		/// <summary>
		/// Gets or sets Timestamp of most recent message in batch.
		/// </summary>
		public double Timestamp { get; set; }
	}
}


text:
var common = require('./fixtures/common')
  , request = require('request')
  , url = require('url')
  , http = require('http')
  , server

var Proxy = process.env.SPNPM_COV
  ? require('../lib-cov').Proxy
  : require('../lib').Proxy

// noop log
var log = {
  info: function() {},
  warn: function() {},
  error: function() {}
}

var options = {
  npm: url.parse('http://localhost:65000'),
  policy: {
    npm: url.parse(common.private.url),
    private: {},
    blacklist: {},
    transparent: false
  },
  log: log
}

var proxy = new Proxy(options)

describe('proxy error', function() {
  before(function(done) {
    server = http.createServer(function(req, res) {
      switch (common.url(req.url)) {
        case '/priv-basic-ok':
          proxy.private(req, res)
          break
        case '/pub-basic-ok':
          proxy.public(req, res)
          break
      }
    }).listen(common.port, done)
  })

  after(function(done) {
    server.on('close', done)
    server.close()
  })

  describe('private', function() {
    it('should proxy GET /priv-basic-ok to private registry', function(done) {
      var opts = {
        uri: common.host+'/priv-basic-ok',
        json: true
      }
      request.get(opts, common.privateOk(done))
    })

    it('should proxy PUT /priv-basic-ok to private registry', function(done) {
      var opts = {
        uri: common.host+'/priv-basic-ok',
        json: true
      }
      request.put(opts, common.privateOk(done))
    })
  })

  describe('public', function() {
    it.skip('should get proxy error on GET /pub-basic-ok', function(done) {
      var opts = {
        uri: common.host+'/pub-basic-ok',
        json: true
      }
      request.get(opts, function(err, res, body) {
        if (err) return done(err)
        // shouldn't this be a 500?
        if (res.statusCode !== 500) {
          return common.wrongStatusCode(res.statusCode, 500, done)
        }
        if (body.error !== 'proxy_error') {
          var msg = 'Request should have been gotten a proxy error'
          return done(new Error(msg))
        }
        if (body.reason !== 'connect ECONNREFUSED') {
          var msg = 'body.reason should have been `connect ECONNREFUSED`'
          return done(new Error(msg))
        }
        done()
      })
    })
    it.skip('should proxy PUT /pub-basic-ok to public registry', function(done) {
      var opts = {
        uri: common.host+'/pub-basic-ok',
        json: true
      }
      request.put(opts, function(err, res, body) {
        if (err) return done(err)
        // shouldn't this be a 500?
        if (res.statusCode !== 500) {
          return common.wrongStatusCode(res.statusCode, 500, done)
        }
        if (body.error !== 'proxy_error') {
          var msg = 'Request should have been gotten a proxy error'
          return done(new Error(msg))
        }
        if (body.reason !== 'connect ECONNREFUSED') {
          var msg = 'body.reason should have been `connect ECONNREFUSED`'
          return done(new Error(msg))
        }
        done()
      })
    })
  })
})


text:
node-mock
=========

simulate data for xdata


text:
/*
 * 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.
 */
package com.facebook.presto.hive.parquet.reader;

import com.facebook.presto.hive.parquet.RichColumnDescriptor;
import com.facebook.presto.spi.type.DecimalType;

public final class ParquetDecimalColumnReaderFactory
{
    private ParquetDecimalColumnReaderFactory() {}

    public static ParquetColumnReader createReader(RichColumnDescriptor descriptor, int precision, int scale)
    {
        DecimalType decimalType = DecimalType.createDecimalType(precision, scale);
        if (decimalType.isShort()) {
            return new ParquetShortDecimalColumnReader(descriptor);
        }
        else {
            return new ParquetLongDecimalColumnReader(descriptor);
        }
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Company = mongoose.model('Company'),
    _ = require('lodash');

/**
 * Get the error message from error object
 */
var getErrorMessage = function(err) {
    var message = '';

    if (err.code) {
        switch (err.code) {
            case 11000:
            case 11001:
                message = 'Company already exists';
                break;
            default:
                message = 'Something went wrong';
        }
    } else {
        for (var errName in err.errors) {
            if (err.errors[errName].message) message = err.errors[errName].message;
        }
    }

    return message;
};

/**
 * Создание компании
 */
exports.create = function(res, req) {
    var company = new Company();

    company.users.push({ user: req.req.user._id });
    company.email = req.req.user.email;

    company.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: getErrorMessage(err)
            });
        } else {
            req.req.session.company = company._id;
            res.res.jsonp(req.req.user);
        }
    });
};

/**
 * Ищем компанию при помощи id пользователя
 */
exports.companyByUserID = function(req, res) {
    Company.findOne({ 'users.user': req.user._id }).exec(function(err, company) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else if (!company) {
            return res.send(400, {
                message: 'Failed to load Company for user ' + req.body.email
            });
        } else {
            req.session.company = company._id;
            res.jsonp(req.user);
        }
    });
};

/**
 * Список компаний
 */
exports.list = function(req, res) {
    Company.find({ 'users.user': req.user._id }).exec(function(err, companies) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            for (var i = 0; i < companies.length; i++) {
                if (companies[i]._id.toString() === req.session.company) {
                    companies[i]._doc.active = true;
                    break;
                }
            }
            res.jsonp(companies);
        }
    });
};

/**
 * Вход в компанию
 */
exports.login = function(req, res) {
    req.session.company = req.company._id;
    res.jsonp(req.company);
};

/**
 * Проверяем авторизацию
 */
exports.hasAuthorization = function(req, res, next) {
    if (!req.user) {
        next();
    } else {
        Company.findOne({ '_id': req.session.company, 'users.user': req.user._id }).exec(function (err, company) {
            if (!company || err) {
                req.logout();
                res.redirect('/#!/signin');
            } else {
                next();
            }
        });
    }
};

/**
 * Ищем компанию с помощью id
 */
exports.companyByID = function(req, res, next, id) {
    Company.findById(id).exec(function(err, company) {
        if (err) return next(err);
        if (!company) return next(new Error('Failed to load Company ' + id));
        req.company = company;
        next();
    });
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.netapp.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.resourcemanager.netapp.fluent.models.VaultInner;

/** An instance of this class provides access to all the operations defined in VaultsClient. */
public interface VaultsClient {
    /**
     * List vaults
     *
     *
List vaults for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of Vaults as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<VaultInner> list(String resourceGroupName, String accountName);

    /**
     * List vaults
     *
     *
List vaults for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of Vaults as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<VaultInner> list(String resourceGroupName, String accountName, Context context);
}


text:
struct parameters {
	int nT = 0;					// Define length of tile width
	int nO = 0;					// Defines width of sample overlap
	int nS = 0;					// Define length of sample width
	double tileScale = 2.0 / sqrt(2.0);
};

void load_JSON_setting(std::string inFile, wangSet & tileSet, parameters & inParameters, std::vector<sample> & inSamples);
void save_JSON_results(std::string & outFile, std::string & date, double duration, double quiltError);
pixelArray convert_lightnessMap_to_pixelArray(std::vector<double> & lightnessMap, int nTx, int nTy);


text:
namespace content {
struct StorageUsageInfo;
}  // namespace content

namespace storage {
class FileSystemContext;
}  // namespace storage

namespace url {
class Origin;
}  // namespace url

// Defines an interface for classes that deal with aggregating and deleting
// media licenses.
// BrowsingDataMediaLicenseHelper instances for a specific profile should
// be created via the static Create method. Each instance will lazily fetch
// data when a client calls StartFetching from the UI thread, and will
// notify the client via a supplied callback when the data is available.
//
// The client's callback is passed a list of StorageUsageInfo objects
// containing usage information for each origin's media licenses.
class BrowsingDataMediaLicenseHelper
    : public base::RefCountedThreadSafe<BrowsingDataMediaLicenseHelper> {
 public:
  using FetchCallback =
      base::OnceCallback<void(const std::list<content::StorageUsageInfo>&)>;

  // Creates a BrowsingDataMediaLicenseHelper instance for the media
  // licenses stored in |profile|'s user data directory. The
  // BrowsingDataMediaLicenseHelper object will hold a reference to the
  // Profile that's passed in, but is not responsible for destroying it.
  //
  // The BrowsingDataMediaLicenseHelper will not change the profile itself,
  // but can modify data it contains (by removing media licenses).
  static BrowsingDataMediaLicenseHelper* Create(
      storage::FileSystemContext* file_system_context);

  // Starts the process of fetching media license data, which will call
  // |callback| upon completion, passing it a constant list of
  // StorageUsageInfo objects. StartFetching must be called only in the UI
  // thread; the provided Callback will likewise be executed asynchronously
  // on the UI thread. Obtaining the data will occur asynchronously on the
  // FILE thread.
  virtual void StartFetching(FetchCallback callback) = 0;

  // Deletes any media licenses associated with |origin| from the disk.
  // Deletion will occur asynchronously on the FILE thread, but this function
  // must be called only on the UI thread.
  virtual void DeleteMediaLicenseOrigin(const url::Origin& origin) = 0;

 protected:
  friend class base::RefCountedThreadSafe<BrowsingDataMediaLicenseHelper>;

  BrowsingDataMediaLicenseHelper() {}
  virtual ~BrowsingDataMediaLicenseHelper() {}
};

#endif  // CHROME_BROWSER_BROWSING_DATA_BROWSING_DATA_MEDIA_LICENSE_HELPER_H_


text:
package org.broadleafcommerce.common.exception;

/**
 * Base exception class for BroadleafExceptions that understands root cause messages.
 *
 * @author bpolster
 */
public abstract class BroadleafException extends Exception implements RootCauseAccessor {

    private Throwable rootCause;

    public BroadleafException() {
        super();
    }

    public BroadleafException(String message, Throwable cause) {
        super(message, cause);
        if (cause != null) {
            rootCause = findRootCause(cause);
        } else {
            rootCause = this;
        }
    }

    private Throwable findRootCause(Throwable cause) {
        Throwable rootCause = cause;
        while (rootCause != null && rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        return rootCause;
    }

    public BroadleafException(String message) {
        super(message);
        this.rootCause = this;

    }

    public BroadleafException(Throwable cause) {
        super(cause);
        if (cause != null) {
            rootCause = findRootCause(cause);
        }
    }

    public Throwable getRootCause() {
        return rootCause;
    }

    public String getRootCauseMessage() {
        if (rootCause != null) {
            return rootCause.getMessage();
        } else {
            return getMessage();
        }
    }

}