text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using DataMesh.AR.Interactive;
using DataMesh.AR.Utility;

namespace DataMesh.AR.UI
{

    /// <summary>
    /// 一个方形按钮
    /// </summary>
    public class BlockButton : MonoBehaviour
    {
        public static float[] COORDINATE_X = { 0.5f, -0.5f, -0.5f, 0.5f };
        public static float[] COORDINATE_Y = { 0.5f, 0.5f, -0.5f, -0.5f };

        /// <summary>
        /// 按钮的ID
        /// </summary>
        [HideInInspector]
        public string buttonId;

        /// <summary>
        /// 按钮的名称
        /// </summary>
        [HideInInspector]
        public string buttonName;

        /// <summary>
        /// 按钮在当前面板内所属的象限位置
        /// </summary>
        [HideInInspector]
        public QUADRANT Quadrant = QUADRANT.First;

        /// <summary>
        /// 按钮中心点的位置(基于当前面板)
        /// </summary>
        [HideInInspector]
        public Vector2 CenterPosition;

        /// <summary>
        /// 所属的面板
        /// </summary>
        [HideInInspector]
        public BlockPanel currentPanel;

        /// <summary>
        /// 链接的下一级面板,如果没有则为null
        /// </summary>
        [HideInInspector]
        public BlockPanel nextPanel;

        /// <summary>
        /// 按钮是否可以点击
        /// </summary>
        [HideInInspector]
        public bool canClick;

        /// <summary>
        /// 实际的button显示对象
        /// </summary>
        public Button uiButton;

        /// <summary>
        /// 实际的Image显示对象
        /// </summary>
        public Image uiImage;

        /// <summary>
        /// 用作点击的碰撞器
        /// </summary>
        public Collider hitCollider;

        /// <summary>
        /// 按钮正常显示和消失所使用的转场对象,在prefab里指定好,用于区分其他的转场
        /// </summary>
        public TweenerGroupTransitObject NormalTransit;

        /// <summary>
        /// 按钮点击后消失的转场对象,目前只有转出有效,转入没有用到。在prefab里指定好,用于区分其他的转场
        /// </summary>
        public TweenerGroupTransitObject ClickTransit;

        /// <summary>
        /// 按钮出现时所使用的tween对象,在prefab里直接指定比较方便
        /// </summary>
        public TweenRotation tweenRotationForShow;
        /// <summary>
        /// 焦点在按钮上时的方所效果的tween对象,在prefab里直接指定比较方便
        /// </summary>
        public TweenScale tweenScaleForPointEnter;

        [HideInInspector]
        public System.Action<BlockButton> cbClick;

        /// <summary>
        /// 所属的Menu对象
        /// </summary>
        private BlockMenu menu = null;

        private RectTransform transBlock;
        private RectTransform transButton;
        private Text btnText;

        private string txt = null;

        private int transitOutGroup = 0;

        private int pointEnterTimerKey = 0;

        private bool hasShow = false;
        private bool hiding = false;

        //private bool isHover = false;
        private MultiInputManager gm;

        public void SetText(string s)
        {
            if (btnText != null)
            {
                btnText.text = s;
            }
            else
            {
                txt = s;
            }
        }

        public bool GetHasShow()
        {
            return hasShow;
        }

        public bool IsHiding()
        {
            return hiding;
        }

        /// <summary>
        /// 初始化按钮
        /// </summary>
        /// <param name="panel"></param>
        /// <param name="q"></param>
        public void Init(BlockMenu menu, BlockPanel panel, QUADRANT q, BlockButtonData buttonData)
        {
            this.menu = menu;
            currentPanel = panel;
            Quadrant = q;

            buttonId = buttonData.buttonId;
            buttonName = buttonData.buttonName;

            canClick = buttonData.canClick;

            transBlock = transform as RectTransform;
            transBlock.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, menu.ButtonWidth);
            transBlock.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, menu.ButtonHeight);

