text:
"""
This tool is Modis' embed API. It allows Modis modules to easily create
fancy looking GUIs in the Discord client.
"""

import logging

import discord

from modis import main

logger = logging.getLogger(__name__)

URL = "https://musicbyango.com/modis/"
ICON = "http://musicbyango.com/modis/dp/modis64t.png"
# TODO Update to ModisWorks url

class UI:
    """Enables easy management of Discord embeds."""

    def __init__(self, channel, title, description, modulename="Modis",
                 colour=0xAAFF00, thumbnail=None, image=None, datapacks=()):
        """Initialise variables and build the embed.

        Args:
            channel (discord.TextChannel): Channel to lock UI to
            title (str): GUI title, in bold
            description (str): GUI description
            modulename (str): Name of your module, default "Modis"
            colour (int): Colour of line on left, default 0xAAFF00
            thumbnail (str): URL to picture shown in top right corner, default None
            datapacks (list): Contains tuples of (title str, data str, inline bool)
        """

        self.channel = channel
        self.title = title
        self.description = description
        self.modulename = modulename
        self.colour = colour
        self.thumbnail = thumbnail
        self.image = image
        self.datapacks = datapacks
        self.datapack_lines = {}

        self.built_embed = self.build()
        self.sent_embed = None

    def build(self):
        """Build the embed.

        Returns:
            discord.Embed: The built embed.
        """

        embed = discord.Embed(
            title=self.title,
            type='rich',
            description=self.description,
            colour=self.colour)

        embed.set_author(
            name="Modis",
            url=URL,
            icon_url=ICON)

        if self.thumbnail:
            embed.set_thumbnail(url=self.thumbnail)

        if self.image:
            embed.set_image(url=self.image)

        self.datapack_lines = {}
        for pack in self.datapacks:
            embed.add_field(name=pack[0], value=pack[1], inline=pack[2])
            self.datapack_lines[pack[0]] = pack

        return embed

    async def send(self):
        """Send the embed message."""

        await self.channel.trigger_typing()
        self.sent_embed = await self.channel.send(embed=self.built_embed)

    async def usend(self):
        """Update the existing embed."""

        try:
            await self.sent_embed.edit(embed=self.built_embed)
        except Exception as e:
            # TODO Add exceptions
            logger.exception(e)

    async def delete(self):
        """Delete the existing embed."""

        try:
            await self.sent_embed.delete()
        except Exception as e:
            # TODO Add exceptions
            logger.exception(e)

        self.sent_embed = None

    def update_field(self, title, data):
        """Update a particular field's data.

        Args:
            title (str): The title of the field to update.
            data (str): The new value to set for this datapack.
        """

        if title in self.datapack_lines:
            self.update_data(self.datapack_lines[title], data)
        else:
            logger.warning("No field with title '{}'".format(title))

    def update_colour(self, new_colour):
        """Update the embed's colour.

        Args:
            new_colour (discord.Colour): The new colour for the embed.
        """

        self.built_embed.colour = new_colour

    def update_data(self, index, data):
        """Update a particular datapack's data.

        Args:
            index (int): The index of the datapack.
            data (str): The new value to set for this datapack.
        """

        datapack = self.built_embed.to_dict()["fields"][index]
        self.built_embed.set_field_at(index, name=datapack["name"], value=data, inline=datapack["inline"])


text:
package org.apache.skywalking.oap.server.configuration.zookeeper;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.skywalking.oap.server.library.module.ModuleConfig;

@Getter
@Setter
@ToString
public class ZookeeperServerSettings extends ModuleConfig {
    private String nameSpace = "/default";
    private String hostPort;
    private int baseSleepTimeMs = 1000;
    private int maxRetries = 3;
    private int period = 60;
}

redpajama_set_name: RedPajamaGithub


text:
namespace Eventually.Subscriptions
{
    using System.Text;
    using Akka.Actor;
    using EventStore.ClientAPI;
    using Messages;

    internal class SubscriptionEventHandler : ReceiveActor
    {
        private readonly IActorRef subscriber;

        public SubscriptionEventHandler(IActorRef subscriber)
        {
            this.subscriber = subscriber;

            Receive<SubscriptionEventAppeared>(x => ExtractEventDetails(x.ResolvedEvent));
        }