            transButton = uiButton.transform as RectTransform;
            transButton.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, menu.ButtonWidth);
            transButton.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, menu.ButtonHeight);

            CenterPosition = new Vector2(
            (menu.ButtonWidth + menu.ButtonInterval) * COORDINATE_X[(int)q],
            (menu.ButtonHeight + menu.ButtonInterval) * COORDINATE_Y[(int)q]);

            //uiButton.onClick.AddListener(OnClick);

            // 设置按钮标题
            SetText(buttonData.buttonName);

            // 设置颜色
            SetButtonColor(buttonData.buttonColor);

            // 设置图片
            SetButtonPic("UI/Texture/" + buttonData.buttonPic);
        }

        /// <summary>
        /// 设置按钮图片,如果没有图片则设置为空白
        /// </summary>
        /// <param name="picPath"></param>
        public void SetButtonPic(string picPath)
        {
            //Debug.Log("pic:" + picPath);
            Sprite sp = null;
            if (picPath != null)
            {
                sp = Resources.Load<Sprite>(picPath);
            }
            if (sp != null)
            {
                uiImage.sprite = sp;
                uiImage.gameObject.SetActive(true);
            }
            else
            {
                uiImage.gameObject.SetActive(false);
            }
        }

        /// <summary>
        /// 设置按钮颜色。此颜色会用作按钮的普通显示颜色,高亮、按下等颜色则会根据主颜色自动生成
        /// </summary>
        /// <param name="color"></param>
        public void SetButtonColor(Color color)
        {
            Color normalColor = color;
            float h, s, v;
            Color.RGBToHSV(normalColor, out h, out s, out v);

            float v1 = v * 1.3f;
            Color highlightColor = Color.HSVToRGB(h, s, v1);

            float v2 = v * 0.8f;
            Color pressColor = Color.HSVToRGB(h, s, v2);

            //Color disableColor = Color.HSVToRGB(h, 0, v);
            Color disableColor = new Color(0.5f, 0.5f, 0.5f);

            ColorBlock btnColors = new ColorBlock();
            btnColors.normalColor = normalColor;
            btnColors.highlightedColor = highlightColor;
            btnColors.pressedColor = pressColor;
            btnColors.disabledColor = disableColor;
            btnColors.fadeDuration = uiButton.colors.fadeDuration;
            btnColors.colorMultiplier = uiButton.colors.colorMultiplier;

            uiButton.colors = btnColors;

        }

        /// <summary>
        /// 按钮每次显示之前,都需要初始化的一些内容
        /// </summary>
        public void InitToShow()
        {
            // 设置离开方式为普通
            transitOutGroup = 0;

            ClickTransit.resetTransit(false);
            NormalTransit.resetTransit(true);

            if (tweenScaleForPointEnter.direction != TweenDirection.Forward)
            {
                tweenScaleForPointEnter.Toggle();
            }
            tweenScaleForPointEnter.ResetToBeginning();
            tweenScaleForPointEnter.enabled = false;
        }

        /// 根据输入的按钮出现顺序,设置一个按钮的基准点和实际位置
        /// </summary>
        /// <param name="qFrom">从哪个象限出发</param>
        public void SetShowDirection(QUADRANT qFrom)
        {
            QUADRANT qTo = this.Quadrant;

            float dx = COORDINATE_X[(int)qFrom] - COORDINATE_X[(int)qTo];
            float dy = COORDINATE_Y[(int)qFrom] - COORDINATE_Y[(int)qTo];

            // 设置重心
            Vector2 pivot;
            pivot.x = ((dx * 0.5f) + 0.5f);
            pivot.y = ((dy * 0.5f) + 0.5f);
            transBlock.pivot = pivot;

            // 设置位置
            Vector3 pos;
            pos.x = CenterPosition.x + (pivot.x - 0.5f) * menu.ButtonWidth;
            pos.y = CenterPosition.y + (pivot.y - 0.5f) * menu.ButtonHeight;
            pos.z = 0;
            transBlock.localPosition = pos;

            // 设置转场
            tweenRotationForShow.from.x = dy * 90;
            tweenRotationForShow.from.y = dx * 90;

            //Debug.Log(" " + qFrom + " -> " + Quadrant);
            //Debug.Log("center=" + CenterPosition);
            //Debug.Log("pivot=" + pivot);
            //Debug.Log("pos=" + pos);

        }

        // Use this for initialization
        void Awake()
        {

            btnText = uiButton.GetComponentInChildren<Text>();
            if (txt != null)
            {
                btnText.text = txt;
                txt = null;
            }

        }

        void Start()
        {
            gm = MultiInputManager.Instance;
        }

        /// <summary>
        /// 焦点进入时的处理
        /// </summary>
        /// <param name="eventData"></param>
        public void OnGazeEnterObject()
        {
            if (!currentPanel.GetHasShow())
                return;

            // 播放动画
            tweenScaleForPointEnter.PlayForward();

            // 准备打开子面板
            if (nextPanel != null)
            {
                if (pointEnterTimerKey <= 0)
                {
                    pointEnterTimerKey = TimerManager.Instance.RegisterTimer(TimerShowNextPanel, 0.2f, 1);
                }
            }

            // 检查同级其他按钮,如果有面板,则关闭
            BlockPanel p = this.currentPanel;
            p.HideOthersSubPanel(this.Quadrant);

            if (nextPanel != null)
                nextPanel.SetKeepShow(true);

            currentPanel.SetKeepShow(true);

            if (canClick)
            {
                menu.uiCanBeClick = true;
            }

            // 这里屏蔽GazeGestureManager
            //GazeGestureManager.Instance.StopCapture();
        }

        private void TimerShowNextPanel(Hashtable param)
        {
            nextPanel.Show();
            nextPanel.cbHide += OnSubPanelClose;
            pointEnterTimerKey = 0;

            // 如果按钮不可点,就变更颜色
            if (!canClick)
            {
                uiButton.interactable = false;
            }

        }

        private void OnSubPanelClose()
        {
            // 如果按钮不可点,就变更颜色
            if (!canClick)
            {
                uiButton.interactable = true;
            }
            nextPanel.cbHide -= OnSubPanelClose;
        }

        /// <summary>
        /// 焦点离开时的处理
        /// </summary>
        /// <param name="eventData"></param>
        public void OnGazeExitObject()
        {
            if (pointEnterTimerKey > 0)
            {
                TimerManager.Instance.RemoveTimer(pointEnterTimerKey);
                pointEnterTimerKey = 0;
            }

            if (!currentPanel.GetHasShow())
                return;

            tweenScaleForPointEnter.PlayReverse();

            menu.NeedHide();

            if (nextPanel != null)
                nextPanel.SetKeepShow(false);

            if (canClick)
            {
                menu.uiCanBeClick = false;
            }

            /*
            if (nextPanel != null)
            {
                nextPanel.Hide();
            }
            */

            //GazeGestureManager.Instance.StartCapture();

        }

        /// <summary>
        /// 点击按钮的处理
        /// </summary>
        public void OnTapOnObject()
        {
            if (!currentPanel.GetHasShow())
                return;

            if (!canClick)
                return;

            // 如果还在转场,则不能点
            if (NormalTransit.isBusy())
                return;

            //Debug.Log("click");

            // 点击后,设置离开方式为点击离开
            transitOutGroup = 1;

            menu.clickedButtonId = this.buttonId;

            menu.NeedHideImmediately();

            //TimerManager.Instance.RegisterTimer(DoClick, 0.5f, 1);
        }

        /*
        private void DoClick(Hashtable param)
        {

            if (cbClick != null)
            {
                cbClick(this);
            }
        }
        */

        /// <summary>
        /// 给按钮添加下一级面板
        /// </summary>
        /// <param name="next"></param>
        public void AddNextPanel(BlockPanel next)
        {
            this.nextPanel = next;
            next.parentButton = this;

            Vector3 pos = Vector3.zero;
            pos.x = currentPanel.centerPosition.x + CenterPosition.x + COORDINATE_X[(int)Quadrant] * (menu.ButtonWidth + menu.ButtonInterval);
            pos.y = currentPanel.centerPosition.y + CenterPosition.y + COORDINATE_Y[(int)Quadrant] * (menu.ButtonHeight + menu.ButtonInterval);

            next.centerPosition = pos;
        }

        /// <summary>
        /// 显示一个按钮,播放出现动画
        /// </summary>
        /// <param name="delay">显示延迟,单位为秒</param>
        public void Show(float delay)
        {
            NormalTransit.resetTransit(true);
            NormalTransit.delayType = TransitDelayType.WaitForTime;
            NormalTransit.delayTime = delay;

            TransitObject.StartTransit(this.gameObject, 0, true);

            hasShow = true;
            hiding = false;

            //Debug.Log("Begin show!");
        }

        // 隐藏一个按钮,播放关闭动画
        public void Hide()
        {
            if (pointEnterTimerKey > 0)
            {
                TimerManager.Instance.RemoveTimer(pointEnterTimerKey);
                pointEnterTimerKey = 0;
            }
            hiding = true;
            //Debug.Log("Begin Hide!");
            TransitObject.StartTransit(this.gameObject, transitOutGroup, false, HideFinish);
        }

        private void HideFinish()
        {
            //Debug.Log("=-============ Hide!");
            hasShow = false;
            hiding = false;
        }

        void Update()
        {
            /*
            if (isHover)
            {
                if (gm.hitCollider != this.hitCollider)
                {
                    isHover = false;
                    //Debug.Log("exit!");
                    OnPointerExit();
                }
            }
            else
            {
                if (gm.hitCollider == this.hitCollider)
                {
                    isHover = true;
                    //Debug.Log("Enter");
                    OnPointerEnter();
                }
            }
            */
        }
    }
}


text:
'use strict';
angular.module('candyflixAngularApp')
  .service('Watchlist', function() {
    this.movies = [];
    function save(movies) {
      localStorage.setItem('movies', JSON.stringify(movies));
    }
    this.add = function(movie) {
      this.movies.push(movie);
      save(this.movies);
    }
    this.delete = function(movie) {
      this.movies.splice(movie, 1);
      save(this.movies);
    }
    this.load = function() {
      this.movies = JSON.parse(localStorage.getItem('movies')) || []
    }
  });

redpajama_set_name: RedPajamaGithub


text:
namespace XBindLecture.DataSets
{
	public sealed class Person
	{
		public string Name { get; }
		public ushort Age { get; }
		public SexType Sex { get; }

		public Person(string name, ushort age, SexType sex)
		{
			this.Name = name;
			this.Age = age;
			this.Sex = sex;
		}
	}
}


text:
import hammerhead from './deps/hammerhead';
import * as eventUtils from './utils/event';
import delay from './utils/delay';
import MESSAGE from '../../test-run/client-messages';
import { isAnchorElement } from './utils/dom';

const Promise       = hammerhead.Promise;
const browserUtils  = hammerhead.utils.browser;
const nativeMethods = hammerhead.nativeMethods;
const transport     = hammerhead.transport;

const DEFAULT_BARRIER_TIMEOUT       = 400;
const SHORT_WAIT_FOR_UNLOAD_TIMEOUT = 30;
const FILE_DOWNLOAD_CHECK_DELAY     = 500;
const MAX_UNLOADING_TIMEOUT         = 15 * 1000;

let waitingForUnload          = false;
let waitingForUnloadTimeoutId = null;
let waitingPromiseResolvers   = [];
let unloading                 = false;

let pageNavigationTriggeredListener = null;
let pageNavigationTriggered         = false;

function onBeforeUnload () {
    if (!browserUtils.isIE) {
        unloading = true;
        return;
    }

    prolongUnloadWaiting(SHORT_WAIT_FOR_UNLOAD_TIMEOUT);

    delay(0)
        .then(() => {
            // NOTE: except file downloading
            if (document.readyState === 'loading') {
                const activeElement = nativeMethods.documentActiveElementGetter.call(document);

                if (!activeElement || !isAnchorElement(activeElement) || !activeElement.hasAttribute('download'))
                    unloading = true;
            }
        });
}

function prolongUnloadWaiting (timeout) {
    if (waitingForUnloadTimeoutId)
        nativeMethods.clearTimeout.call(window, waitingForUnloadTimeoutId);

    waitingForUnload = true;

    waitingForUnloadTimeoutId = nativeMethods.setTimeout.call(window, () => {
        waitingForUnloadTimeoutId = null;
        waitingForUnload          = false;

        waitingPromiseResolvers.forEach(resolve => resolve());
        waitingPromiseResolvers = [];
    }, timeout);
}

function waitForFileDownload () {
    return new Promise(resolve => {
        nativeMethods.setTimeout.call(window, () => {
            transport
                .queuedAsyncServiceMsg({ cmd: MESSAGE.waitForFileDownload })
                .then(fileDownloadingHandled => {
                    // NOTE: we use a flag to confirm file download because if unload
                    // is raised the browser can respond with an empty string
                    if (fileDownloadingHandled)
                        resolve();
                });

        }, FILE_DOWNLOAD_CHECK_DELAY);
    });
}