        private void ExtractEventDetails(ResolvedEvent resolvedEvent)
        {
            // TODO: Decide if I actually care about non-json events
            if (resolvedEvent.Event.IsJson)
            {
                var eventNumber = resolvedEvent.Link != null ? resolvedEvent.Link.EventNumber : resolvedEvent.Event.EventNumber;
                var eventType = resolvedEvent.Event.EventType;
                var eventDate = resolvedEvent.Event.Created;
                var body = Encoding.UTF8.GetString(resolvedEvent.Event.Data);
                var metadata = Encoding.UTF8.GetString(resolvedEvent.Event.Metadata);

                subscriber.Tell(new EventReceived(eventNumber, eventType, eventDate, body, metadata));
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2015, ProductLayer GmbH All rights reserved.
  ~
  ~ Redistribution and use in source and binary forms, with or without
  ~ modification, are permitted provided that the following conditions are met:
  ~
  ~ - Redistributions of source code must retain the above copyright notice, this
  ~   list of conditions and the following disclaimer.
  ~
  ~ - Redistributions in binary form must reproduce the above copyright notice,
  ~   this list of conditions and the following disclaimer in the documentation
  ~   and/or other materials provided with the distribution.
  ~
  ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  ~ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  ~ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  ~ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  ~ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  ~ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  ~ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  ~ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  ~ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  ~ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="4dp">

    <EditText
        android:id="@+id/opinion_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="@string/opinion_text_hint"
        android:inputType="text|textMultiLine|textCapSentences"
        android:maxLength="@integer/opinion_char_max"
        android:textColorHint="?attr/textColorAccent"/>

    <TextView
        android:id="@+id/chars_text"
        style="?attr/textAppearanceCaption"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/opinion_text"
        android:text="@integer/opinion_char_max"/>

    <ImageView
        android:id="@+id/facebook_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/opinion_text"
        android:contentDescription="@string/facebook"
        android:src="@drawable/facebook_gray_24dp"/>

    <ImageView
        android:id="@+id/twitter_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/opinion_text"
        android:layout_marginRight="16dp"
        android:layout_toLeftOf="@id/facebook_image"
        android:contentDescription="@string/twitter"
        android:src="@drawable/twitter_gray_24dp"/>

</RelativeLayout>


text:
/**
* Developer: Minhas Kamal (BSSE-0509, IIT, DU)
* Date: 08.Oct.2013
**/

#include <iostream>
#include <fstream>
#include <stack>

using namespace std;

int main()//(int argc, char* argv[])
{
    ifstream graph; //input file stream
    graph.open("TopologicalSort_Input.txt");
    //graph.open(argv[1]);

    if(!graph.is_open()){   //when file is not found
        cout << "File name is wrong!\n";
        return 0;
    }

    int vertexNumber, **matrix;
    graph >> vertexNumber;
    matrix = new int* [vertexNumber];
    for(int i=0; i<vertexNumber; i++)
        matrix[i] = new int [vertexNumber];

    for(int i=0; i<vertexNumber; i++)   //taking the input
        for(int j=0; j<vertexNumber; j++)
            graph >> matrix[i][j];

    /*for(int i=0; i<vertexNumber; i++){  //output of the input file
        for(int j=0; j<vertexNumber; j++)
            cout << matrix[i][j] << " ";

        cout << endl;
    }*/

    int *colour = new int [vertexNumber];     //colour of the vertex

    for(int i=0; i<vertexNumber; i++)  //initializing the arrays
        colour[i] = 1;       //colour = 1 = white, 2 = grey

    ///start of DFS
    stack<int> sortedList;
    for(int x=0; x<vertexNumber; x++)
        if(colour[x]==1){
            int startVertex=x;
            stack<int> dFSStack;
            dFSStack.push(startVertex);
            sortedList.push(startVertex);

            colour[startVertex]=2;      //colour is set to grey

            while(!dFSStack.empty()){
                int i=dFSStack.top();
                dFSStack.pop();

                for(int j=0; j<vertexNumber; j++)
                    if(matrix[i][j]==1){
                        colour[j]=2;
                        dFSStack.push(j);
                        sortedList.push(j);
                    }
            }
        }

    int result[vertexNumber];
    for(int i=0; i<vertexNumber; i++){  //refreshing the result
        int flag=1;
        while(flag){
            flag=0;
            for(int j=0; j<i && flag==0; j++)
                if(result[j]==sortedList.top()){
                    //cout << sortedList.top() <<"\n";
                    sortedList.pop();
                    flag=1;
                }
            if(flag==0) {
                result[i]=sortedList.top();
                sortedList.pop();
            }
        }
    }

    cout << "Topological Sort: " << endl;   //output of the result
    for(int i=vertexNumber-1; i>=0; i--)
        cout << "\t\t" << result[i]+1 << endl;

    for(int i=0; i<vertexNumber; i++)   //delete the matrix
        delete[] matrix[i];
    delete[] matrix;

    delete[] colour;    //returning the used memory

    graph.close();  //close the file graph

    return 0;
}


text:
import json
import logging
import math
import os
import shutil
import time
from io import BytesIO

from bzt.bza import Master, Session
from bzt.modules.aggregator import DataPoint, KPISet
from bzt.modules.blazemeter import BlazeMeterUploader, ResultsFromBZA
from bzt.modules.blazemeter import MonitoringBuffer
from bzt.six import HTTPError
from bzt.six import iteritems, viewvalues
from tests import BZTestCase, random_datapoint, __dir__
from tests.mocks import EngineEmul, RecordingHandler
from tests.modules.test_blazemeter import BZMock

class TestBlazeMeterUploader(BZTestCase):
    def test_some_errors(self):
        mock = BZMock()
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Test': {"result": []},
            'https://a.blazemeter.com/api/v4/sessions/1': {"result": {'id': 1, "note": "somenote"}},
            'https://a.blazemeter.com/api/v4/masters/1': {"result": {'id': 1, "note": "somenote"}},
        })
        mock.mock_post.update({
            'https://a.blazemeter.com/api/v4/projects': {"result": {'id': 1}},
            'https://a.blazemeter.com/api/v4/tests': {"result": {'id': 1}},
            'https://a.blazemeter.com/api/v4/tests/1/start-external': {"result": {
                "session": {'id': 1, "testId": 1, "userId": 1},
                "master": {'id': 1},
                "signature": "sign"
            }},
            'https://a.blazemeter.com/api/v4/image/1/files?signature=sign': {"result": True},
            'https://data.blazemeter.com/submit.php?session_id=1&signature=sign&test_id=1&user_id=1&pq=0&target=labels_bulk&update=1': {},
            'https://a.blazemeter.com/api/v4/sessions/1/stop': {"result": True},
        })