// API
export function init () {
    hammerhead.on(hammerhead.EVENTS.beforeUnload, onBeforeUnload);

    eventUtils.bind(window, 'unload', () => {
        unloading = true;
    });
}

export function watchForPageNavigationTriggers () {
    pageNavigationTriggeredListener = () => {
        pageNavigationTriggered = true;
    };

    hammerhead.on(hammerhead.EVENTS.pageNavigationTriggered, pageNavigationTriggeredListener);
}

export function wait (timeout) {
    const waitForUnloadingPromise = new Promise(resolve => {
        if (timeout === void 0)
            timeout = !pageNavigationTriggeredListener || pageNavigationTriggered ? DEFAULT_BARRIER_TIMEOUT : 0;

        if (pageNavigationTriggeredListener) {
            hammerhead.off(hammerhead.EVENTS.pageNavigationTriggered, pageNavigationTriggeredListener);
            pageNavigationTriggeredListener = null;
        }

        delay(timeout)
            .then(() => {
                if (unloading) {
                    waitForFileDownload()
                        .then(() => {
                            unloading = false;
                            resolve();
                        });

                    return;
                }

                if (!waitingForUnload)
                    resolve();
                else
                    waitingPromiseResolvers.push(resolve);
            });
    });

    // NOTE: sometimes the page isn't actually unloaded after the beforeunload event
    // fires (see issues #664, #437). To avoid test hanging, we resolve the unload
    // barrier waiting promise in MAX_UNLOADING_TIMEOUT. We can improve this logic when
    // the https://github.com/DevExpress/testcafe-hammerhead/issues/667 issue is fixed.
    const watchdog = delay(MAX_UNLOADING_TIMEOUT)
        .then(() => {
            unloading = false;
        });

    return Promise.race([waitForUnloadingPromise, watchdog]);
}


text:
import unittest
from unittest import mock
import twstock
from twstock import realtime
import responses
from requests.exceptions import ProxyError, InvalidURL
import json
try:
    from json.decoder import JSONDecodeError
except ImportError:
    JSONDecodeError = ValueError
import sys

# import logging
# from pprint import pprint
# # 顯示 DEBUG 訊息
# # logging.basicConfig(level=logging.DEBUG)

class RealtimeTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.FETCH_URL = {
            '2330' : 'http://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=tse_2330.tw&_=1500861243000',
            '6223' : 'http://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=otc_6223.tw&_=1500861243000',
            '2330_6223' : 'http://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=tse_2330.tw%7Cotc_6223.tw&_=1500861243000'
        }

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_realtime_field(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            json=twstock.mock.get_stock_info('2330'),
            status=200
        )
        stock = realtime.get_raw('2330')

        self.assertCountEqual(
            stock.keys(),
            twstock.mock.get_stock_info('2330').keys())

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_realtime_get_raw(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            json=twstock.mock.get_stock_info('2330'),
            status=200
        )
        stock = realtime.get_raw('2330')

        self.assertIn('msgArray', stock)

    def test_realtime_get_blank(self):
        realtime.proxies_list = []
        stock = realtime.get('')

        self.assertFalse(stock['success'])
        self.assertIn('rtmessage', stock)
        self.assertIn('rtcode', stock)

    def test_realtime_get_bad_id(self):
        realtime.proxies_list = []
        stock = realtime.get('9999')

        self.assertFalse(stock['success'])
        self.assertIn('rtmessage', stock)
        self.assertIn('rtcode', stock)

        stock = realtime.get(['9999', '8888'])

        self.assertFalse(stock['success'])
        self.assertIn('rtmessage', stock)
        self.assertIn('rtcode', stock)

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_realtime_get_tpex_id(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['6223'],
            json=twstock.mock.get_stock_info('6223'),
            status=200
        )
        stock = realtime.get('6223')

        self.assertTrue(stock['success'])
        self.assertEqual(stock['info']['code'], '6223')

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_realtime_multiple_stock_id(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330_6223'],
            json=twstock.mock.get_stock_info('2330_6223'),
            status=200
        )
        stock = realtime.get(['2330', '6223'])

        self.assertTrue(stock['success'])
        self.assertIn('2330', stock)
        self.assertTrue(stock['2330']['success'])
        self.assertEqual(stock['2330']['info']['code'], '2330')
        self.assertIn('6223', stock)
        self.assertTrue(stock['6223']['success'])
        self.assertEqual(stock['6223']['info']['code'], '6223')

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_realtime_get_response_with_wrong_id(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            json=twstock.mock.get_stock_info('error_code'),
            status=200
        )
        stock = realtime.get('2330')
        self.assertFalse(stock['success'])
        self.assertIn('rtmessage', stock)
        self.assertIn('rtcode', stock)
        self.assertEqual(stock['rtcode'], '5004')

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_realtime_get_response_without_msg_array(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            json=twstock.mock.get_stock_info('without_msg_array'),
            status=200
        )
        stock = realtime.get('2330')
        self.assertFalse(stock['success'])
        self.assertIn('rtmessage', stock)
        self.assertIn('rtcode', stock)

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_realtime_get_response_empty_msg_array(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            json=twstock.mock.get_stock_info('empty_msg_array'),
            status=200
        )
        stock = realtime.get('2330')
        self.assertFalse(stock['success'])
        self.assertIn('rtmessage', stock)
        self.assertIn('rtcode', stock)
        self.assertEqual(stock['rtcode'], '5001')

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_raises_json_decode_error(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            body='{json:wrong',
            status=200
        )
        stock = realtime.get('2330')

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_raises_timeout_error(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            body=TimeoutError('Unittest Mock TimeoutError!!'),
            status=200
        )
        stock = realtime.get('2330')

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_raises_unexpected_error(self):
        realtime.proxies_list = []
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            body=InvalidURL('Unittest Mock InvalidURL!!'),
            status=200
        )
        self.assertRaises(InvalidURL, realtime.get, '2330')

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_proxy_raises_proxy_error(self):
        realtime.proxies_list = [
            'http://0.0.0.0:1234',
            'http://0.0.0.0:3128',
        ]
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            body=ProxyError('Unittest Mock ProxyError!!'),
            status=200
        )
        stock = realtime.get('2330')

    @responses.activate
    @mock.patch('time.time', mock.MagicMock(return_value=1500861243))
    def test_proxy(self):
        realtime.proxies_list = [
            'http://128.199.165.29:8888',
            'http://128.199.195.200:8080',
            'socks5://207.180.233.152:50775',
        ]
        responses.add(
            responses.GET,
            'http://mis.twse.com.tw/stock/index.jsp',
            status=200
        )
        responses.add(
            responses.GET,
            self.FETCH_URL['2330'],
            json=twstock.mock.get_stock_info('2330'),
            status=200
        )
        stock = realtime.get('2330')

class MockRealtimeTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        realtime.mock = True

    @classmethod
    def tearDownClass(cls):
        realtime.mock = False

    def test_mock_one_stock_id(self):
        mock_stock = realtime.get('2330')

        self.assertTrue(mock_stock['success'])
        self.assertEqual(mock_stock['info']['code'], '2330')
        self.assertEqual(mock_stock['realtime']['latest_trade_price'], '214.50')
        self.assertEqual(mock_stock['realtime']['best_bid_price'],
                         ['214.00', '213.50', '213.00', '212.50', '212.00'])

    @unittest.skip('Dont want to fix this, is about the code in realtime')
    def test_mock_multiple_stock_id(self):
        mock_stock = realtime.get(['2330', '2337'])

        self.assertTrue(mock_stock['success'])
        self.assertCountEqual(mock_stock.keys(), ['2330', '2337', 'success'])
        self.assertTrue(mock_stock['2330']['success'])
        self.assertEqual(mock_stock['2330']['info']['code'], '2330')
        self.assertEqual(mock_stock['2330']['realtime']['latest_trade_price'], '214.50')
        self.assertTrue(mock_stock['2337']['success'])


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_item_layout"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/grid_image"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:background="@color/primary_dark_material_light"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


text:
standalone script
====================

It is possible to create ``doit`` as a standalone python script including ``doit`` source code and its dependencies. This way it is easy to include this file in your project and use doit without going through the installation process.

Requirements
--------------

The standalone script should be created on a system where doit and dependencies are
installed. Apart from doit dependencies it also requires the the libraries "py" and "py.test".

Usage
-------

The script ``genstandalone.py`` will create a standalone 'doit' on the current working directory. So it should be executed in the path where the standalone will be distributed, i.e.::

  /my/project/path $ python ../../path/to/doit/genstandalone.py

Then you can distribute the standalone script to other systems.