        mock.mock_patch.update({
            'https://a.blazemeter.com/api/v4/sessions/1': {"result": {"id": 1, "note": "somenote"}},
            'https://a.blazemeter.com/api/v4/masters/1': {"result": {"id": 1, "note": "somenote"}},
        })

        obj = BlazeMeterUploader()
        mock.apply(obj._user)
        obj.parameters['project'] = 'Proj name'
        obj.settings['token'] = '123'
        obj.settings['browser-open'] = 'none'
        obj.engine = EngineEmul()
        obj.prepare()
        obj.startup()
        obj.engine.stopping_reason = ValueError('wrong value')
        obj.aggregated_second(random_datapoint(10))
        obj.kpi_buffer[-1][DataPoint.CUMULATIVE][''][KPISet.ERRORS] = [
            {'msg': 'Forbidden', 'cnt': 10, 'type': KPISet.ERRTYPE_ASSERT, 'urls': [], KPISet.RESP_CODES: '111'},
            {'msg': 'Allowed', 'cnt': 20, 'type': KPISet.ERRTYPE_ERROR, 'urls': [], KPISet.RESP_CODES: '222'}]
        obj.post_process()
        obj.log.info("Requests: %s", mock.requests)

        # check for note appending in _postproc_phase3()
        reqs = mock.requests[-4:]
        self.assertIn('api/v4/sessions/1', reqs[0]['url'])
        self.assertIn('api/v4/sessions/1', reqs[1]['url'])
        self.assertIn('api/v4/masters/1', reqs[2]['url'])
        self.assertIn('api/v4/masters/1', reqs[3]['url'])
        self.assertIn('ValueError: wrong value', str(reqs[1]['data']))
        self.assertIn('ValueError: wrong value', str(reqs[3]['data']))

        labels = mock.requests[8]['data']
        if not isinstance(labels, str):
            labels = labels.decode("utf-8")
        obj.log.info("Labels: %s", labels)
        data = json.loads(str(labels))
        self.assertEqual(1, len(data['labels']))
        total_item = data['labels'][0]
        self.assertEqual('ALL', total_item['name'])
        self.assertEqual(total_item['assertions'],
                         [{'failureMessage': 'Forbidden', 'failures': 10, 'name': 'All Assertions'}])
        self.assertEqual(total_item['errors'], [{'m': 'Allowed', 'count': 20, 'rc': '222'}])

    def test_no_notes_for_public_reporting(self):
        mock = BZMock()
        mock.mock_post.update({
            'https://a.blazemeter.com/api/v4/sessions/1/terminate-external': {},
            'https://data.blazemeter.com/submit.php?session_id=1&signature=None&test_id=1&user_id=1&pq=0&target=labels_bulk&update=1': {},
        })

        obj = BlazeMeterUploader()
        obj.parameters['project'] = 'Proj name'
        obj.settings['token'] = ''  # public reporting
        obj.settings['browser-open'] = 'none'
        obj.engine = EngineEmul()
        mock.apply(obj._user)
        obj.prepare()

        obj._session = Session(obj._user, {'id': 1, 'testId': 1, 'userId': 1})
        obj._master = Master(obj._user, {'id': 1})

        obj.engine.stopping_reason = ValueError('wrong value')
        obj.aggregated_second(random_datapoint(10))
        obj.kpi_buffer[-1][DataPoint.CUMULATIVE][''][KPISet.ERRORS] = [
            {'msg': 'Forbidden', 'cnt': 10, 'type': KPISet.ERRTYPE_ASSERT, 'urls': [], KPISet.RESP_CODES: '111'},
            {'msg': 'Allowed', 'cnt': 20, 'type': KPISet.ERRTYPE_ERROR, 'urls': [], KPISet.RESP_CODES: '222'}]
        obj.send_monitoring = obj.send_custom_metrics = obj.send_custom_tables = False
        obj.post_process()

        # TODO: looks like this whole block of checks is useless
        # check for note appending in _postproc_phase3()
        reqs = [{'url': '', 'data': ''} for _ in range(4)]  # add template for minimal size
        reqs = (reqs + mock.requests)[-4:]
        self.assertNotIn('api/v4/sessions/1', reqs[0]['url'])
        self.assertNotIn('api/v4/sessions/1', reqs[1]['url'])
        self.assertNotIn('api/v4/masters/1', reqs[2]['url'])
        self.assertNotIn('api/v4/masters/1', reqs[3]['url'])
        if reqs[1]['data']:
            self.assertNotIn('ValueError: wrong value', reqs[1]['data'])
        if reqs[3]['data']:
            self.assertNotIn('ValueError: wrong value', reqs[3]['data'])

    def test_check(self):
        mock = BZMock()
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Test': {"result": []},
            'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Test': {"result": []}
        })
        mock.mock_post.update({
            'https://a.blazemeter.com/api/v4/projects': {"result": {
                "id": 1,
                "name": "boo",
                "userId": 2,
                "description": None,
                "created": time.time(),
                "updated": time.time(),
                "organizationId": None
            }},
            'https://a.blazemeter.com/api/v4/tests': {"result": {'id': 1}},
            'https://a.blazemeter.com/api/v4/tests/1/start-external': {"result": {
                'session': {'id': 1, 'userId': 1, 'testId': 1},
                'master': {'id': 1, 'userId': 1},
                'signature': 'sign'}},
            'https://data.blazemeter.com/submit.php?session_id=1&signature=sign&test_id=1&user_id=1&pq=0&target=labels_bulk&update=1': [
                {},
                {"result": {'session': {"statusCode": 140, 'status': 'ENDED'}}},
                {},
            ],
            'https://a.blazemeter.com/api/v4/image/1/files?signature=sign': [
                IOError("monitoring push expected fail"),
                {"result": True},
                {"result": True},
                {"result": True},
                {"result": True},
                {"result": True},
                {"result": True},
                {"result": True},
                {"result": True},
            ],
            'https://a.blazemeter.com/api/v4/data/masters/1/custom-metrics': [
                IOError("custom metric push expected fail"),
                {"result": True},
                {"result": True},
            ],
            'https://a.blazemeter.com/api/v4/sessions/1/stop': {}
        })

        obj = BlazeMeterUploader()
        obj.parameters['project'] = 'Proj name'
        obj.settings['token'] = '123'
        obj.settings['browser-open'] = 'none'
        obj.settings['send-custom-metrics'] = True
        obj.settings['send-custom-tables'] = True
        obj.engine = EngineEmul()
        shutil.copy(__file__, os.path.join(obj.engine.artifacts_dir, os.path.basename(__file__)))
        mock.apply(obj._user)
        obj._user.timeout = 0.1
        obj.prepare()
        obj.startup()
        for x in range(0, 31):
            obj.aggregated_second(random_datapoint(x))
        mon = [{"ts": 1, "source": "local", "cpu": 1, "mem": 2, "bytes-recv": 100, "other": 0},
               {"ts": 1, "source": "chrome", "memory": 32, "cpu": 23}]
        obj.monitoring_data(mon)
        obj.check()
        for x in range(32, 65):
            obj.aggregated_second(random_datapoint(x))
        obj.last_dispatch = time.time() - 2 * obj.send_interval
        self.assertRaises(KeyboardInterrupt, obj.check)
        obj.aggregated_second(random_datapoint(10))
        obj.shutdown()
        log_file = obj.engine.create_artifact('log', '.tmp')
        handler = logging.FileHandler(log_file)
        obj.engine.log.parent.addHandler(handler)
        obj.engine.config.get('modules').get('shellexec').get('env')['TAURUS_INDEX_ALL'] = 1
        obj.post_process()
        self.assertEqual(22, len(mock.requests))
        obj.engine.log.parent.removeHandler(handler)

    def test_monitoring_buffer_limit_option(self):
        obj = BlazeMeterUploader()
        obj.engine = EngineEmul()
        mock = BZMock(obj._user)
        obj.settings["monitoring-buffer-limit"] = 100
        obj.prepare()
        for i in range(1000):
            mon = [{"ts": i, "source": "local", "cpu": float(i) / 1000 * 100, "mem": 2, "bytes-recv": 100, "other": 0}]
            obj.monitoring_data(mon)
            for source, buffer in iteritems(obj.monitoring_buffer.data):
                self.assertLessEqual(len(buffer), 100)
        self.assertEqual(1, len(mock.requests))

    def test_direct_feeding(self):
        obj = BlazeMeterUploader()
        obj.engine = EngineEmul()
        mock = BZMock(obj._user)
        mock.mock_post.update({
            'https://data.blazemeter.com/submit.php?session_id=direct&signature=sign&test_id=None&user_id=None&pq=0&target=labels_bulk&update=1': {},
            'https://a.blazemeter.com/api/v4/image/direct/files?signature=sign': {"result": True},
        })
        obj.parameters['session-id'] = 'direct'
        obj.parameters['signature'] = 'sign'
        obj.prepare()
        obj.startup()
        obj.check()
        obj.shutdown()
        obj.post_process()
        self.assertEquals('direct', obj._session['id'])
        self.assertEqual(2, len(mock.requests))

    def test_anonymous_feeding(self):
        obj = BlazeMeterUploader()
        obj.engine = EngineEmul()
        obj.browser_open = False
        mock = BZMock(obj._user)
        mock.mock_post.update({
            'https://a.blazemeter.com/api/v4/sessions': {"result": {
                "signature": "sign",
                "publicTokenUrl": "publicUrl",
                "session": {"id": 1, "testId": 1, "userId": 1},
                "master": {"id": 1},
            }},
            'https://data.blazemeter.com/submit.php?session_id=1&signature=sign&test_id=1&user_id=1&pq=0&target=labels_bulk&update=1': {},
            'https://a.blazemeter.com/api/v4/image/1/files?signature=sign': {"result": True},
        })
        obj.prepare()
        obj.startup()
        obj.check()
        obj.shutdown()
        obj.post_process()
        self.assertEquals(1, obj._session['id'])
        self.assertEqual(4, len(mock.requests))

    def test_401(self):
        obj = BlazeMeterUploader()
        obj.engine = EngineEmul()
        mock = BZMock(obj._user)
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/web/version': HTTPError(None, None, None, None, None, ),
        })
        self.assertRaises(HTTPError, obj.prepare)

    def test_multiple_reporters_one_monitoring(self):
        obj1 = BlazeMeterUploader()
        obj1.engine = EngineEmul()
        BZMock(obj1._user)

        obj2 = BlazeMeterUploader()
        obj2.engine = EngineEmul()
        BZMock(obj2._user)

        obj1.prepare()
        obj2.prepare()

        for i in range(10):
            mon = [{"ts": i, "source": "local", "cpu": float(i) / 1000 * 100, "mem": 2, "bytes-recv": 100, "other": 0}]
            obj1.monitoring_data(mon)
            obj2.monitoring_data(mon)

    def test_public_report(self):
        mock = BZMock()
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Test': {"result": []}
        })

        mock.mock_post.update({
            'https://a.blazemeter.com/api/v4/projects': {"result": {'id': 1}},
            'https://a.blazemeter.com/api/v4/tests': {'result': {'id': 'unittest1'}},
            'https://a.blazemeter.com/api/v4/tests/unittest1/start-external': {"result": {
                'session': {'id': 'sess1', 'userId': 1, 'testId': 1},
                'master': {'id': 'master1', 'userId': 1},
                'signature': ''
            }},
            'https://a.blazemeter.com/api/v4/masters/master1/public-token': {'result': {'publicToken': 'publicToken'}},
            'https://data.blazemeter.com/submit.php?session_id=sess1&signature=&test_id=1&user_id=1&pq=0&target=labels_bulk&update=1': {
                "result": {'session': {}}},
            'https://a.blazemeter.com/api/v4/image/sess1/files?signature=': {'result': True},
        })

        log_recorder = RecordingHandler()

        obj = BlazeMeterUploader()
        obj.settings['token'] = '123'
        obj.settings['browser-open'] = 'none'
        obj.settings['public-report'] = True
        obj.settings['send-monitoring'] = False
        obj.engine = EngineEmul()
        mock.apply(obj._user)
        obj.log.addHandler(log_recorder)
        obj.prepare()
        obj.startup()
        obj.aggregated_second(random_datapoint(10))
        obj.check()
        obj.shutdown()
        obj.post_process()

        log_buff = log_recorder.info_buff.getvalue()
        log_line = "Public report link: https://a.blazemeter.com/app/?public-token=publicToken#/masters/master1/summary"
        self.assertIn(log_line, log_buff)
        logging.warning("\n".join([x['url'] for x in mock.requests]))
        self.assertEqual(14, len(mock.requests))

    def test_new_project_existing_test(self):
        obj = BlazeMeterUploader()
        mock = BZMock(obj._user)
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Test': {'result': [
                {'id': 1, 'name': 'Taurus Test', 'configuration': {"type": 'external'}}
            ]},
            'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Test': {'result': []}
        })

        mock.mock_post.update({
            'https://a.blazemeter.com/api/v4/projects': {"result": {"id": 1}},
            'https://a.blazemeter.com/api/v4/tests': {"result": {"id": 1}},
        })

        obj.parameters['project'] = 'Proj name'
        obj.settings['token'] = '123'
        obj.settings['browser-open'] = 'none'
        obj.engine = EngineEmul()
        obj.prepare()
        self.assertEquals('https://a.blazemeter.com/api/v4/projects', mock.requests[4]['url'])
        self.assertEquals('POST', mock.requests[4]['method'])
        self.assertEquals('https://a.blazemeter.com/api/v4/tests', mock.requests[6]['url'])
        self.assertEquals('POST', mock.requests[6]['method'])

    def test_new_project_new_test(self):
        obj = BlazeMeterUploader()
        mock = BZMock(obj._user)
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/tests?workspaceId=1&name=Taurus+Test': {'result': []},
            'https://a.blazemeter.com/api/v4/projects?workspaceId=1': {'result': []}
        })

        mock.mock_post.update({
            'https://a.blazemeter.com/api/v4/projects': {"result": {"id": 1}},
            'https://a.blazemeter.com/api/v4/tests': {"result": {"id": 1}},
        })

        obj.settings['token'] = '123'
        obj.settings['browser-open'] = 'none'
        obj.engine = EngineEmul()
        obj.prepare()
        self.assertEquals('https://a.blazemeter.com/api/v4/projects', mock.requests[6]['url'])
        self.assertEquals('POST', mock.requests[6]['method'])
        self.assertEquals('https://a.blazemeter.com/api/v4/tests', mock.requests[7]['url'])
        self.assertEquals('POST', mock.requests[7]['method'])

    def test_existing_project_new_test(self):
        obj = BlazeMeterUploader()
        mock = BZMock(obj._user)
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/tests?projectId=1&name=Taurus+Test': {'result': []},
            'https://a.blazemeter.com/api/v4/projects?workspaceId=1': {'result': [
                {'id': 1, 'name': 'Proj name'}
            ]}
        })

        mock.mock_post.update({
            'https://a.blazemeter.com/api/v4/projects': {"result": {"id": 1}},
            'https://a.blazemeter.com/api/v4/tests': {"result": {"id": 1}},
        })

        obj.parameters['project'] = 'Proj name'
        obj.settings['token'] = '123'
        obj.settings['browser-open'] = 'none'
        obj.engine = EngineEmul()
        obj.prepare()
        self.assertEquals('https://a.blazemeter.com/api/v4/tests', mock.requests[6]['url'])
        self.assertEquals('POST', mock.requests[6]['method'])