.. warning::

  The generated standalone script can be used by any python version but the
  dependencies included are dependent on the python version used to generate
  the standalone script.


text:
import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16 #paInt8
CHANNELS = 2
RATE = 44100 #sample rate
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
				output=True,
                frames_per_buffer=CHUNK) #buffer

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data) # 2 bytes(16 bits) per channel

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'rb')

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
				channels=wf.getnchannels(),
				rate=wf.getframerate(),
				output=True)

data = wf.readframes(CHUNK)

loop = True

while loop :
	stream.write(data)
	data = wf.readframes(CHUNK)
	print(data)
	if data == '' : # If file is over then rewind.
		print("do we enter?")
		print(data)
		wf.rewind()
		data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()

p.terminate()


text:
"""
Normalize Array
~~~~~~~~~~~~~~~

This example will demonstrate how to perform a normalization or any custom
mathematical operation on a single data array for an input data set.

This filter allow the user to select an array from the input data set to be
normalized. The filter will append another array to that data set for the
output. The user can specify how they want to rename the array, can choose a
multiplier, and can choose from two types of common normalizations:
Feature Scaling and Standard Score.

This example demos :class:`PVGeo.filters.NormalizeArray`

"""
import numpy as np
import pyvista
from pyvista import examples
import PVGeo
from PVGeo.filters import NormalizeArray

###############################################################################
# Create some input data. this can be any `vtkDataObject`
mesh = examples.load_uniform()
title = 'Spatial Point Data'
mesh.plot(scalars=title)
###############################################################################

# Apply the filter
f = NormalizeArray(normalization='feature_scale', new_name='foo')
output = f.apply(mesh, title)
print(output)

###############################################################################
output.plot(scalars='foo')


text:
<?php

namespace Mc\CollegeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ChuckController extends Controller
{
    public function indexAction()
    {

    	$programs = $this->getDoctrine()
    	                 ->getRepository('McAdminBundle:Program')
    	                 ->createQueryBuilder('p')
    	                 ->select('p')
    	                 ->orderBy('p.sortId' , 'asc')
    	                 ->getQuery()
    	                 ->getResult();

        if( $this->get('user.status')->getId() )
        {
            $selected = $this->getDoctrine()
                             ->getRepository('McAdminBundle:Selected')
                             ->createQueryBuilder('s')
                             ->select('s.id , s.active , s.programId , s.startDate')
                             ->where('s.userId = :userId')
                             ->setParameter( 'userId' , $this->get('user.status')->getId() )
                             ->getQuery()->getArrayResult();

            $temp = array();
            foreach ($selected as $key => $value) {
                $temp[$value['programId']] = $value ;
            }

        }

    	return $this->render('McCollegeBundle:Chuck:index.html.twig' ,
            array ( 'programs' => $programs ,
                    'selected' => array( 'items'=> isset( $temp) ? $temp : null ) ,

                  )
        );
    }

}


text:
#pragma once

#pragma once

#include "ofMain.h"
#include "ofxJSON.h"
#include "ofxCsv.h"

#define RECONNECTING_TIME 5000
#define READABLE_FRAMERATE 200

struct targetData {
	int64_t id;
	int distance;
	int angleDegree; //Neg values (left), Positive values (right)
	int speedKm;
	int strength;
};

class ofxRadarGlxRss3 {
public:
	ofxRadarGlxRss3();
    void setup();
	void update();
	void updateOnlineRadarData();
    void draw();
	ofxJSONElement jsonRadar;
	ofxJSONElement jsonRecordingRadar;
	ofxJSONElement jsonSimulationRadar;

	void startPlaying();
	bool isPlaying();
	bool isRecording();
	void startRecorging();
	void stopRecorging();

	void setupRadar();

	void playSimFile(int _idPosFileInFolder);
	int getNumSimFiles();

private:

	bool parsingSuccessful = false;

	//Area Radar
	void defineIdealRadarArea();
	ofPolyline radarAreaEffective;
	void drawIdealAreaTracking(int x, int y);

	//Tracking Info
	void drawRawTextRadarInfo();
	void drawRawTextRadarDetection();
	void drawBlobsCartesian(int x, int y);

	void radarPolarToCartesian();
	vector<ofVec2f> cartesianRadar;
	ofVec2f transformPolarToCartesian(float _distance, float _angleDegree);

	void readJsonDataRadar();
	void parseJsonDataRadar();//Radar
	void parseJsonDataRadar(ofxJSONElement jsonRadar);//SimulationRadar

	int timerReader = 0;
	std::string url;
	std::string textStatusRadar;

	vector<targetData> targetsData;
	std::string stargetResumedData;

	//Radar Related Data
	float sensorScale = 2;
	float sensorMaxDistance = 0;

	float sensorHeight = 0;
	float sensorWidth = 0;
	float sensorAccurateHeight = 0;

	int angleMaxRadar = 40;

	//Save Load Simulation
	string fileName = "default.json";

	//write
	void updateRecording();
	bool bRecording = false;
	bool bStartRecording = false;
	int framesRecorded = 0;
	//read
	bool bPlaying = false;
	bool bStartPlaying= false;
	ofxJSONElement readingSimulationRadar();
	int counterFramesSimulation = 0;
	int totalFramesSimulation = 0;

	ofDirectory myDataFolder;
	int idActualSimulatorIter = 0;

};

/*
Improve reading CVS
https://forum.openframeworks.cc/t/large-csv-file/9006/4

Thanks for your help. FYI I guess I have found the fastest possible way for my situation. I just wrote a little program to convert CSV files to binary files and used below code to read it:

fstream myFile ((ofToString(currentFrame) + ".bin").c_str(), ios::in | ios::binary);
myFile.seekg(0);

int num_points;
myFile.read ((char*)&num_points, sizeof (int));

allPoints = new pointData[num_points];

myFile.read ((char*)allPoints, sizeof (pointData) * num_points);

myFile.close();

Before it was about 7 frames (files) per second, now it is around 300 fps.

*/


text:
[View Javadoc](../../../../../../apidocs/org/apache/struts/chain/contexts/ContextWrapper.html.md)

    1
    21  package org.apache.struts.chain.contexts;
    22
    23  import org.apache.commons.chain.Context;
    24
    25  import java.util.Collection;
    26  import java.util.Map;
    27  import java.util.Set;
    28
    29  /**
    30   *
 Provide a base class for any Context Implementation which is primarily
    31   * intended for use in a subchain.

 Classes which extend
    32   * ContextWrapper may implement typesafe property methods which
    33   * also leave their values in the underlying context.

    34   */
    35  public class ContextWrapper implements Context {
    36      private Context base;
    37
    38      /**
    39       *
 Instantiate object as a composite around the given Context.

    40       *
    41       * @param context Context instance to wrap
    42       */
    43      public ContextWrapper(Context context) {
    44          this.base = context;
    45      }
    46
    47      /**
    48       * Provide the underlying Context for this composite.
    49       *
    50       * @return The undelrying Context
    51       */
    52      protected Context getBaseContext() {
    53          return this.base;
    54      }
    55
    56      // -------------------------------
    57      // Map interface methods
    58      // -------------------------------
    59      public Set entrySet() {
    60          return this.base.entrySet();
    61      }
    62
    63      public Set keySet() {
    64          return this.base.keySet();
    65      }
    66
    67      public Collection values() {
    68          return this.base.values();
    69      }
    70
    71      public void clear() {
    72          this.base.clear();
    73      }
    74
    75      public void putAll(Map map) {
    76          // ISSUE: Should we check this call to putAll?
    77          this.base.putAll(map);
    78      }
    79
    80      public Object remove(Object key) {
    81          return this.base.remove(key);
    82      }
    83
    84      public Object put(Object key, Object value) {
    85          // ISSUE: Should we check this call to put?
    86          return this.base.put(key, value);
    87      }
    88
    89      public Object get(Object key) {
    90          return this.base.get(key);
    91      }
    92
    93      public boolean containsValue(Object o) {
    94          return this.base.containsValue(o);
    95      }
    96
    97      public boolean containsKey(Object o) {
    98          return this.base.containsKey(o);
    99      }
    100
    101     public boolean isEmpty() {
    102         return this.base.isEmpty();
    103     }
    104
    105     public int size() {
    106         return this.base.size();
    107     }
    108 }

------------------------------------------------------------------------

This page was automatically generated by [Maven](http://maven.apache.org/)


text:
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using Drumble.DomainDrivenArchitecture.Infrastructure.EntityFramework;
using System.ComponentModel.DataAnnotations.Schema;

namespace AppCampus.Infrastructure.Models
{
    [Table("LogFile")]
	[GeneratedCode("EntityFrameworkCodeGeneration", "6.1.1")]
    public partial class LogFileTable : IDataEntity<Guid>
    {
        public LogFileTable()
        {
            this.DeviceLogs = new List<DeviceLogTable>();
        }

        [Column("LogFileId")]
		public System.Guid Id { get; set; }

        [Column("Binary")]
		public byte[] Binary { get; set; }

        public virtual ICollection<DeviceLogTable> DeviceLogs { get; set; }

    }
}


text:
package library

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"path"
	"strings"
	"text/tabwriter"
	"time"

	"github.com/vmware/govmomi/govc/cli"
	"github.com/vmware/govmomi/govc/flags"
	"github.com/vmware/govmomi/object"
	"github.com/vmware/govmomi/units"
	"github.com/vmware/govmomi/vapi/library"
	"github.com/vmware/govmomi/vapi/library/finder"

	"github.com/vmware/govmomi/property"
	"github.com/vmware/govmomi/vim25/mo"
	"github.com/vmware/govmomi/vim25/types"
)

type info struct {
	*flags.ClientFlag
	*flags.OutputFlag
	*flags.DatacenterFlag

	long bool
	link bool
	url  bool

	names map[string]string
}

func init() {
	cli.Register("library.info", &info{})
}

func (cmd *info) Register(ctx context.Context, f *flag.FlagSet) {
	cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
	cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
	cmd.ClientFlag.Register(ctx, f)
	cmd.OutputFlag.Register(ctx, f)
	cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
	cmd.DatacenterFlag.Register(ctx, f)

	f.BoolVar(&cmd.long, "l", false, "Long listing format")
	f.BoolVar(&cmd.link, "L", false, "List Datastore path only")
	f.BoolVar(&cmd.url, "U", false, "List pub/sub URL(s) only")

	cmd.names = make(map[string]string)
}

func (cmd *info) Process(ctx context.Context) error {
	if err := cmd.ClientFlag.Process(ctx); err != nil {
		return err
	}
	return nil
}

func (cmd *info) Description() string {
	return `Display library information.

Examples:
  govc library.info
  govc library.info /lib1
  govc library.info -l /lib1 | grep Size:
  govc library.info /lib1/item1
  govc library.info /lib1/item1/
  govc library.info */
  govc device.cdrom.insert -vm $vm -device cdrom-3000 $(govc library.info -L /lib1/item1/file1)
  govc library.info -json | jq .
  govc library.info -json /lib1/item1 | jq .`
}

type infoResultsWriter struct {
	Result []finder.FindResult
	m      *library.Manager
	cmd    *info
}

func (r infoResultsWriter) MarshalJSON() ([]byte, error) {
	return json.Marshal(r.Result)
}

func (r infoResultsWriter) Dump() interface{} {
	res := make([]interface{}, len(r.Result))
	for i := range r.Result {
		res[i] = r.Result[0].GetResult()
	}
	return res
}

func (r infoResultsWriter) Write(w io.Writer) error {
	if r.cmd.link {
		for _, j := range r.Result {
			p, err := r.cmd.getDatastoreFilePath(j)
			if err != nil {
				return err
			}
			if !r.cmd.long {
				var path object.DatastorePath
				path.FromString(p)
				p = path.Path
			}
			fmt.Fprintln(w, p)
		}
		return nil
	}

	tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
	defer tw.Flush()
	for _, j := range r.Result {
		switch t := j.GetResult().(type) {
		case library.Library:
			if err := r.writeLibrary(tw, t, j); err != nil {
				return err
			}
		case library.Item:
			if err := r.writeItem(tw, t, j); err != nil {
				return err
			}
		case library.File:
			if err := r.writeFile(tw, t, j); err != nil {
				return err
			}
		}
		tw.Flush()
	}
	return nil
}

func (r infoResultsWriter) writeLibrary(
	w io.Writer, v library.Library, res finder.FindResult) error {

	published := v.Publication != nil && *v.Publication.Published

	if r.cmd.url {
		switch {
		case v.Subscription != nil:
			_, _ = fmt.Fprintf(w, "%s\n", v.Subscription.SubscriptionURL)
		case published:
			_, _ = fmt.Fprintf(w, "%s\n", v.Publication.PublishURL)
		}

		return nil
	}

	fmt.Fprintf(w, "Name:\t%s\n", v.Name)
	fmt.Fprintf(w, "  ID:\t%s\n", v.ID)
	fmt.Fprintf(w, "  Path:\t%s\n", res.GetPath())
	fmt.Fprintf(w, "  Description:\t%s\n", v.Description)
	fmt.Fprintf(w, "  Version:\t%s\n", v.Version)
	fmt.Fprintf(w, "  Created:\t%s\n", v.CreationTime.Format(time.ANSIC))
	fmt.Fprintf(w, "  Security Policy ID\t%s\n", v.SecurityPolicyID)
	fmt.Fprintf(w, "  StorageBackings:\t\n")
	for _, d := range v.Storage {
		fmt.Fprintf(w, "    DatastoreID:\t%s\n", d.DatastoreID)
		fmt.Fprintf(w, "    Type:\t%s\n", d.Type)
	}
	if r.cmd.long {
		fmt.Fprintf(w, "  Datastore Path:\t%s\n", r.cmd.getDatastorePath(res))
		items, err := r.m.GetLibraryItems(context.Background(), v.ID)
		if err != nil {
			return err
		}
		var size int64
		for i := range items {
			size += items[i].Size
		}
		fmt.Fprintf(w, "  Size:\t%s\n", units.ByteSize(size))
		fmt.Fprintf(w, "  Items:\t%d\n", len(items))
	}
	if v.Subscription != nil {
		dl := "All"
		if v.Subscription.OnDemand != nil && *v.Subscription.OnDemand {
			dl = "On Demand"
		}

		fmt.Fprintf(w, "  Subscription:\t\n")
		fmt.Fprintf(w, "    AutoSync:\t%t\n", *v.Subscription.AutomaticSyncEnabled)
		fmt.Fprintf(w, "    URL:\t%s\n", v.Subscription.SubscriptionURL)
		fmt.Fprintf(w, "    Auth:\t%s\n", v.Subscription.AuthenticationMethod)
		fmt.Fprintf(w, "    Download:\t%s\n", dl)
	}
	if published {
		fmt.Fprintf(w, "  Publication:\t\n")
		fmt.Fprintf(w, "    URL:\t%s\n", v.Publication.PublishURL)
		fmt.Fprintf(w, "    Auth:\t%s\n", v.Publication.AuthenticationMethod)
	}
	return nil
}

func (r infoResultsWriter) writeItem(
	w io.Writer, v library.Item, res finder.FindResult) error {

	fmt.Fprintf(w, "Name:\t%s\n", v.Name)
	fmt.Fprintf(w, "  ID:\t%s\n", v.ID)
	fmt.Fprintf(w, "  Path:\t%s\n", res.GetPath())
	fmt.Fprintf(w, "  Description:\t%s\n", v.Description)
	fmt.Fprintf(w, "  Type:\t%s\n", v.Type)
	fmt.Fprintf(w, "  Size:\t%s\n", units.ByteSize(v.Size))
	fmt.Fprintf(w, "  Created:\t%s\n", v.CreationTime.Format(time.ANSIC))
	fmt.Fprintf(w, "  Modified:\t%s\n", v.LastModifiedTime.Format(time.ANSIC))
	fmt.Fprintf(w, "  Version:\t%s\n", v.Version)

	if r.cmd.long {
		fmt.Fprintf(w, "  Datastore Path:\t%s\n", r.cmd.getDatastorePath(res))
	}

	return nil
}

func (r infoResultsWriter) writeFile(
	w io.Writer, v library.File, res finder.FindResult) error {

	size := "-"
	if v.Size != nil {
		size = units.ByteSize(*v.Size).String()
	}
	fmt.Fprintf(w, "Name:\t%s\n", v.Name)
	fmt.Fprintf(w, "  Path:\t%s\n", res.GetPath())
	fmt.Fprintf(w, "  Size:\t%s\n", size)
	fmt.Fprintf(w, "  Version:\t%s\n", v.Version)

	if r.cmd.long {
		fmt.Fprintf(w, "  Datastore Path:\t%s\n", r.cmd.getDatastorePath(res))
	}

	return nil
}