class TestBlazeMeterClientUnicode(BZTestCase):
    def test_unicode_request(self):
        """
        test UnicodeDecodeError in BlazeMeterClient._request()
        """
        session = Session(data={'id': 1})
        mock = BZMock(session)
        mock.mock_post['https://a.blazemeter.com/api/v4/image/1/files?signature=None'] = {"result": 1}
        session.upload_file(__dir__() + "/../data/unicode_file")

    def test_binary_unicode_error(self):
        session = Session(data={'id': 1})
        mock = BZMock(session)
        mock.mock_post['https://a.blazemeter.com/api/v4/image/1/files?signature=None'] = {"result": 1}
        with open(__dir__() + "/../data/jmeter-dist-2.13.zip", 'rb') as fds:
            zip_content = fds.read()
        session.upload_file("jtls_and_more.zip", zip_content)

class DummyHttpResponse(object):
    def __init__(self):
        self.fake_socket = BytesIO()
        self.fake_socket.write(open(__dir__() + "/../data/unicode_file", 'rb').read())

    def read(self):
        self.fake_socket.seek(0)
        return self.fake_socket.read(1024)

def dummy_urlopen(*args, **kwargs):
    del args, kwargs
    return DummyHttpResponse()

class TestResultsFromBZA(BZTestCase):
    def test_datapoint(self):
        mock = BZMock()
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/data/labels?master_id=1': {
                "api_version": 2,
                "error": None,
                "result": [
                    {
                        "sessions": [
                            "r-t-5746a8e38569a"
                        ],
                        "id": "ALL",
                        "name": "ALL"
                    },
                    {
                        "sessions": [
                            "r-t-5746a8e38569a"
                        ],
                        "id": "e843ff89a5737891a10251cbb0db08e5",
                        "name": "http://blazedemo.com/"
                    }
                ]
            },
            'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=0&master_ids%5B%5D=1&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
                "api_version": 2,
                "error": None,
                "result": [
                    {
                        "labelId": "ALL",
                        "labelName": "ALL",
                        "label": "ALL",
                        "kpis": [
                            {
                                "n": 1,
                                "na": 1,
                                "ec": 0,
                                "p90": 0,
                                "t_avg": 817,
                                "lt_avg": 82,
                                "by_avg": 0,
                                "n_avg": 1,
                                "ec_avg": 0,
                                "ts": 1464248743
                            }
                        ]
                    }
                ]
            },
            'https://a.blazemeter.com/api/v4/masters/1/reports/aggregatereport/data': {
                "api_version": 2,
                "error": None,
                "result": [
                    {
                        "labelId": "ALL",
                        "labelName": "ALL",
                        "samples": 152,
                        "avgResponseTime": 786,
                        "90line": 836,
                        "95line": 912,
                        "99line": 1050,
                        "minResponseTime": 531,
                        "maxResponseTime": 1148,
                        "avgLatency": 81,
                        "geoMeanResponseTime": None,
                        "stDev": 108,
                        "duration": 119,
                        "avgBytes": 0,
                        "avgThroughput": 1.2773109243697,
                        "medianResponseTime": 0,
                        "errorsCount": 0,
                        "errorsRate": 0,
                        "hasLabelPassedThresholds": None
                    },
                    {
                        "labelId": "e843ff89a5737891a10251cbb0db08e5",
                        "labelName": "http://blazedemo.com/",
                        "samples": 152,
                        "avgResponseTime": 786,
                        "90line": 836,
                        "95line": 912,
                        "99line": 1050,
                        "minResponseTime": 531,
                        "maxResponseTime": 1148,
                        "avgLatency": 81,
                        "geoMeanResponseTime": None,
                        "stDev": 108,
                        "duration": 119,
                        "avgBytes": 0,
                        "avgThroughput": 1.2773109243697,
                        "medianResponseTime": 0,
                        "errorsCount": 0,
                        "errorsRate": 0,
                        "hasLabelPassedThresholds": None
                    }
                ]
            }
        })

        obj = ResultsFromBZA()
        obj.master = Master(data={"id": 1})
        mock.apply(obj.master)
        res = list(obj.datapoints(True))
        cumulative_ = res[0][DataPoint.CUMULATIVE]
        total = cumulative_['']
        percentiles_ = total[KPISet.PERCENTILES]
        self.assertEquals(1.05, percentiles_['99.0'])

    def test_no_kpis_on_cloud_crash(self):
        mock = BZMock()
        mock.mock_get.update({
            'https://a.blazemeter.com/api/v4/data/labels?master_id=0': {
                "api_version": 2,
                "error": None,
                "result": [
                    {
                        "sessions": [
                            "r-t-5746a8e38569a"
                        ],
                        "id": "ALL",
                        "name": "ALL"
                    },
                    {
                        "sessions": [
                            "r-t-5746a8e38569a"
                        ],
                        "id": "e843ff89a5737891a10251cbb0db08e5",
                        "name": "http://blazedemo.com/"
                    }
                ]
            },
            'https://a.blazemeter.com/api/v4/data/kpis?interval=1&from=0&master_ids%5B%5D=0&kpis%5B%5D=t&kpis%5B%5D=lt&kpis%5B%5D=by&kpis%5B%5D=n&kpis%5B%5D=ec&kpis%5B%5D=ts&kpis%5B%5D=na&labels%5B%5D=ALL&labels%5B%5D=e843ff89a5737891a10251cbb0db08e5': {
                "api_version": 2,
                "error": None,
                "result": [
                    {
                        "labelId": "ALL",
                        "labelName": "ALL",
                    }
                ]
            },
            'https://a.blazemeter.com/api/v4/masters/0/reports/aggregatereport/data': {
                "api_version": 2,
                "error": None,
                "result": [
                    {
                        "labelId": "ALL",
                        "labelName": "ALL",
                        "samples": 152,
                        "avgResponseTime": 786,
                        "90line": 836,
                        "95line": 912,
                        "99line": 1050,
                        "minResponseTime": 531,
                        "maxResponseTime": 1148,
                        "avgLatency": 81,
                        "geoMeanResponseTime": None,
                        "stDev": 108,
                        "duration": 119,
                        "avgBytes": 0,
                        "avgThroughput": 1.2773109243697,
                        "medianResponseTime": 0,
                        "errorsCount": 0,
                        "errorsRate": 0,
                        "hasLabelPassedThresholds": None
                    },
                    {
                        "labelId": "e843ff89a5737891a10251cbb0db08e5",
                        "labelName": "http://blazedemo.com/",
                        "samples": 152,
                        "avgResponseTime": 786,
                        "90line": 836,
                        "95line": 912,
                        "99line": 1050,
                        "minResponseTime": 531,
                        "maxResponseTime": 1148,
                        "avgLatency": 81,
                        "geoMeanResponseTime": None,
                        "stDev": 108,
                        "duration": 119,
                        "avgBytes": 0,
                        "avgThroughput": 1.2773109243697,
                        "medianResponseTime": 0,
                        "errorsCount": 0,
                        "errorsRate": 0,
                        "hasLabelPassedThresholds": None
                    }
                ]
            }
        })

        obj = ResultsFromBZA(Master(data={'id': 0}))
        mock.apply(obj.master)

        res = list(obj.datapoints(True))
        self.assertEqual(res, [])