func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
	c, err := cmd.RestClient()
	if err != nil {
		return err
	}

	m := library.NewManager(c)
	finder := finder.NewFinder(m)
	findResults, err := finder.Find(ctx, f.Args()...)
	if err != nil {
		return err
	}
	// Lookup the names(s) of the library's datastore(s).
	for i := range findResults {
		if t, ok := findResults[i].GetResult().(library.Library); ok {
			for j := range t.Storage {
				if t.Storage[j].Type == "DATASTORE" {
					t.Storage[j].DatastoreID = cmd.getDatastoreName(t.Storage[j].DatastoreID)
				}
			}
		}
	}
	return cmd.WriteResult(&infoResultsWriter{findResults, m, cmd})
}

func (cmd *info) getDatastoreName(id string) string {
	if name, ok := cmd.names[id]; ok {
		return name
	}

	c, err := cmd.Client()
	if err != nil {
		return id
	}

	obj := types.ManagedObjectReference{
		Type:  "Datastore",
		Value: id,
	}
	pc := property.DefaultCollector(c)
	var me mo.ManagedEntity

	err = pc.RetrieveOne(context.Background(), obj, []string{"name"}, &me)
	if err != nil {
		return id
	}

	cmd.names[id] = me.Name
	return me.Name
}

func (cmd *info) getDatastorePath(r finder.FindResult) string {
	p, _ := cmd.getDatastoreFilePath(r)
	return p
}

func (cmd *info) getDatastoreFilePath(r finder.FindResult) (string, error) {
	switch x := r.GetResult().(type) {
	case library.Library:
		id := ""
		if len(x.Storage) != 0 {
			id = cmd.getDatastoreName(x.Storage[0].DatastoreID)
		}
		return fmt.Sprintf("[%s] contentlib-%s", id, x.ID), nil
	case library.Item:
		return fmt.Sprintf("%s/%s", cmd.getDatastorePath(r.GetParent()), x.ID), nil
	case library.File:
		return cmd.getDatastoreFileItemPath(r)
	default:
		return "", fmt.Errorf("unsupported type=%T", x)
	}
}

// getDatastoreFileItemPath returns the absolute datastore path for a library.File
func (cmd *info) getDatastoreFileItemPath(r finder.FindResult) (string, error) {
	name := r.GetName()
	dir := cmd.getDatastorePath(r.GetParent())
	p := path.Join(dir, name)

	lib := r.GetParent().GetParent().GetResult().(library.Library)
	if len(lib.Storage) == 0 {
		return p, nil
	}

	ctx := context.Background()
	c, err := cmd.Client()
	if err != nil {
		return p, err
	}

	ref := types.ManagedObjectReference{Type: "Datastore", Value: lib.Storage[0].DatastoreID}
	ds := object.NewDatastore(c, ref)

	b, err := ds.Browser(ctx)
	if err != nil {
		return p, err
	}

	// The file ID isn't available via the API, so we use DatastoreBrowser to search
	ext := path.Ext(name)
	pat := strings.Replace(name, ext, "*"+ext, 1)
	spec := types.HostDatastoreBrowserSearchSpec{
		MatchPattern: []string{pat},
	}

	task, err := b.SearchDatastore(ctx, dir, &spec)
	if err != nil {
		return p, err
	}

	info, err := task.WaitForResult(ctx, nil)
	if err != nil {
		return p, err
	}

	res, ok := info.Result.(types.HostDatastoreBrowserSearchResults)
	if !ok {
		return p, fmt.Errorf("search(%s) result type=%T", pat, info.Result)
	}

	if len(res.File) != 1 {
		return p, fmt.Errorf("search(%s) result files=%d", pat, len(res.File))
	}

	return path.Join(dir, res.File[0].GetFileInfo().Path), nil
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Torula klein Weiss

### Remarks
null


text:
@include('blogLaravel::front.subviewcategorias',['categorias' =>$categorias ])

{{$post['title']}}

            image)}}" alt="A Clockwork Origin">

By {{$post['author']->name}}

{{date('d/m/Y', strtotime($post->updated_at))}}

 $post->categorys[0]->id]) !!}>{{$post->categorys[0]->name}}

{{count($post->comments)}} comentarios

                {!! html_entity_decode($post['textBody']) !!}

                Tags:

                    @foreach ($post->tags as $tag)

{{$tag->name}}

                    @endforeach

{{count($post->comments)}} comentarios

            @if(count($post->comments) > 0)

                @foreach ($post->comments as $comment)
                @if($comment->quotedComment == 0)

{{$comment->name}}

                            •
                            {{date('d/m/Y', strtotime($comment->created_at))}}

                                id}}" aria-expanded="false">
                                     Contestar

                                {{$comment->textBody}}

id}}" class="panel-body panel-collapse collapse" aria-expanded="false">
                        @include('blogLaravel::forms.formResponderComentario',$comment)

                    @foreach ($comment->quotedBy as $quote)
                    @include('blogLaravel::front.layouts.posts.commentariosSegundoNivel',$quote)
                    @endforeach

                @endif
                @endforeach

            @else

No hay mensajes

            @endif

            @include('blogLaravel::forms.formComentarPost')


text:
package com.log999.markup;

import javafx.scene.paint.Color;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static com.log999.markup.matchers.MarkupMatchers.hasRange;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class LineMarkupTest {

    private LineMarkup underTest;

    @Mock
    private LineMarkup.Observer observer;

    @Before
    public void setUp() throws Exception {
        underTest = new LineMarkup(observer, 1000);
    }

    @Test
    public void lineMarkupsEmptyInitially() {
        assertThat(underTest.getMarkups(), is(empty()));
    }

    @Test
    public void shouldCreateMarkupWithBackgroundChange() throws Exception {
        // When
        underTest.markBackground(0, 99, Color.BEIGE);
        // Then
        assertThat(underTest.getMarkups(), hasSize(1));
        assertThat(underTest.getMarkups().get(0), hasRange(0, 99));
        assertThat(underTest.getMarkups().get(0).getValue().getBg(), equalTo(Color.BEIGE));
    }

    @Test
    public void shouldCreateMarkupWithForegroundChange() throws Exception {
        // When
        underTest.markForeground(5, 10, Color.AQUAMARINE);
        // Then
        assertThat(underTest.getMarkups(), hasSize(1));
        assertThat(underTest.getMarkups().get(0), hasRange(5, 10));
        assertThat(underTest.getMarkups().get(0).getValue().getFg(), equalTo(Color.AQUAMARINE));
    }

    @Test
    public void shouldCreateMarkupWithBoldChange() throws Exception {
        // When
        underTest.markBold(0, 3, true);
        // Then
        assertThat(underTest.getMarkups(), hasSize(1));
        assertThat(underTest.getMarkups().get(0), hasRange(0, 3));
        assertThat(underTest.getMarkups().get(0).getValue().isBold(), equalTo(true));
    }

    @Test
    public void shouldRemoveBoldChange() throws Exception {
        // Given
        underTest.markBold(0, 10, true);
        // When
        underTest.markBold(5, 6, false);
        // Then
        assertThat(underTest.getMarkups(), hasSize(2));
        assertThat(underTest.getMarkups().get(0), hasRange(0, 4));
        assertThat(underTest.getMarkups().get(1), hasRange(7, 10));
        assertThat(underTest.getMarkups().get(0).getValue().isBold(), equalTo(true));
        assertThat(underTest.getMarkups().get(1).getValue().isBold(), equalTo(true));
    }

    @Test
    public void shouldRemoveBackgroundChange() throws Exception {
        // Given
        underTest.markBackground(0, 10, Color.AQUAMARINE);
        // When
        underTest.markBackground(5, 6, Color.TRANSPARENT);
        // Then
        assertThat(underTest.getMarkups(), hasSize(2));
        assertThat(underTest.getMarkups().get(0), hasRange(0, 4));
        assertThat(underTest.getMarkups().get(1), hasRange(7, 10));
        assertThat(underTest.getMarkups().get(0).getValue().getBg(), equalTo(Color.AQUAMARINE));
        assertThat(underTest.getMarkups().get(1).getValue().getBg(), equalTo(Color.AQUAMARINE));
    }

    @Test
    public void shouldRemoveForeground() throws Exception {
        // Given
        underTest.markForeground(0, 10, Color.AQUAMARINE);
        // When
        underTest.markForeground(5, 6, Color.TRANSPARENT);
        // Then
        assertThat(underTest.getMarkups(), hasSize(2));
        assertThat(underTest.getMarkups().get(0), hasRange(0, 4));
        assertThat(underTest.getMarkups().get(1), hasRange(7, 10));
        assertThat(underTest.getMarkups().get(0).getValue().getFg(), equalTo(Color.AQUAMARINE));
        assertThat(underTest.getMarkups().get(1).getValue().getFg(), equalTo(Color.AQUAMARINE));
    }

    @Test
    public void removingAllFormattingShouldRemoveAllMarkups() throws Exception {
        // Given
        underTest.markForeground(0, 10, Color.AQUAMARINE);
        // When
        underTest.markForeground(0, 10, Color.TRANSPARENT);
        // Then
        assertThat(underTest.getMarkups(), hasSize(0));
    }

    @Test
    public void shouldNotifyObserverWhenChanged() throws Exception {
        // When
        underTest.markBackground(1,10,Color.ANTIQUEWHITE);
        // Then
        verify(observer, times(1)).updated(underTest);
    }
}


text:
from elasticsearch import Elasticsearch, RequestsHttpConnection
from aws_requests_auth.aws_auth import AWSRequestsAuth
from urlparse import urlparse

class Connection(Elasticsearch):
    def __init__(self, connection_string, access_key=None, secret_key=None, region=None, upper_result_limit=None):
        """
            Args:
                connection_string(string): Elasticsearch connection string <host>:<port>
                access_key(string | None): Cloud provider access key if using Elasticsearch as a provided service
                secret_key(string | None): Cloud provider secret access key
                region(string | None): Cloud provider region
                upper_result_limit(int | None): Upper limit for search results. Defaults to 1000.
        """
        self.connection_string = connection_string
        self._es_index = None
        self._es_host = None
        self._es_port = None
        self._parse_url()
        self._init_connection(access_key, secret_key, region)

        if not upper_result_limit:
            upper_result_limit = 10000
        self.upper_result_limit = upper_result_limit

    @property
    def es_index(self):
        if not self._es_index:
            self._es_index = self._parsed_url.path[1:]

        return self._es_index

    @property
    def es_host(self):
        if not self._es_host:
            self._es_host = self._parsed_url.hostname

        return self._es_host

    @property
    def es_port(self):
        if not self._es_port:
            # If no port is given then Elasticsearch-py defaults it to 9200
            port = self._parsed_url.netloc.rsplit(":", 1)

            if len(port) > 1:
                self._es_port = int(port[1])

        return self._es_port

    def _parse_url(self):
        """
            Parses connection string.
        """
        self._parsed_url = urlparse(self.connection_string)

    def _init_connection(self, access_key=None, secret_key=None, region=None):
        """
            Configures Elasticsearch connection object.
        """
        ssl = False
        auth = None

        if self._parsed_url.scheme == "https":
            ssl = True

        if access_key and secret_key and region:
            auth = AWSRequestsAuth(aws_access_key=access_key,
                                   aws_secret_access_key=secret_key,
                                   aws_host=self.es_host,
                                   aws_region=region,
                                   aws_service="es")

        hosts = [{"host": self.es_host, "port": self.es_port}]
        super(Connection, self).__init__(
            hosts=hosts,
            http_auth=auth,
            use_ssl=ssl,
            verify_certs=ssl,
            # So that if the connection times out it will attempt
            # to connect again.
            retry_on_timeout=True,
            connection_class=RequestsHttpConnection
        )


text:
'''
Created on 20/01/2011

v0.2 (C) Gerald Storer
MIT License

Based on JSON.minify.js:
https://github.com/getify/JSON.minify

Contributers:
 - Pradyun S. Gedam (conditions and variable names changed)
'''

import re

def json_minify(string, strip_space=True):
    tokenizer = re.compile(r'"|(/\*)|(\*/)|(//)|\n|\r')
    in_string = False
    in_multi = False
    in_single = False

    new_str = []
    index = 0

    for match in re.finditer(tokenizer, string):

        if not (in_multi or in_single):
            tmp = string[index:match.start()]
            if not in_string and strip_space:
                # replace white space as defined in standard
                tmp = re.sub('[ \t\n\r]+', '', tmp)
            new_str.append(tmp)

        index = match.end()
        val = match.group()

        if val == '"' and not (in_multi or in_single):
            escaped = re.search(r'(\\)*$', string[:match.start()])

            # start of string or unescaped quote character to end string
            if not in_string or (escaped is None or len(escaped.group()) % 2 == 0):
                in_string = not in_string
            index -= 1 # include " character in next catch
        elif not (in_string or in_multi or in_single):
            if val == '/*':
                in_multi = True
            elif val == '//':
                in_single = True
        elif val == '*/' and in_multi and not (in_string or in_single):
            in_multi = False
        elif val in '\r\n' and not (in_multi or in_string) and in_single:
            in_single = False
        elif not ((in_multi or in_single) or (val in ' \r\n\t' and strip_space)):
            new_str.append(val)

    new_str.append(string[index:])
    return ''.join(new_str)

if __name__ == '__main__':
    # Python 2.6+ needed to run tests
    import json
    import textwrap
    import unittest

    class JsonMinifyTestCase(unittest.TestCase):
        """Tests for json_minify"""
        def template(self, in_string, expected):
            in_dict = json.loads(json_minify(in_string))
            expected_dict = json.loads(expected)
            self.assertEqual(in_dict, expected_dict)

        def test_1(self):
            self.template(textwrap.dedent('''
                // this is a JSON file with comments
                {
                    "foo": "bar",    // this is cool
                    "bar": [
                        "baz", "bum"
                    ],
                /* the rest of this document is just fluff
                   in case you are interested. */
                    "something": 10,
                    "else": 20
                }

                /* NOTE: You can easily strip the whitespace and comments
                   from such a file with the JSON.minify() project hosted
                   here on github at http://github.com/getify/JSON.minify
                */'''),
                '{"foo":"bar","bar":["baz","bum"],"something":10,"else":20}'
            )

        def test_2(self):
            self.template(textwrap.dedent('''
                {"/*":"*/","//":"",/*"//"*/"/*/"://
                "//"}'''),
                '{"/*":"*/","//":"","/*/":"//"}'
            )

        def test_3(self):
            self.template(textwrap.dedent(r'''
                /*
                this is a
                multi line comment */{

                "foo"
                :
                    "bar/*"// something
                    ,    "b\"az":/*
                something else */"blah"

                }
                '''),
                r'{"foo":"bar/*","b\"az":"blah"}'
            )

        def test_4(self):
            self.template(textwrap.dedent(r'''
                {"foo": "ba\"r//", "bar\\": "b\\\"a/*z",
                "baz\\\\": /* yay */ "fo\\\\\"*/o"
                }
                '''),
                r'{"foo":"ba\"r//","bar\\":"b\\\"a/*z","baz\\\\":"fo\\\\\"*/o"}'
            )

    unittest.main()


text:
import { RecursivePartial } from "../../Types/RecursivePartial";
export interface IOptionLoader<T> {
    load(data?: RecursivePartial<T>): void;
}


text:
module Liquefiable
  extend ActiveSupport::Concern

  # included do
  #   has_many :taggings, as: :taggable
  #   has_many :tags, through: :taggings

  #   class_attribute :tag_limit
  # end

  # def tags_string
  #   tags.map(&:name).join(', ')
  # end

  # def tags_string=(tag_string)
  #   tag_names = tag_string.to_s.split(', ')

  #   tag_names.each do |tag_name|
  #     tags.build(name: tag_name)
  #   end
  # end

  # # methods defined here are going to extend the class, not the instance of it
  # module ClassMethods

  #   def tag_limit(value)
  #     self.tag_limit_value = value
  #   end

  # end

  included do |base|
    klass = Class.new(Liquid::Drop)
    klass.include(ERB::Util)
    klass.__send__(:define_method,:initialize) {|thing| @thing = thing}

    base::LIQUEFIABLE_SANITIZED_ATTRIBUTES.each do |attr_name|
      klass.__send__(:define_method,attr_name) do
        h(@thing.attributes[attr_name.to_s])
      end
    end if defined? base::LIQUEFIABLE_SANITIZED_ATTRIBUTES

    base::LIQUEFIABLE_ATTRIBUTES.each do |attr_name|
      klass.__send__(:define_method,attr_name) do
        @thing.attributes[attr_name.to_s]
      end
    end if defined? base::LIQUEFIABLE_ATTRIBUTES

    base::LIQUEFIABLE_METHODS.each do |public_method, private_method|
      klass.__send__(:define_method,public_method) do
        @thing.__send__(private_method)
      end
    end if defined? base::LIQUEFIABLE_METHODS

    base::LIQUEFIABLE_USER_METHODS.each do |public_method, private_method|
      klass.__send__(:define_method,public_method) do
        @thing.__send__(private_method,@context.registers[:user])
      end
    end if defined? base::LIQUEFIABLE_USER_METHODS

    base.const_set(:Drop,klass)
  end

  def to_liquid
    @liquid ||= self.class::Drop.new(self)
  end

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
MerchantContact (Authorize.Net Java SDK)
</TITLE>