class TestMonitoringBuffer(BZTestCase):
    def to_rad(self, deg):
        return deg * math.pi / 180

    def test_harmonic(self):
        iterations = 50
        size_limit = 10
        mon_buffer = MonitoringBuffer(size_limit, logging.getLogger(''))
        for i in range(iterations):
            cpu = math.sin(self.to_rad(float(i) / iterations * 180))
            mon = [{"ts": i, "source": "local", "cpu": cpu}]
            mon_buffer.record_data(mon)
            self.assertLessEqual(len(mon_buffer.data['local']), size_limit)

    def test_downsample_theorem(self):
        # Theorem: average interval size in monitoring buffer will always
        # be less or equal than ITERATIONS / BUFFER_LIMIT
        mon_buffer = MonitoringBuffer(100, logging.getLogger(''))
        for i in range(5000):
            mon = [{"ts": i, "source": "local", "cpu": 1, "mem": 2, "bytes-recv": 100, "other": 0}]
            mon_buffer.record_data(mon)
            for source, buffer in iteritems(mon_buffer.data):
                self.assertLessEqual(len(buffer), 100)
                sizes = [item['interval'] for item in viewvalues(buffer)]
                avg_size = float(sum(sizes)) / len(sizes)
                expected_size = 5000 / 100
                self.assertLessEqual(avg_size, expected_size * 1.20)

    def test_sources(self):
        mon_buffer = MonitoringBuffer(10, logging.getLogger(''))
        for i in range(100):
            mon = [
                {"ts": i, "source": "local", "cpu": 1, "mem": 2, "bytes-recv": 100},
                {"ts": i, "source": "server-agent", "cpu": 10, "mem": 20},
            ]
            mon_buffer.record_data(mon)
            for source, buffer in iteritems(mon_buffer.data):
                self.assertLessEqual(len(buffer), 10)

    def test_unpack(self):
        ITERATIONS = 200
        SIZE_LIMIT = 10
        mon_buffer = MonitoringBuffer(SIZE_LIMIT, logging.getLogger(''))
        for i in range(ITERATIONS):
            mon = [{"ts": i, "source": "local", "cpu": 1}]
            mon_buffer.record_data(mon)
        unpacked = sum(item['interval'] for item in viewvalues(mon_buffer.data['local']))
        self.assertEqual(unpacked, ITERATIONS)