<META NAME="date" CONTENT="2011-07-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

net.authorize.data.mobile

Class MerchantContact

java.lang.Object
  net.authorize.data.mobile.MerchantContact

All Implemented Interfaces:
java.io.Serializable

public class MerchantContact
extends java.lang.Object
implements java.io.Serializable

See Also:
Serialized Form

Method Summary

static MerchantContact
createMerchantContact()

          Create a merchant contact.

static MerchantContact
createMerchantContact(java.lang.String companyName,
                      java.lang.String address,
                      java.lang.String city,
                      java.lang.String state,
                      java.lang.String zip,
                      java.lang.String phone)

          Create a merchant contact.

 java.lang.String
getAddress()

 java.lang.String
getCity()

 java.lang.String
getCompanyName()

 java.lang.String
getPhone()

 java.lang.String
getState()

 java.lang.String
getZip()

 void
setAddress(java.lang.String address)

 void
setCity(java.lang.String city)

 void
setCompanyName(java.lang.String companyName)

 void
setPhone(java.lang.String phone)

 void
setState(java.lang.String state)

 void
setZip(java.lang.String zip)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

createMerchantContact

public static MerchantContact createMerchantContact()

Create a merchant contact.

Returns:
MerchantContact

createMerchantContact

public static MerchantContact createMerchantContact(java.lang.String companyName,
                                                    java.lang.String address,
                                                    java.lang.String city,
                                                    java.lang.String state,
                                                    java.lang.String zip,
                                                    java.lang.String phone)

Create a merchant contact.

Parameters:
companyName -
address -
city -
state -
zip -
phone -

Returns:
MerchantContact container

getCompanyName

public java.lang.String getCompanyName()

Returns:
the companyName

setCompanyName

public void setCompanyName(java.lang.String companyName)

Parameters:
companyName - the companyName to set

getAddress

public java.lang.String getAddress()

Returns:
the address

setAddress

public void setAddress(java.lang.String address)

Parameters:
address - the address to set

getCity

public java.lang.String getCity()

Returns:
the city

setCity

public void setCity(java.lang.String city)

Parameters:
city - the city to set

getState

public java.lang.String getState()

Returns:
the state

setState

public void setState(java.lang.String state)

Parameters:
state - the state to set

getZip

public java.lang.String getZip()

Returns:
the zip

setZip

public void setZip(java.lang.String zip)

Parameters:
zip - the zip to set

getPhone

public java.lang.String getPhone()

Returns:
the phone

setPhone

public void setPhone(java.lang.String phone)

Parameters:
phone - the phone to set

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package org.apache.ftpserver.clienttests;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ftpserver.test.TestUtil;

/**
*
* @author The Apache MINA Project (dev@mina.apache.org)
* @version $Rev$, $Date$
*
*/
public class FtpMd5Test extends ClientTestTemplate {
    private static final File TEST_FILE1 = new File(ROOT_DIR, "test1.txt");

    private static final File TEST_FILE_WITH_SPACE = new File(ROOT_DIR,
            "test 2.txt");

    private static final File TEST_DIR1 = new File(ROOT_DIR, "dir1");

    private static final File TEST_FILE_IN_DIR1 = new File(TEST_DIR1,
            "test4.txt");

    private static byte[] testData = null;

    private static byte[] testData2 = null;

    private static String testDataHash;

    private static String testData2Hash;

    /*
     * (non-Javadoc)
     *
     * @see org.apache.ftpserver.clienttests.ClientTestTemplate#setUp()
     */
    protected void setUp() throws Exception {
        super.setUp();

        testData = "TESTDATA".getBytes("UTF-8");
        testData2 = "Hello world".getBytes("UTF-8");
        testDataHash = DigestUtils.md5Hex(testData).toUpperCase();
        testData2Hash = DigestUtils.md5Hex(testData2).toUpperCase();

        client.login(ADMIN_USERNAME, ADMIN_PASSWORD);
    }

    public void testMd5() throws Exception {
        TestUtil.writeDataToFile(TEST_FILE1, testData);

        assertTrue(TEST_FILE1.exists());

        String fileName = TEST_FILE1.getName();

        assertEquals(251, client.sendCommand("MD5 " + fileName));

        assertHash(testDataHash, client.getReplyString(), fileName);
    }

    public void testMd5NoFileName() throws Exception {
        assertEquals(504, client.sendCommand("MD5"));
    }

    public void testMd5NonExistingFile() throws Exception {
        assertFalse(TEST_FILE1.exists());

        String fileName = TEST_FILE1.getName();

        assertEquals(504, client.sendCommand("MD5 " + fileName));
    }

    public void testMd5WithSpaceInFileName() throws Exception {
        TestUtil.writeDataToFile(TEST_FILE_WITH_SPACE, testData);

        assertTrue(TEST_FILE_WITH_SPACE.exists());

        String fileName = TEST_FILE_WITH_SPACE.getName();

        assertEquals(251, client.sendCommand("MD5 " + fileName));

        assertHash(testDataHash, client.getReplyString(), fileName);
    }

    public void testMd5WithDirectory() throws Exception {
        TEST_DIR1.mkdirs();
        assertTrue(TEST_DIR1.exists());

        String fileName = TEST_DIR1.getName();

        assertEquals(504, client.sendCommand("MD5 " + fileName));
    }

    public void testMd5WithNonExistingFile() throws Exception {
        assertFalse(TEST_FILE1.exists());

        String fileName = TEST_FILE1.getName();

        assertEquals(504, client.sendCommand("MD5 " + fileName));
    }

    public void testMd5WithPath() throws Exception {
        TEST_DIR1.mkdirs();
        assertTrue(TEST_DIR1.exists());
        TestUtil.writeDataToFile(TEST_FILE_IN_DIR1, testData);
        assertTrue(TEST_FILE_IN_DIR1.exists());

        String fileName = TEST_DIR1.getName() + "/"
                + TEST_FILE_IN_DIR1.getName();

        assertEquals(251, client.sendCommand("MD5 " + fileName));

        assertHash(testDataHash, client.getReplyString(), fileName);
    }

    private void assertHash(String expected, String reply, String fileName) {
        Map<String, String> hashes = parseReplyHash(reply);
        assertEquals(expected, hashes.get(fileName));
    }

    public void testMMd5() throws Exception {
        TestUtil.writeDataToFile(TEST_FILE1, testData);
        TestUtil.writeDataToFile(TEST_FILE_WITH_SPACE, testData2);

        assertTrue(TEST_FILE1.exists());
        assertTrue(TEST_FILE_WITH_SPACE.exists());

        String fileNames = TEST_FILE1.getName() + ","
                + TEST_FILE_WITH_SPACE.getName();

        assertEquals(252, client.sendCommand("MMD5 " + fileNames));

        assertHash(testDataHash, client.getReplyString(), TEST_FILE1.getName());
        assertHash(testData2Hash, client.getReplyString(), TEST_FILE_WITH_SPACE
                .getName());
    }

    public void testMMd5SingleFile() throws Exception {
        TestUtil.writeDataToFile(TEST_FILE1, testData);

        assertTrue(TEST_FILE1.exists());

        String fileNames = TEST_FILE1.getName();

        assertEquals(252, client.sendCommand("MMD5 " + fileNames));

        assertHash(testDataHash, client.getReplyString(), TEST_FILE1.getName());
    }

    public void testMMd5MixedFilesAndDirs() throws Exception {
        TestUtil.writeDataToFile(TEST_FILE1, testData);
        TEST_DIR1.mkdirs();

        assertTrue(TEST_FILE1.exists());
        assertTrue(TEST_DIR1.exists());

        String fileNames = TEST_FILE1.getName() + "," + TEST_DIR1.getName();

        assertEquals(504, client.sendCommand("MMD5 " + fileNames));
    }

    private Map<String, String> parseReplyHash(String reply) {
        String s = reply.substring(4);
        s = s.trim();

        String[] tokens = s.split(",");

        Map<String, String> result = new HashMap<String, String>();
        for (int i = 0; i < tokens.length; i++) {
            String token = tokens[i].trim();
            int hashStart = token.lastIndexOf(' ');

            String fileName = token.substring(0, hashStart).trim();
            String hash = token.substring(hashStart).trim();

            result.put(fileName, hash);
        }

        return result;
    }
}