text:
// 02. Write a program that retrieves the name and description of all categories in the Northwind DB.
namespace GetNameAndDescription
{
    using System;
    using System.Data.SqlClient;
    class Program
    {
        static void Main()
        {
            // Please change the connection string with Your Own
            // Check the database Name too!!!
            string connectionString = "Server=LENOVO\\SQLEXPRESS; Database=NORTHWND; Integrated Security=true";
            SqlConnection dbCon = new SqlConnection(connectionString);
            dbCon.Open();
            using (dbCon)
            {
                Console.WriteLine("FETCHING CATEGORIES AND DESCRIPTION:");
                Console.WriteLine("------------------------------------");
                SqlCommand cmdCategoryNameDescription = new SqlCommand(
                  "SELECT CategoryName, Description FROM Categories", dbCon);
                SqlDataReader reader = cmdCategoryNameDescription.ExecuteReader();
                using (reader)
                {
                    while (reader.Read())
                    {
                        string categoryName = (string)reader["CategoryName"];
                        string categoryDescription = (string)reader["Description"];
                        Console.WriteLine("{0}: \n\t{1}\n", categoryName, categoryDescription);
                    }
                }
            }
        }
    }
}


text:
module RTS.Assembler where

import RTS.BCParser
import RTS.Bytecode

bcAsm :: FilePath -> IO ()
bcAsm f = do bc <- parseFile f
             print bc


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

<phpunit backupGlobals="true"
         backupStaticAttributes="false"
         bootstrap="/path/to/bootstrap.php"
         colors="false"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         stopOnFailure="false"
         syntaxCheck="false"
         testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader">>
  <testsuites>
    <testsuite name="My Test Suite">
      <directory suffix="Test.php">/path/to/files</directory>
      <file>/path/to/MyTest.php</file>
    </testsuite>
  </testsuites>

  <groups>
    <include>
      <group>name</group>
    </include>
    <exclude>
      <group>name</group>
    </exclude>
  </groups>

  <filter>
    <blacklist>
      <directory suffix=".php">/path/to/files</directory>
      <file>/path/to/file</file>
      <exclude>
        <directory suffix=".php">/path/to/files</directory>
        <file>/path/to/file</file>
      </exclude>
    </blacklist>
    <whitelist addUncoveredFilesFromWhitelist="true">
      <directory suffix=".php">/path/to/files</directory>
      <file>/path/to/file</file>
      <exclude>
        <directory suffix=".php">/path/to/files</directory>
        <file>/path/to/file</file>
      </exclude>
    </whitelist>
  </filter>

  <listeners>
    <listener class="MyListener" file="/optional/path/to/MyListener.php">
      <arguments>
        <array>
          <element key="0">
            <string>Sebastian</string>
          </element>
        </array>
        <integer>22</integer>
        <string>April</string>
        <double>19.78</double>
        <null/>
        <object class="stdClass"/>
      </arguments>
    </listener>
  </listeners>

  <logging>
    <log type="coverage-html" target="/tmp/report" title="My Project"
         charset="UTF-8" yui="true" highlight="false"
         lowUpperBound="35" highLowerBound="70"/>
    <log type="coverage-clover" target="/tmp/clover.xml"/>
    <log type="coverage-source" target="/tmp/coverage"/>
    <log type="graphviz" target="/tmp/logfile.dot"/>
    <log type="json" target="/tmp/logfile.json"/>
    <log type="metrics-xml" target="/tmp/metrics.xml"/>
    <log type="plain" target="/tmp/logfile.txt"/>
    <log type="pmd-xml" target="/tmp/pmd.xml" cpdMinLines="5" cpdMinMatches="70"/>
    <log type="tap" target="/tmp/logfile.tap"/>
    <log type="junit" target="/tmp/logfile.xml" logIncompleteSkipped="false"/>
    <log type="story-html" target="/tmp/story.html"/>
    <log type="story-text" target="/tmp/story.txt"/>
    <log type="testdox-html" target="/tmp/testdox.html"/>
    <log type="testdox-text" target="/tmp/testdox.txt"/>

    <pmd>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Project_CRAP"
            threshold="5,30" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Class_DepthOfInheritanceTree"
            threshold="6" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Class_EfferentCoupling"
            threshold="20" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Class_ExcessiveClassLength"
            threshold="1000" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Class_ExcessivePublicCount"
            threshold="45" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Class_TooManyFields"
            threshold="15" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Function_CodeCoverage"
            threshold="35,70" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Function_CRAP"
            threshold="30" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Function_CyclomaticComplexity"
            threshold="20" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Function_ExcessiveMethodLength"
            threshold="100" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Function_ExcessiveParameterList"
            threshold="10" priority="1"/>
      <rule class="PHPUnit_Util_Log_PMD_Rule_Function_NPathComplexity"
            threshold="200" priority="1"/>
    </pmd>
  </logging>

  <php>
    <ini name="foo" value="bar"/>
    <const name="foo" value="bar"/>
    <var name="foo" value="bar"/>
  </php>

  <selenium>
    <browser name="Firefox on Linux"
             browser="*firefox /usr/lib/firefox/firefox-bin"
             host="my.linux.box"
             port="4444"
             timeout="30000"/>
  </selenium>
</phpunit>


text:
Notebook Viewer
===============

An IPython notebook viewer for OODA's research reports.

Licence
-------

MIT