text:
<!--
WARNING: THIS IS AN AUTO-GENERATED FILE. CHANGES TO IT ARE LIKELY TO BE
OVERWRITTEN AND LOST. Changes to this xml configuration should be made using:
  virsh nwfilter-edit clean-traffic
or other application using the libvirt API.
-->

<filter name='clean-traffic' chain='root'>
  <uuid>f7169c33-0b78-45f3-8a66-103a6f2f32d1</uuid>
  <filterref filter='no-mac-spoofing'/>
  <filterref filter='no-ip-spoofing'/>
  <rule action='accept' direction='out' priority='-650'>
    <mac protocolid='ipv4'/>
  </rule>
  <filterref filter='allow-incoming-ipv4'/>
  <filterref filter='no-arp-spoofing'/>
  <rule action='accept' direction='inout' priority='-500'>
    <mac protocolid='arp'/>
  </rule>
  <filterref filter='no-other-l2-traffic'/>
  <filterref filter='qemu-announce-self'/>
</filter>


text:
FROM fedora:20
RUN yum -y update
RUN yum -y install python-devel openssl-devel python-pip git gcc libxslt-devel mysql-devel postgresql-devel libffi-devel libvirt-devel graphviz sqlite-devel
RUN yum clean all

ADD https://raw.github.com/pypa/pip/master/contrib/get-pip.py /get-pip.py
RUN python /get-pip.py

RUN mkdir /data
RUN pip install wheel devpi-client
ADD run.sh /
CMD /run.sh

redpajama_set_name: RedPajamaGithub


text:
/* Magic Mirror
 * Node Helper: MMM-PrayerTime
 *
 * By Slamet PS/slametps@gmail.com
 * MIT Licensed.
 */

var NodeHelper = require("node_helper");
var async = require('async');
var exec = require('child_process').exec;

module.exports = NodeHelper.create({
	// Subclass start method.
	start: function() {
		console.log("Starting node_helper.js for MMM-PrayerTime.");
	},

	socketNotificationReceived: function(notification, payload) {
    console.log(this.name + " node helper received a socket notification: " + notification + " - Payload: " + payload);
    if (notification == "PLAY_ADZAN") {
      var adzanSound = 'adzan.mp3';
      if (payload.occasion) {
        if (payload.occasion=="FAJR") {
          adzanSound = 'adzan-fajr.mp3';
        }
        else if (payload.occasion=="IMSAK") {
          adzanSound = 'imsak.mp3';
        }
      }
      var adzanCmd = '/usr/bin/omxplayer -o both modules/MMM-PrayerTime/res/' + adzanSound + ' &';
      async.parallel([
        async.apply(exec, adzanCmd)
      ],
      function (err, res) {
      });
    }
	else if (notification == "TELEGRAM_ALERT") {
		var chat_ids = payload.telegramAlert_params[0];
		chat_ids.forEach(function(chat_id) {
			var telegramCmd = "curl -s --max-time 10 -d 'chat_id=" + chat_id + "&disable_web_page_preview=1&text=" + encodeURI(payload.telegramTxt).replace(/'/g, '%27') + "' https://api.telegram.org/bot" + payload.telegramAlert_params[1] + "/sendMessage";
			async.parallel([
				async.apply(exec, telegramCmd)
			],
			function (err, res) {
			});
		});
	}
  }
});


text:
layout: project
title: Teaching
categories: [project]
order: 9
splash: "/images/teaching/splash.jpg"
---

## Teaching and Mentoring

- Victoria University, TAFE division: I devised and delivered and introduction to games programming for designers.
- Footscray Primary School: I started and ran an after school games making class.
- Academy of Interactive Entertainment: I was invited in a number of times to judge and give feedback on students projects.
- Transmission Games: I initiated and lead a group of programmers through C#/.NET training.


text:
require 'fog/core/collection'
require 'fog/rackspace/models/load_balancers/node'

module Fog
  module Rackspace
    class LoadBalancers
      class Nodes < Fog::Collection
        model Fog::Rackspace::LoadBalancers::Node

        attr_accessor :load_balancer

        def all
          requires :load_balancer
          data = service.list_nodes(load_balancer.id).body['nodes']
          load(data)
        end

        def get(node_id)
          requires :load_balancer
          if node = service.get_node(load_balancer.id, node_id).body['node']
            new(node)
          end
        rescue Fog::Rackspace::LoadBalancers::NotFound
          nil
        end
      end
    end
  end
end


text:
//
//  QBMEventPagedResult.h
//  Quickblox
//
//  Created by Igor Khomenko on 7/19/12.
//  Copyright (c) 2012 QuickBlox. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Result.h"

/** QBMEventPagedResult class declaration. */
/** Overview */
/** This class is an instance, which will be returned to user after he made the request for get events. */

@interface QBMEventPagedResult : Result

/** Array of QBMEvent objects */
@property (nonatomic,readonly) NSArray *events;

@end


text:
/**
 * \file
 * \brief Joybubbles GUI toolkit
 */

#ifndef JOY_BUBBLES_H
#define JOY_BUBBLES_H

#include <joy/animation/fade.h>
#include <joy/animation/move.h>
#include <joy/animation/parallel.h>
#include <joy/animation/resize.h>
#include <joy/animation/series.h>
#include <joy/application.h>
#include <joy/bubble.h>
#include <joy/button.h>
#include <joy/container.h>
#include <joy/easing.h>
#include <joy/filter/gaussian.h>
#include <joy/image.h>
#include <joy/iterator.h>
#include <joy/label.h>
#include <joy/screen.h>
#include <joy/sketch.h>
#include <joy/window.h>

#endif // JOY_BUBBLES_H


text:
var db = require('../dbConfig');
var Keyword = require('../models/keywordModel.js');

var Keywords = new db.Collection();

Keywords.model = Keyword;

module.exports = Keywords;


text:
#ifndef __avmplus_AbcParser__
#define __avmplus_AbcParser__

namespace avmplus
{
	/**
	 * Parser for reading .abc (Actionscript Byte Code) files.
	 */
	class AbcParser
	{
	public:
		AbcParser(AvmCore* core, ScriptBuffer code,
			Toplevel* toplevel,
			Domain* domain,
			const NativeInitializer* natives,
			const List<Stringp>* keepVersions = NULL);

		~AbcParser();

		/**
		 * parse an .abc file
		 * @param code
		 * @return
		 */
		static PoolObject* decodeAbc(AvmCore* core, ScriptBuffer code,
			Toplevel* toplevel,
			Domain* domain,
			const NativeInitializer* natives,
			const List<Stringp>* keepVersions = NULL);

	protected:
		PoolObject* parse();
		AbstractFunction* resolveMethodInfo(uint32 index) const;

		#ifdef AVMPLUS_VERBOSE
		void parseTypeName(const byte* &p, Multiname& m) const;
		#endif

		Namespacep parseNsRef(const byte* &pc) const;
		Stringp resolveUtf8(uint32 index) const;
		Stringp parseName(const byte* &pc) const;
		void resolveQName(const byte* &pc, Multiname &m) const;
		uint32_t computeInstanceSize(int class_id, Traits* base) const;
		void parseMethodInfos();
		void parseMetadataInfos();
		bool parseInstanceInfos();
		void parseClassInfos();
		bool parseScriptInfos();
		void parseMethodBodies();
		void parseCpool();
		Traits* parseTraits(uint32_t sizeofInstance,
							Traits* base,
							Namespacep ns,
							Stringp name,
							AbstractFunction* script,
							TraitsPosPtr traitsPos,
							TraitsPosType posType,
							Namespacep protectedNamespace);

		/**
		 * add script to VM-wide table
		 */
		void addNamedScript(Namespacep ns, Stringp name, AbstractFunction* script);

		/**
		 * Adds traits to the VM-wide traits table, for types
		 * that can be accessed from multiple abc's.
		 * @param name The name of the class
		 * @param ns The namespace of the class
		 * @param itraits The instance traits of the class
		 */
		void addNamedTraits(Namespacep ns, Stringp name, Traits* itraits);

		/**
		 * reads in 8 bytes in little endian order and stores in
		 * memory as an ieee double, doing endian swapping as needed
		 */
		double readDouble(const byte* &p) const;

        /**
         * Reads in 2 bytes and turns them into a 16 bit number.  Always reads in 2 bytes.  Currently
         * only used for version number of the ABC file and for version 11 support.
         */
		int readU16(const byte* p) const
		{
#ifdef SAFE_PARSE
			if (p < abcStart || p+1 >= abcEnd)
				toplevel->throwVerifyError(kCorruptABCError);
#endif //SAFE_PARSE
			return p[0] | p[1]<<8;
		}

        /**
         * Read in a 32 bit number that is encoded with a variable number of bytes.  The value can
         * take up 1-5 bytes depending on its value.  0-127 takes 1 byte, 128-16383 takes 2 bytes, etc.
         * The scheme is that if the current byte has the high bit set, then the following byte is also
         * part of the value.
         *
         * Returns the value, and the 2nd argument is set to the number of bytes that were read to get that
         * value.
         */
		int readS32(const byte *&p) const
		{
#ifdef SAFE_PARSE
			// We have added kBufferPadding bytes to the end of the main swf buffer.
			// Why?  Here we can read from 1 to 5 bytes.  If we were to
			// put the required safety checks at each byte read, we would slow
			// parsing of the file down.  With this buffer, only one check at the
			// top of this function is necessary. (we will read on into our own memory)
		    if ( p < abcStart || p >= abcEnd )
				toplevel->throwVerifyError(kCorruptABCError);
#endif //SAFE_PARSE

			int result = p[0];
			if (!(result & 0x00000080))
			{
				p++;
				return result;
			}
			result = (result & 0x0000007f) | p[1]<<7;
			if (!(result & 0x00004000))
			{
				p += 2;
				return result;
			}
			result = (result & 0x00003fff) | p[2]<<14;
			if (!(result & 0x00200000))
			{
				p += 3;
				return result;
			}
			result = (result & 0x001fffff) | p[3]<<21;
			if (!(result & 0x10000000))
		{
				p += 4;
				return result;
			}
			result = (result & 0x0fffffff) | p[4]<<28;
			p += 5;
			return result;
		}

		uint32_t readU30(const byte*& p) const;

	// ------------------------ DATA SECTION BEGIN
	private:
		ScriptBuffer				code;
		List<Traits*>				instances;
		Toplevel* const				toplevel;
		Domain* const				domain;
		AvmCore*					core;
		PoolObject*					pool;
		const byte*					pos;
		const NativeInitializer*	natives;
		byte*						abcStart;
		byte*						abcEnd; // one past the end, actually
		Stringp*					metaNames;
		Stringp						kNeedsDxns;
		const List<Stringp>*		keepVersions;
#ifdef AVMPLUS_VERBOSE
		Stringp 					kVerboseVerify;
#endif
#ifdef FEATURE_BUFFER_GUARD // no Carbon
		BufferGuard*				guard;
#endif
		int32_t						version;
		uint32_t					classCount;
	// ------------------------ DATA SECTION END
	};

}

#endif // __avmplus_AbcParser__


text:
package elastic

import (
	"encoding/json"
	"testing"
)

func TestTermFilter(t *testing.T) {
	f := NewTermFilter("user", "ki")
	f = f.Cache(true)
	f = f.CacheKey("MyTermFilter")
	f = f.FilterName("MyFilterName")
	data, err := json.Marshal(f.Source())
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"term":{"_cache":true,"_cache_key":"MyTermFilter","_name":"MyFilterName","user":"ki"}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}


text:
<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use Zend\Form\Annotation\AnnotationBuilder;
use Application\Model\Student;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return new ViewModel();
    }

    public function holaAction()
    {
        return new ViewModel(array('hi'=>'hola mundo!'));
    }

    public function addAction()
    {
        $student    = new Student();
        $builder    = new AnnotationBuilder();
        $form       = $builder->createForm($student);

        $request = $this->getRequest();
        if ($request->isPost()){
            $form->bind($student);
            $form->setData($request->getPost());
            if ($form->isValid()){
                print_r($form->getData());
            }
        }
        return array('form'=>$form);
    }
}


text:
title: "sponsors"
bg: light-green
color: black
fa-icon: certificate
---


text:
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
        <meta charset="utf-8">

        <link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/style.min.css" type="text/css">
        <link rel="stylesheet" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/A360.css" type="text/css">

        {{ headContent() }}


text:
//
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
//

using System.Reflection;

[assembly: AssemblyProduct("Accord.NET Framework")]
[assembly: AssemblyCopyright("Copyright © César Souza, 2009-2014")]
[assembly: AssemblyCompany("Accord.NET")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: AssemblyVersion("2.12.0")]
[assembly: AssemblyInformationalVersion("2.12.0")]
[assembly: AssemblyFileVersion("2.12.0.4750")]


text:
package org.apache.geronimo.testsuite.testset;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.geronimo.testsupport.TestSupport;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

public class JaxWSRestTest extends TestSupport {

    private String baseURL = "http://localhost:8080/";

    @Test
    public void testGET() throws Exception {
        String warName = System.getProperty("webAppName");
        assertNotNull("Web application name not specified", warName);

        URL url = new URL(baseURL + warName + "/calculator?num1=10&num2=50");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        try {
            String reply = call(conn);

            assertEquals("responseCode", 200, conn.getResponseCode());

            InputSource is = new InputSource(new StringReader(reply));
            Document doc = parseMessage(is);

            Text replyMsg = findText(doc.getDocumentElement(), "60");
            assertTrue("reply message", replyMsg != null);

        } finally {
            conn.disconnect();
        }
    }

    @Test(dependsOnMethods = {"testGET"})
    public void testPOST() throws Exception {
        String warName = System.getProperty("webAppName");
        assertNotNull("Web application name not specified", warName);

        InputStream requestInput = JaxWSRestTest.class.getResourceAsStream("/request1.xml");
        assertNotNull("SOAP request not specified", requestInput);

        URL url = new URL(baseURL + warName + "/calculator");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        try {
            String reply = call(requestInput, conn);

            assertEquals("responseCode", 200, conn.getResponseCode());

            InputSource is = new InputSource(new StringReader(reply));
            Document doc = parseMessage(is);

            Text replyMsg = findText(doc.getDocumentElement(), "120");
            assertTrue("reply message", replyMsg != null);

        } finally {
            conn.disconnect();
        }
    }

    private Document parseMessage(InputSource is) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(is);
        return doc;
    }

    private Text findText(Element element, String value) {
        NodeList list = element.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node child = (Node)list.item(i);
            if (child instanceof Text) {
                Text text = (Text)child;
                if (text.getData().indexOf(value) != -1) {
                    return text;
                }
            } else if (child instanceof Element) {
                Element childEl = (Element)child;
                Text text = findText(childEl, value);
                if (text != null) {
                    return text;
                }
            }
        }
        return null;
    }

    private String call(HttpURLConnection conn) throws IOException {
        return call(null, conn);
    }

    private String call(InputStream requestInput, HttpURLConnection conn) throws IOException {
        conn.setConnectTimeout(30 * 1000);
        conn.setReadTimeout(30 * 1000);
        conn.setDoInput(true);
        conn.setUseCaches(false);

        if (requestInput == null) {
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/xml");

            conn.connect();
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/xml");

            conn.connect();

            OutputStream out = conn.getOutputStream();

            byte[] data = new byte[1024];
            int read = 0;
            while ((read = requestInput.read(data, 0, data.length)) != -1) {
                out.write(data, 0, read);
            }

            requestInput.close();

            out.flush();
            out.close();
        }

        InputStream is = null;

        try {
            is = conn.getInputStream();
        } catch (IOException e) {
            is = conn.getErrorStream();
        }

        StringBuilder buf = new StringBuilder();
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
            buf.append(inputLine);
        }
        in.close();

        return buf.toString();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/bg_album">

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_introduce"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="4">
    </android.support.v4.view.ViewPager>

    <LinearLayout
        android:id="@+id/layout_dots"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="@dimen/activity_margin_big"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/img_introduce_1"
            android:layout_width="10dip"
            android:layout_height="10dip"
            android:layout_marginRight="10dip"
            android:src="@drawable/img_introduce_dot_foucs"/>

        <ImageView
            android:id="@+id/img_introduce_2"
            android:layout_width="10dip"
            android:layout_height="10dip"
            android:layout_marginRight="10dip"
            android:src="@drawable/img_introduce_dot"/>

        <ImageView
            android:id="@+id/img_introduce_3"
            android:layout_width="10dip"
            android:layout_height="10dip"
            android:layout_marginRight="10dip"
            android:src="@drawable/img_introduce_dot"/>

        <ImageView
            android:id="@+id/img_introduce_4"
            android:layout_width="10dip"
            android:layout_height="10dip"
            android:layout_marginRight="10dip"
            android:src="@drawable/img_introduce_dot"/>

        <ImageView
            android:id="@+id/img_introduce_5"
            android:layout_width="10dip"
            android:layout_height="10dip"
            android:layout_marginRight="10dip"
            android:src="@drawable/img_introduce_dot"/>

        <ImageView
            android:id="@+id/img_introduce_6"
            android:layout_width="10dip"
            android:layout_height="10dip"
            android:layout_marginRight="10dip"
            android:src="@drawable/img_introduce_dot"/>
    </LinearLayout>

    <ImageView
        android:id="@+id/btn_introduce_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/layout_dots"
        android:layout_centerHorizontal="true"
        android:src="@drawable/btn_guide_enter"
        android:visibility="gone"/>

    <com.yydcdut.note.view.CircleProgressBarLayout
        android:id="@+id/layout_progress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:visibility="gone">
    </com.yydcdut.note.view.CircleProgressBarLayout>

</RelativeLayout>


text:
import unittest
import bifrost as bf
import numpy as np
from bifrost import blocks
from bifrost import pipeline as bfp

class CallbackBlock(blocks.CopyBlock):
    """Testing-only block which calls user-defined
        functions on sequence and on data"""
    def __init__(self, iring, seq_callback, data_callback, data_ref=None,
                 *args, **kwargs):
        super(CallbackBlock, self).__init__(iring, *args, **kwargs)
        self.seq_callback  = seq_callback
        self.data_callback = data_callback
        self.data_ref = data_ref
    def on_sequence(self, iseq):
        self.seq_callback(iseq)
        return super(CallbackBlock, self).on_sequence(iseq)
    def on_data(self, ispan, ospan):
        self.data_callback(ispan, ospan)
        if self.data_ref is not None:
            # Note: This can be used to check data from outside the pipeline,
            #         which is useful when exceptions inside blocks prevent
            #         downstream callback blocks from ever executing.
            self.data_ref['odata'] = ospan.data.copy()
        return super(CallbackBlock, self).on_data(ispan, ospan)

class BinaryIOTest(unittest.TestCase):
    """Test simple IO for the binary read/write blocks"""
    def setUp(self):
        """Generate some dummy data to read"""
        # Generate test vector and save to file
        t = np.arange(32768 * 1024)
        w = 0.01
        self.s0 = np.sin(w * t, dtype='float32')
        self.s0.tofile('numpy_data0.bin')
        self.s1 = np.sin(w * 4 * t, dtype='float32')
        self.s1.tofile('numpy_data1.bin')

        # Setup pipeline
        self.filenames = ['numpy_data0.bin', 'numpy_data1.bin']
    def test_read_write(self):
        """Read from a binary file, then write to another one"""
        b_read = blocks.binary_read(self.filenames, 32768, 1, 'f32')
        b_write = blocks.binary_write(b_read.orings[0])

        # Run pipeline
        pipeline = bfp.get_default_pipeline()
        pipeline.run()

        # Check the output files match the input files
        outdata0 = np.fromfile('numpy_data0.bin.out', dtype='float32')
        outdata1 = np.fromfile('numpy_data1.bin.out', dtype='float32')

        np.testing.assert_almost_equal(self.s0, outdata0)
        np.testing.assert_almost_equal(self.s1, outdata1)
    def test_header_compliance(self):
        """Make sure that the binary in has all required header labels"""
        def seq_callback(iseq):
            for key in ['_tensor']:
                self.assertTrue(bool(key in iseq.header))
            for key in ['units', 'labels', 'scales', 'dtype', 'shape']:
                self.assertTrue(key in iseq.header['_tensor'])
            self.assertTrue(type(iseq.header['_tensor']['scales'][0]) is list)
        def data_callback(ispan, ospan):
            pass

        self.fil_file = "./data/2chan16bitNoDM.fil"
        with bf.Pipeline() as pipeline:
            b_read = blocks.binary_read(self.filenames, 32768, 1, 'f32')
            callback = CallbackBlock(b_read, seq_callback, data_callback)

            pipeline.run()


text:
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Christian Schulte <schulte@gecode.org>
 *     Mikael Lagerkvist <lagerkvist@gecode.org>
 *
 *  Copyright:
 *     Christian Schulte, 2008
 *     Mikael Lagerkvist, 2008
 *
 *  Last modified:
 *     $Date: 2011-05-11 12:44:17 +0200 (Wed, 11 May 2011) $ by $Author: tack $
 *     $Revision: 12001 $
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include <gecode/kernel.hh>

namespace Gecode {

  const VarBranchOptions VarBranchOptions::def;

  const ValBranchOptions ValBranchOptions::def;

  const TieBreakVarBranchOptions TieBreakVarBranchOptions::def;

  /*
   * Function brancher
   */

  /// %Brancher for calling a function
  class GECODE_KERNEL_EXPORT FunctionBranch : public Brancher {
  protected:
    /// Minimal brancher description storing no information
    class GECODE_KERNEL_EXPORT Description : public Choice {
    public:
      /// Initialize description for brancher \a b, number of alternatives \a a.
      Description(const Brancher& b, unsigned int a) : Choice(b,a) {}
      /// Report size occupied
      virtual size_t size(void) const { return sizeof(Description); }
      /// Archive into \a e
      virtual void archive(Archive& e) const {
        Choice::archive(e);
      }
    };
    /// Function to call
    void (*f)(Space&);
    /// Call function just once
    bool done;
    /// Construct brancher
    FunctionBranch(Home home, void (*f0)(Space&))
      : Brancher(home), f(f0), done(false) {}
    /// Copy constructor
    FunctionBranch(Space& home, bool share, FunctionBranch& b)
      : Brancher(home,share,b), f(b.f), done(b.done) {}
  public:
    /// Check status of brancher, return true if alternatives left
    virtual bool status(const Space&) const {
      return !done;
    }
    /// Return choice
    virtual const Choice* choice(Space&) {
      assert(!done);
      return new Description(*this,1);
    }
    /// Return choice
    virtual const Choice* choice(const Space&, Archive&) {
      return new Description(*this,1);
    }
    /// Perform commit
    virtual ExecStatus
    commit(Space& home, const Choice&, unsigned int) {
      done = true;
      f(home);
      return home.failed() ? ES_FAILED : ES_OK;
    }
    /// Copy brancher
    virtual Actor* copy(Space& home, bool share) {
      return new (home) FunctionBranch(home,share,*this);
    }
    /// Post brancher
    static void post(Home home, void (*f)(Space&)) {
      (void) new (home) FunctionBranch(home,f);
    }
  };

  void
  branch(Home home, void (*f)(Space& home)) {
    if (home.failed())
      return;
    FunctionBranch::post(home,f);
  }

}

// STATISTICS: kernel-branch


text:
/*
 * File:   JsonWriter.hpp
 * Author: Paolo D'Apice
 *
 * Created on January 10, 2012, 11:18 AM
 */

#ifndef JSONWRITER_HPP
#define	JSONWRITER_HPP

#include "net/sf1r/config.h"
#include "Writer.hpp"

NS_IZENELIB_SF1R_BEGIN

/**
 * Class implementing the Writer interface for the JSON format.
 */
class JsonWriter : public Writer {
public:
    JsonWriter();
    ~JsonWriter();

    void setHeader(const std::string& controller,
                   const std::string& action,
                   const std::string& tokens,
                   std::string& request,
                   std::string& collection) const;

    bool checkData(const std::string& data) const;

};

NS_IZENELIB_SF1R_END

#endif	/* JSONWRITER_HPP */


text:
package org.wso2.carbon.governance.registry.extensions.utils;

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.wso2.carbon.governance.api.exception.GovernanceException;
import org.wso2.carbon.registry.core.exceptions.RegistryException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import static org.wso2.carbon.governance.registry.extensions.executors.utils.ExecutorConstants.*;

/**
 * Created by a548347 on 05/07/2014.
 * This class will be util class for APIM related stuff.
 */
public final class APIUtils {

    /**
     * This method will authenticate the user name and password mentioned in life cycle against APIM.
     *
     * @param httpContext
     * @param apimEndpoint
     * @param apimUsername
     * @param apimPassword
     */
    public static void authenticateAPIM(HttpContext httpContext, String apimEndpoint, String apimUsername, String apimPassword)  throws GovernanceException {

        String loginEP = apimEndpoint + Constants.APIM_LOGIN_ENDPOINT;
        try {
            // create a post request to addAPI.
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(loginEP);
            // Request parameters and other properties.
            List<NameValuePair> params = new ArrayList<NameValuePair>(Constants.APIM_PARAMETER_COUNT);

            params.add(new BasicNameValuePair(API_ACTION, API_LOGIN_ACTION));
            params.add(new BasicNameValuePair(API_USERNAME, apimUsername));
            params.add(new BasicNameValuePair(API_PASSWORD, apimPassword));
            httppost.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));

            HttpResponse response = httpclient.execute(httppost, httpContext);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, Constants.UTF_8_ENCODE);
            if (response.getStatusLine().getStatusCode() != Constants.SUCCESS_RESPONSE_CODE) {
                throw new RegistryException(" Authentication with APIM failed: HTTP error code : " +
                        response.getStatusLine().getStatusCode());
            }

            Gson gson = new Gson();
            ResponseAPIM responseAPIM = gson.fromJson(responseString, ResponseAPIM.class);
            if (responseAPIM.getError().equalsIgnoreCase("true")) {
                throw new GovernanceException("Error occurred in validating the user. Please check the credentials");
            }

        } catch (Exception e) {
            throw new GovernanceException("Authentication failed with API Manager. Please check the credentials", e);
        }
    }

    /**
     * This method will authenticate the user name and password mentioned in life cycle against APIM 2.0.0.
     *
     * @param httpContext
     * @param apimEndpoint
     * @param apimUsername
     * @param apimPassword
     */
    public static String authenticateAPIM_2(HttpContext httpContext, String apimEndpoint, String apimUsername, String apimPassword)  throws GovernanceException {

        String loginEP = apimEndpoint + Constants.APIM_2_0_0_LOGIN_ENDPOINT;
        try {
            // create a post request to addAPI.
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(loginEP);
            // Request parameters and other properties.
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair(API_USERNAME, apimUsername));
            params.add(new BasicNameValuePair(API_PASSWORD, apimPassword));
            httppost.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));

            HttpResponse response = httpclient.execute(httppost, httpContext);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, Constants.UTF_8_ENCODE);
            if (response.getStatusLine().getStatusCode() != Constants.SUCCESS_RESPONSE_CODE) {
                throw new RegistryException(" Authentication with APIM failed: HTTP error code : " +
                        response.getStatusLine().getStatusCode());
            }

            JSONObject obj = new JSONObject(responseString);
            return obj.getJSONObject("data").getString("sessionId");

        } catch (Exception e) {
            throw new GovernanceException("Authentication failed with API Manager. Please check the credentials", e);
        }
    }

    /**
     * This method will publish api to APIM.
     * @param httpclient
     * @param httppost
     * @param params
     * @param httpContext
     * @return
     */
    public static ResponseAPIM callAPIMToPublishAPI(HttpClient httpclient, HttpPost httppost, List<NameValuePair> params,
                                             HttpContext httpContext)  throws GovernanceException {
        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));
            HttpResponse response = httpclient.execute(httppost, httpContext);
            if (response.getStatusLine().getStatusCode() != Constants.SUCCESS_RESPONSE_CODE) { // 200 is the successful response status code
                throw new RegistryException("Failed : HTTP error code : " +
                        response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, Constants.UTF_8_ENCODE);
            Gson gson = new Gson();
            return gson.fromJson(responseString, ResponseAPIM.class);

        } catch (java.net.SocketTimeoutException e) {
            throw new GovernanceException("Connection timed out, Please check the network availability", e);
        } catch (UnsupportedEncodingException e) {
            throw new GovernanceException("Unsupported encode exception.", e);
        } catch (IOException e) {
            throw new GovernanceException("IO Exception occurred.", e);
        } catch (Exception e) {
            throw new GovernanceException(e.getMessage(), e);
        }
    }

    /**
     * This method will publish api to APIM 2.0.0.
     * @param httpclient
     * @param httppost
     * @param params
     * @param httpContext
     * @return
     */
    public static ResponseAPIM callAPIMToPublishAPI2(HttpClient httpclient, HttpPost httppost, List<NameValuePair> params,
                                                    HttpContext httpContext)  throws GovernanceException {
        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));
            HttpResponse response = httpclient.execute(httppost, httpContext);
            if (response.getStatusLine().getStatusCode() != Constants.CREATED_RESPONSE_CODE) { // 201 is the successful response status code
                throw new RegistryException("Failed : HTTP error code : " +
                        response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, Constants.UTF_8_ENCODE);
            return null;

        } catch (java.net.SocketTimeoutException e) {
            throw new GovernanceException("Connection timed out, Please check the network availability", e);
        } catch (UnsupportedEncodingException e) {
            throw new GovernanceException("Unsupported encode exception.", e);
        } catch (IOException e) {
            throw new GovernanceException("IO Exception occurred.", e);
        } catch (Exception e) {
            throw new GovernanceException(e.getMessage(), e);
        }
    }
}


text:
package com.orientechnologies.orient.etl;

import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.etl.extractor.OAbstractExtractor;

import java.io.Reader;
import java.util.Random;

/**
 * ETL Mock loader to check the result in tests.
 *
 * @author Luca Garulli on 27/11/14.
 */
public class RandomExtractor extends OAbstractExtractor {
  private long current = 0;
  private int  fields;
  private long items;
  private int  delay   = 0;

  @Override
  public void configure(OETLProcessor iProcessor, ODocument iConfiguration, OCommandContext iContext) {
    super.configure(iProcessor, iConfiguration, iContext);

    if (iConfiguration.containsField("items"))
      items = ((Number) iConfiguration.field("items")).longValue();
    if (iConfiguration.containsField("fields"))
      fields = iConfiguration.field("fields");
    if (iConfiguration.containsField("delay"))
      delay = iConfiguration.field("delay");
  }

  @Override
  public void extract(final Reader iReader) {
  }

  @Override
  public String getUnit() {
    return "row";
  }

  @Override
  public boolean hasNext() {
    return current < items;
  }

  @Override
  public OExtractedItem next() {
    final ODocument doc = new ODocument();

    for (int i = 0; i < fields; ++i) {
      doc.field("field" + i, "value_" + new Random().nextInt(30));
    }

    if (delay > 0)
      // SIMULATE A SLOW DOWN
      try {
        Thread.sleep(delay);
      } catch (InterruptedException e) {
      }

    return new OExtractedItem(current++, doc);
  }

  @Override
  public String getName() {
    return "random";
  }
}


text:
package com.espirit.moddev.cli.commands.project.activateWebServerCommand;

import com.espirit.moddev.shared.webapp.WebAppIdentifier;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Class that represents all parameters for the "activatewebserver" command.
 */
public class ProjectWebServerActivationParameter {

    private final String projectName;
    private final List<WebAppIdentifier> scopes;
    private final String serverName;
    private final boolean forceActivation;

    public ProjectWebServerActivationParameter(String projectName, List<WebAppIdentifier> scopes, String serverName, boolean forceActivation) {
        if(projectName == null || projectName.isEmpty()) {
            throw new IllegalArgumentException("Project name should not be null or empty");
        }
        if(scopes == null || scopes.isEmpty()) {
            throw new IllegalArgumentException("Scopes should not be null or empty");
        }
        if(serverName == null || serverName.isEmpty()) {
            throw new IllegalArgumentException("Server name should not be null or empty");
        }
        this.projectName = projectName;
        this.scopes = new ArrayList<>(scopes);
        this.serverName = serverName;
        this.forceActivation = forceActivation;
    }

    public String getProjectName() {
        return projectName;
    }

    public List<WebAppIdentifier> getScopes() {
        return Collections.unmodifiableList(scopes);
    }

    public String getServerName() {
        return serverName;
    }

    public boolean isForceActivation() {
        return forceActivation;
    }

    public static ProjectWebServerActivationParameterBuilder builder() {
        return new ProjectWebServerActivationParameterBuilder();
    }
}


text:
    <title>Application Requirements</title>

Como usuario deseo conocer centros polideportivos municipales.

Como usuario deseo conocer instalaciones deportivas mucipales.

Como usuario deseo conocer zonas de estacionamiento regulado SER.

Como usuario deseo conocer aparcamientos públicos municipales.


text:
define([], function () {
    'use strict';

    function PceMenuItemService(PceMenuModel, PceMenuItemModel, Restangular) {

        this.createPceMenu = createPceMenu;
        this.loadMainMenu = loadMainMenu;

        /**
         * Implementations
         */

        /**
         * Creates PceMenu object, fills it with menuData (if available), adds methods and returns the object.
         * @param menuData
         * @returns PceMenuModel
         */
        function createPceMenu (menuData) {
            var result = new PceMenuModel(),
                itemsList = [];

            if(menuData) {
                itemsList = menuData.map(createItem);

                function createItem(dataObj){
                    var newItemObj = new PceMenuItemModel();
                    newItemObj.setData(dataObj);
                    if(dataObj.hasOwnProperty('submenu') && dataObj.submenu.length){
                        newItemObj.setSubMenu(createPceMenu(dataObj.submenu));
                    }
                    return newItemObj;
                }
            }
            result.setItems(itemsList);

            result.pageExists = pageExists;
            result.setActivePage = setActivePage;
            return result;

        }

        function setActivePage(pageName){
            /*jshint validthis:true */
            var self = this;
            var result = false;

            self.items.forEach(setActive);

            function setActive(menuItemObj){
                if(menuItemObj.subMenu === null){
                    menuItemObj.active = menuItemObj.url === '#/pce/' + pageName;
                }
                else{
                    menuItemObj.active = menuItemObj.subMenu.setActivePage(pageName);
                }
                result = result || menuItemObj.active;
            }
            return result;
        }

        function pageExists(pageName){
            /*jshint validthis:true */
            var self = this;
            var result = false;

            self.items.forEach(existingPage);

            function existingPage(menuItemObj){
                if(menuItemObj.subMenu === null){
                    result = result || menuItemObj.url === '#/pce/' + pageName;
                }
                else{
                    result = result || menuItemObj.subMenu.pageExists(pageName);
                }

            }
            return result;

        }

        function loadMainMenu(){
            return Restangular.oneUrl('mainMenu','./app/modules/pce/data/pce-menu.json').get();
        }
    }

    PceMenuItemService.$inject=['PceMenuModel', 'PceMenuItemModel', 'Restangular'];

    return PceMenuItemService;

});


text:
import test from 'ava'
import React from 'react'
import { shallow } from 'enzyme'

const Foo = ({ children }) =>

      bar
      {children}
      bar

Foo.propTypes = {
  children: React.PropTypes.any
}

test('has a .Foo class name', t => {
  const wrapper = shallow(<Foo/>)
  t.true(wrapper.hasClass('Foo'))
})

test('renders two `.Bar`', t => {
  const wrapper = shallow(<Foo/>)
  t.is(wrapper.find('.bar').length, 2)
})

test('renders children when passed in', t => {
  const wrapper = shallow(
    <Foo>

    </Foo>
  )
  t.true(wrapper.contains(
))
})


text:
using System;
using Azure.Core;
using Azure.ResourceManager.Kusto;
using Azure.ResourceManager.Models;

namespace Azure.ResourceManager.Kusto.Models
{
    /// <summary> Class representing an Event Grid data connection. </summary>
    public partial class KustoEventGridDataConnection : KustoDataConnectionData
    {
        /// <summary> Initializes a new instance of KustoEventGridDataConnection. </summary>
        public KustoEventGridDataConnection()
        {
            Kind = DataConnectionKind.EventGrid;
        }

        /// <summary> Initializes a new instance of KustoEventGridDataConnection. </summary>
        /// <param name="id"> The id. </param>
        /// <param name="name"> The name. </param>
        /// <param name="resourceType"> The resourceType. </param>
        /// <param name="systemData"> The systemData. </param>
        /// <param name="location"> Resource location. </param>
        /// <param name="kind"> Kind of the endpoint for the data connection. </param>
        /// <param name="storageAccountResourceId"> The resource ID of the storage account where the data resides. </param>
        /// <param name="eventGridResourceId"> The resource ID of the event grid that is subscribed to the storage account events. </param>
        /// <param name="eventHubResourceId"> The resource ID where the event grid is configured to send events. </param>
        /// <param name="consumerGroup"> The event hub consumer group. </param>
        /// <param name="tableName"> The table where the data should be ingested. Optionally the table information can be added to each message. </param>
        /// <param name="mappingRuleName"> The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. </param>
        /// <param name="dataFormat"> The data format of the message. Optionally the data format can be added to each message. </param>
        /// <param name="isFirstRecordIgnored"> A Boolean value that, if set to true, indicates that ingestion should ignore the first record of every file. </param>
        /// <param name="blobStorageEventType"> The name of blob storage event type to process. </param>
        /// <param name="managedIdentityResourceId"> The resource ID of a managed identity (system or user assigned) to be used to authenticate with event hub and storage account. </param>
        /// <param name="managedIdentityObjectId"> The object ID of managedIdentityResourceId. </param>
        /// <param name="databaseRouting"> Indication for database routing information from the data connection, by default only database routing information is allowed. </param>
        /// <param name="provisioningState"> The provisioned state of the resource. </param>
        internal KustoEventGridDataConnection(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, AzureLocation? location, DataConnectionKind kind, ResourceIdentifier storageAccountResourceId, ResourceIdentifier eventGridResourceId, ResourceIdentifier eventHubResourceId, string consumerGroup, string tableName, string mappingRuleName, KustoEventGridDataFormat? dataFormat, bool? isFirstRecordIgnored, BlobStorageEventType? blobStorageEventType, ResourceIdentifier managedIdentityResourceId, Guid? managedIdentityObjectId, KustoDatabaseRouting? databaseRouting, KustoProvisioningState? provisioningState) : base(id, name, resourceType, systemData, location, kind)
        {
            StorageAccountResourceId = storageAccountResourceId;
            EventGridResourceId = eventGridResourceId;
            EventHubResourceId = eventHubResourceId;
            ConsumerGroup = consumerGroup;
            TableName = tableName;
            MappingRuleName = mappingRuleName;
            DataFormat = dataFormat;
            IsFirstRecordIgnored = isFirstRecordIgnored;
            BlobStorageEventType = blobStorageEventType;
            ManagedIdentityResourceId = managedIdentityResourceId;
            ManagedIdentityObjectId = managedIdentityObjectId;
            DatabaseRouting = databaseRouting;
            ProvisioningState = provisioningState;
            Kind = kind;
        }

        /// <summary> The resource ID of the storage account where the data resides. </summary>
        public ResourceIdentifier StorageAccountResourceId { get; set; }
        /// <summary> The resource ID of the event grid that is subscribed to the storage account events. </summary>
        public ResourceIdentifier EventGridResourceId { get; set; }
        /// <summary> The resource ID where the event grid is configured to send events. </summary>
        public ResourceIdentifier EventHubResourceId { get; set; }
        /// <summary> The event hub consumer group. </summary>
        public string ConsumerGroup { get; set; }
        /// <summary> The table where the data should be ingested. Optionally the table information can be added to each message. </summary>
        public string TableName { get; set; }
        /// <summary> The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. </summary>
        public string MappingRuleName { get; set; }
        /// <summary> The data format of the message. Optionally the data format can be added to each message. </summary>
        public KustoEventGridDataFormat? DataFormat { get; set; }
        /// <summary> A Boolean value that, if set to true, indicates that ingestion should ignore the first record of every file. </summary>
        public bool? IsFirstRecordIgnored { get; set; }
        /// <summary> The name of blob storage event type to process. </summary>
        public BlobStorageEventType? BlobStorageEventType { get; set; }
        /// <summary> The resource ID of a managed identity (system or user assigned) to be used to authenticate with event hub and storage account. </summary>
        public ResourceIdentifier ManagedIdentityResourceId { get; set; }
        /// <summary> The object ID of managedIdentityResourceId. </summary>
        public Guid? ManagedIdentityObjectId { get; }
        /// <summary> Indication for database routing information from the data connection, by default only database routing information is allowed. </summary>
        public KustoDatabaseRouting? DatabaseRouting { get; set; }
        /// <summary> The provisioned state of the resource. </summary>
        public KustoProvisioningState? ProvisioningState { get; }
    }
}


text:
<?php

namespace Oro\Bundle\TestFrameworkBundle\BehatStatisticExtension\TestApp;

use Behat\Behat\Context\Context;

class PingPongContext implements Context
{
    /**
     * @Given ping
     */
    public function ping()
    {
    }

    /**
     * @Then pong
     */
    public function pong()
    {
    }
}


text:
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net.Sockets;

namespace Arebis.Logging.GrayLog
{
    /// <summary>
    /// A GrayLog client using the UDP protocol.
    /// </summary>
    public class GrayLogUdpClient : GrayLogClient
    {
        /// <summary>
        /// Creates a new GrayLogUdpClient using the "GrayLogFacility", "GrayLogHost" and optionally "GrayLogUdpPort" AppSettings.
        /// </summary>
        public GrayLogUdpClient()
            : this(ConfigurationManager.AppSettings["GrayLogFacility"], ConfigurationManager.AppSettings["GrayLogHost"], Int32.Parse(ConfigurationManager.AppSettings["GrayLogUdpPort"] ?? "12201"))
        { }

        /// <summary>
        /// Creates a new GrayLogUdpClient.
        /// </summary>
        /// <param name="facility">Facility to set on all sent messages.</param>
        /// <param name="host">GrayLog host name.</param>
        /// <param name="port">GrayLog UDP port.</param>
        public GrayLogUdpClient(string facility, string host, int port = 12201)
            : this(facility, new UdpClient(host, port), true)
        { }

        /// <summary>
        /// Creates a new GrayLogUdpClient.
        /// </summary>
        /// <param name="facility">Facility to set on all sent messages.</param>
        /// <param name="udpClient">UdpClient to use to sent messages to GrayLog.</param>
        public GrayLogUdpClient(string facility, UdpClient udpClient)
            : this(facility, udpClient, false)
        { }

        protected GrayLogUdpClient(string facility, UdpClient udpClient, bool udpClientIsOwned)
            : base(facility)
        {
            this.UdpClient = udpClient;
            this.UdpClientIsOwned = udpClientIsOwned;
            this.NextChunckedMessageId = new Random().Next(0, Int32.MaxValue);
            this.MaxPacketSize = Int32.Parse(ConfigurationManager.AppSettings["GrayLogUdpMaxPacketSize"] ?? "512");
        }

        private bool UdpClientIsOwned { get; set; }

        protected UdpClient UdpClient { get; private set; }

        protected long NextChunckedMessageId { get; private set; }

        /// <summary>
        /// Maximum UDP packet payload byte size used.
        /// Can also be overriden by the "GrayLogUdpMaxPacketSize" AppSetting.
        /// </summary>
        public int MaxPacketSize { get; set; }

        protected override void InternallySendMessage(byte[] messageBody)
        {
            // Get message id:
            NextChunckedMessageId++;

            // Apply compression:
            if (this.CompressionTreshold != -1 && messageBody.Length > this.CompressionTreshold)
                messageBody = this.Compress(messageBody, CompressionLevel.Optimal);

            using (var objectStream = new MemoryStream(messageBody))
            {
                // Calculate needed chunk count:
                var chunkCount = PartsNeeded(messageBody.Length, MaxPacketSize - 12);
                if (chunkCount > 128)
                {
                    Debug.WriteLine(String.Format("Error: Maximum number of GrayLog GELF UDP chuncks exceeded; {0} chuncks while maximum is {1}", chunkCount, 128));
                    throw new GrayLoggingException("Maximum number of GrayLog GELF UDP chuncks exceeded.");
                }

                // For each chunk:
                for (byte chunkNumber = 0; chunkNumber < chunkCount; chunkNumber++)
                {
                    // Create packet buffer:
                    var chunkBuffer = new byte[MaxPacketSize];

                    // Write GELF header (http://docs.graylog.org/en/latest/pages/gelf.html):
                    chunkBuffer[0x00] = (byte)0x1e;
                    chunkBuffer[0x01] = (byte)0x0f;
                    BitConverter.GetBytes(NextChunckedMessageId).CopyTo(chunkBuffer, 0x02);
                    chunkBuffer[0x0a] = chunkNumber;
                    chunkBuffer[0x0b] = (byte)chunkCount;

                    // Write body:
                    var chunkSize = 12 + objectStream.Read(chunkBuffer, 12, MaxPacketSize - 12);

                    // Send UDP packet:
                    Debug.WriteLine(String.Format("GrayLogUdpClient - Writing chunk {0} ({1}/{2}) {3:#,##0} bytes : ", NextChunckedMessageId, chunkNumber + 1, chunkCount, chunkSize) + String.Format("[{0:X2}-{1:X2}, {2:X2}-{3:X2}-{4:X2}-{5:X2}-{6:X2}-{7:X2}-{8:X2}-{9:X2}, {10:X2}, {11:X2}, [{12:X2},{13:X2},{14:X2},{15:X2},...]]", chunkBuffer[0], chunkBuffer[1], chunkBuffer[2], chunkBuffer[3], chunkBuffer[4], chunkBuffer[5], chunkBuffer[6], chunkBuffer[7], chunkBuffer[8], chunkBuffer[9], chunkBuffer[10], chunkBuffer[11], chunkBuffer[12], chunkBuffer[13], chunkBuffer[14], chunkBuffer[15]));
                    this.UdpClient.Send(chunkBuffer, chunkSize);
                }
            }
        }

        /// <summary>
        /// Disposes the client.
        /// </summary>
        public override void Dispose()
        {
            ((IDisposable)this.UdpClient).Dispose();
        }

        /// <summary>
        /// Returns the number of parts needed
        /// </summary>
        /// <param name="totalSize"></param>
        /// <param name="partSize"></param>
        /// <returns></returns>
        private static int PartsNeeded(int totalSize, int partSize)
        {
            return (totalSize + partSize - 1) / partSize;
        }
    }
}


text:
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Store;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.PushNotifications;
using Windows.Storage;

namespace PushNotificationsHelper
{
    public sealed class ChannelAndWebResponse
    {
        public PushNotificationChannel Channel {get; set;}
        public String WebResponse {get; set;}
    }

    [DataContract]
    internal class UrlData
    {
        [DataMember]
        public String Url;
        [DataMember]
        public String ChannelUri;
        [DataMember]
        public bool IsAppId;
        [DataMember]
        public DateTime Renewed;
    }

    public sealed class Notifier
    {
        private const String APP_TILE_ID_KEY = "appTileIds";
        private const String MAIN_APP_TILE_KEY = "mainAppTileKey";
        private const int DAYS_TO_RENEW = 15; // Renew if older than 15 days
        private Dictionary<String, UrlData> urls;

        public Notifier()
        {
            this.urls = new Dictionary<String, UrlData>();
            List<String> storedUrls = null;
            IPropertySet currentData = ApplicationData.Current.LocalSettings.Values;

            try
            {
                String urlString = (String)currentData[APP_TILE_ID_KEY];
                using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(urlString)))
                {
                    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(List<String>));
                    storedUrls = (List<String>)deserializer.ReadObject(stream);
                }
            }
            catch (Exception) { }

            if (storedUrls != null)
            {
                for (int i = 0; i < storedUrls.Count; i++)
                {
                    String key = storedUrls[i];
                    try
                    {
                        String dataString = (String)currentData[key];
                        using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(dataString)))
                        {
                            DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UrlData));
                            this.urls[key] = (UrlData)deserializer.ReadObject(stream);
                        }
                    }
                    catch (Exception) { }
                }
            }
        }

        private UrlData TryGetUrlData(String key)
        {
            UrlData returnedData = null;
            lock (this.urls)
            {
                if (this.urls.ContainsKey(key))
                {
                    returnedData = this.urls[key];
                }
            }

            return returnedData;
        }

        private void SetUrlData(String key, UrlData dataToSet)
        {
            lock (this.urls)
            {
                this.urls[key] = dataToSet;
            }
        }

        // Update the stored target URL
        private void UpdateUrl(String url, String channelUri, String inputItemId, bool isPrimaryTile)
        {
            String itemId = isPrimaryTile && inputItemId == null ? MAIN_APP_TILE_KEY : inputItemId;

            bool shouldSerializeTileIds = TryGetUrlData(itemId) == null;
            UrlData storedData = new UrlData() { Url = url, ChannelUri = channelUri, IsAppId = isPrimaryTile, Renewed = DateTime.Now };
            SetUrlData(itemId, storedData);

            using (MemoryStream stream = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UrlData));
                serializer.WriteObject(stream, storedData);
                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream))
                {
                    ApplicationData.Current.LocalSettings.Values[itemId] = reader.ReadToEnd();
                }
            }

            if (shouldSerializeTileIds)
            {
                SaveAppTileIds();
            }
        }

        private void SaveAppTileIds()
        {
            List<String> dataToStore;

            lock (this.urls)
            {
                dataToStore = new List<String>(this.urls.Count);
                foreach (String key in this.urls.Keys)
                {
                    dataToStore.Add(key);
                }
            }

            using (MemoryStream stream = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<String>));
                serializer.WriteObject(stream, dataToStore);
                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream))
                {
                    ApplicationData.Current.LocalSettings.Values[APP_TILE_ID_KEY] = reader.ReadToEnd();
                }
            }
        }

        // This method checks the freshness of each channel, and returns as necessary
        public IAsyncAction RenewAllAsync(bool force)
        {
            DateTime now = DateTime.Now;
            TimeSpan daysToRenew = new TimeSpan(DAYS_TO_RENEW, 0, 0, 0);
            List<Task<ChannelAndWebResponse>> renewalTasks;
            lock (this.urls)
            {
                renewalTasks = new List<Task<ChannelAndWebResponse>>(this.urls.Count);
                foreach (var keyValue in this.urls)
                {
                    UrlData dataForUpload = keyValue.Value;
                    if (force || ((now - dataForUpload.Renewed) > daysToRenew))
                    {
                        if (keyValue.Key == MAIN_APP_TILE_KEY)
                        {
                            renewalTasks.Add(OpenChannelAndUploadAsync(dataForUpload.Url).AsTask());
                        }
                        else
                        {
                            renewalTasks.Add(OpenChannelAndUploadAsync(dataForUpload.Url, keyValue.Key, dataForUpload.IsAppId).AsTask());
                        }

                    }
                }
            }
            return Task.WhenAll(renewalTasks).AsAsyncAction();
        }

        // Instead of using the async and await keywords, actual Tasks will be returned.
        // That way, components consuming these APIs can await the returned tasks
        public IAsyncOperation<ChannelAndWebResponse> OpenChannelAndUploadAsync(String url)
        {
            IAsyncOperation<PushNotificationChannel> channelOperation = PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
            return ExecuteChannelOperation(channelOperation, url, MAIN_APP_TILE_KEY, true);
        }

        public IAsyncOperation<ChannelAndWebResponse> OpenChannelAndUploadAsync(String url, String inputItemId, bool isPrimaryTile)
        {
            IAsyncOperation<PushNotificationChannel> channelOperation;
            if (isPrimaryTile)
            {
                channelOperation = PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(inputItemId);
            }
            else
            {
                channelOperation = PushNotificationChannelManager.CreatePushNotificationChannelForSecondaryTileAsync(inputItemId);
            }

            return ExecuteChannelOperation(channelOperation, url, inputItemId, isPrimaryTile);
        }

        private IAsyncOperation<ChannelAndWebResponse> ExecuteChannelOperation(IAsyncOperation<PushNotificationChannel> channelOperation, String url, String itemId, bool isPrimaryTile)
        {
            return channelOperation.AsTask().ContinueWith<ChannelAndWebResponse>((Task<PushNotificationChannel> channelTask) =>
            {
                PushNotificationChannel newChannel = channelTask.Result;
                String webResponse = "URI already uploaded";

                // Upload the channel URI if the client hasn't recorded sending the same uri to the server
                UrlData dataForItem = TryGetUrlData(itemId);

                if (dataForItem == null || newChannel.Uri != dataForItem.ChannelUri)
                {
                    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                    webRequest.Method = "POST";
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] channelUriInBytes = Encoding.UTF8.GetBytes("ChannelUri=" + WebUtility.UrlEncode(newChannel.Uri) + "&ItemId=" + WebUtility.UrlEncode(itemId));

                    Task<Stream> requestTask = webRequest.GetRequestStreamAsync();
                    using (Stream requestStream = requestTask.Result)
                    {
                        requestStream.Write(channelUriInBytes, 0, channelUriInBytes.Length);
                    }

                    Task<WebResponse> responseTask = webRequest.GetResponseAsync();
                    using (StreamReader requestReader = new StreamReader(responseTask.Result.GetResponseStream()))
                    {
                        webResponse = requestReader.ReadToEnd();
                    }
                }

                // Only update the data on the client if uploading the channel URI succeeds.
                // If it fails, you may considered setting another AC task, trying again, etc.
                // OpenChannelAndUploadAsync will throw an exception if upload fails
                UpdateUrl(url, newChannel.Uri, itemId, isPrimaryTile);
                return new ChannelAndWebResponse { Channel = newChannel, WebResponse = webResponse };
            }).AsAsyncOperation();
        }
    }
}


text:
using namespace std;

nTest::duration test_tghosgor_ctor_and_dtor(unsigned long cnt)
{
	return nTool::calc_time([&]{
		while(cnt--)
			threadpool11::Pool tp(nTest::thread_count);
	}).duration_nanoseconds();
}

nTest::duration test_tghosgor_specific_N(unsigned long cnt)
{
	threadpool11::Pool tp(nTest::thread_count);
	queue<future<void>> que;
	return nTool::calc_time([&]{
		while(cnt--)
		{
			for(auto i(nTest::thread_count);i--;)
				que.emplace(tp.postWork(function<void()>(nTest::empty)));
			while(que.size())
			{
				que.front().get();
				que.pop();
			}
		}
	}).duration_nanoseconds();
}

nTest::duration test_tghosgor_all_N(unsigned long cnt)
{
	threadpool11::Pool tp(nTest::thread_count);
	return nTool::calc_time([&]{
		while(cnt--)
		{
			for(auto i(nTest::thread_count);i--;)
				tp.postWork(function<void()>(nTest::empty));
			tp.waitAll();
		}
	}).duration_nanoseconds();
}

nTest::duration test_tghosgor_job(unsigned long cnt)
{
	threadpool11::Pool tp(nTest::thread_count);
	return nTool::calc_time([&]{
		while(cnt--)
			tp.postWork(function<void()>(nTest::empty));
		tp.waitAll();
	}).duration_nanoseconds();
}


text:
using System;
using System.Diagnostics;

namespace Shapes.Provisioning
{
	public class DebugLogger : LoggerBase
	{
		public DebugLogger(LoggingMode mode)
			: base(mode)
		{
		}

		protected override void OnWriteError(String error, Exception exception)
		{
			Debug.WriteLine("ERROR: {0}", error);
			Debug.WriteLine("EXCEPTION:", exception);
			Debug.WriteLine("");
		}

		protected override void OnWriteVerbose(String message)
		{
			Debug.WriteLine("VERBOSE: {0}", message);
		}

		protected override void OnWriteWarning(String warning)
		{
			Debug.WriteLine("WARNING: {0}", warning);
		}
	}
}


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

package util

import (
	"bytes"
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/gorilla/websocket"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/metadata"

	echopb "istio.io/istio/pkg/test/echo/proto"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		// allow all connections by default
		return true
	},
} //defaults

type pilotTestHandler struct {
	port    int
	version string
}

// Imagine a pie of different flavors.
// The flavors are the HTTP response codes.
// The chance of a particular flavor is ( slices / sum of slices ).
type codeAndSlices struct {
	httpResponseCode int
	slices           int
}

func (h *pilotTestHandler) addResponsePayload(r *http.Request, body *bytes.Buffer) { // nolint:interfacer

	body.WriteString("ServiceVersion=" + h.version + "\n")
	body.WriteString("ServicePort=" + strconv.Itoa(h.port) + "\n")
	body.WriteString("Method=" + r.Method + "\n")
	body.WriteString("URL=" + r.URL.String() + "\n")
	body.WriteString("Proto=" + r.Proto + "\n")
	body.WriteString("RemoteAddr=" + r.RemoteAddr + "\n")
	body.WriteString("Host=" + r.Host + "\n")
	for name, headers := range r.Header {
		for _, h := range headers {
			body.WriteString(fmt.Sprintf("%v=%v\n", name, h))
		}
	}

	if hostname, err := os.Hostname(); err == nil {
		body.WriteString(fmt.Sprintf("Hostname=%v\n", hostname))
	}
}

func (h *pilotTestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Header.Get("testwebsocket") != "" {
		h.WebSocketEcho(w, r)
		return
	}

	body := bytes.Buffer{}

	if err := r.ParseForm(); err != nil {
		body.WriteString("ParseForm() error: " + err.Error() + "\n")
	}

	if len(r.FormValue("url")) > 0 {
		echoClientHandler(w, r)
		return
	}

	// If the request has form ?codes=code[:chance][,code[:chance]]* return those codes, rather than 200
	// For example, ?codes=500:1,200:1 returns 500 1/2 times and 200 1/2 times
	// For example, ?codes=500:90,200:10 returns 500 90% of times and 200 10% of times
	if err := setResponseFromCodes(r, w); err != nil {
		body.WriteString("codes error: " + err.Error() + "\n")
	}

	h.addResponsePayload(r, &body)

	w.Header().Set("Content-Type", "application/text")
	if _, err := w.Write(body.Bytes()); err != nil {
		log.Println(err.Error())
	}
}

func (h *pilotTestHandler) Echo(ctx context.Context, req *echopb.EchoRequest) (*echopb.EchoResponse, error) {
	body := bytes.Buffer{}
	md, ok := metadata.FromIncomingContext(ctx)
	if ok {
		for key, vals := range md {
			body.WriteString(key + "=" + strings.Join(vals, " ") + "\n")
		}
	}
	body.WriteString("ServiceVersion=" + h.version + "\n")
	body.WriteString("ServicePort=" + strconv.Itoa(h.port) + "\n")
	body.WriteString("Echo=" + req.GetMessage())
	return &echopb.EchoResponse{Message: body.String()}, nil
}

func (h *pilotTestHandler) ForwardEcho(ctx context.Context, in *echopb.ForwardEchoRequest) (*echopb.ForwardEchoResponse, error) {
	return nil, fmt.Errorf("unsupported operation")
}

func (h *pilotTestHandler) WebSocketEcho(w http.ResponseWriter, r *http.Request) {
	body := bytes.Buffer{}
	h.addResponsePayload(r, &body) // create resp payload apriori

	// adapted from https://github.com/gorilla/websocket/blob/master/examples/echo/server.go
	// First send upgrade headers
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("websocket-echo upgrade failed:", err)
		return
	}

	// nolint: errcheck
	defer c.Close()

	// ping
	mt, message, err := c.ReadMessage()
	if err != nil {
		log.Println("websocket-echo read failed:", err)
		return
	}

	// pong
	body.Write(message)
	err = c.WriteMessage(mt, body.Bytes())
	if err != nil {
		log.Println("websocket-echo write failed:", err)
		return
	}
}

// RunHTTP runs the http echo service.
func RunHTTP(port int, version string) {
	fmt.Printf("Listening HTTP1.1 on %v\n", port)
	h := &pilotTestHandler{port: port, version: version}
	if err := http.ListenAndServe(fmt.Sprintf(":%d", port), h); err != nil {
		log.Println(err.Error())
	}
}

// RunGRPC runs the GRPC service, with optional TLS
func RunGRPC(port int, version, crt, key string) {
	fmt.Printf("Listening GRPC on %v\n", port)
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	h := pilotTestHandler{port: port, version: version}

	var grpcServer *grpc.Server
	if crt != "" && key != "" {
		// Create the TLS credentials
		creds, errCreds := credentials.NewServerTLSFromFile(crt, key)
		if errCreds != nil {
			log.Fatalf("could not load TLS keys: %s", errCreds)
		}
		grpcServer = grpc.NewServer(grpc.Creds(creds))
	} else {
		grpcServer = grpc.NewServer()
	}
	echopb.RegisterEchoTestServiceServer(grpcServer, &h)
	if err = grpcServer.Serve(lis); err != nil {
		log.Println(err.Error())
	}
}

func setResponseFromCodes(request *http.Request, response http.ResponseWriter) error {
	responseCodes := request.FormValue("codes")

	codes, err := validateCodes(responseCodes)
	if err != nil {
		return err
	}

	// Choose a random "slice" from a pie
	var totalSlices = 0
	for _, flavor := range codes {
		totalSlices += flavor.slices
	}
	slice := rand.Intn(totalSlices)

	// What flavor is that slice?
	responseCode := codes[len(codes)-1].httpResponseCode // Assume the last slice
	position := 0
	for n, flavor := range codes {
		if position > slice {
			responseCode = codes[n-1].httpResponseCode // No, use an earlier slice
			break
		}
		position += flavor.slices
	}

	response.WriteHeader(responseCode)
	return nil
}

// codes must be comma-separated HTTP response code, colon, positive integer
func validateCodes(codestrings string) ([]codeAndSlices, error) {
	if codestrings == "" {
		// Consider no codes to be "200:1" -- return HTTP 200 100% of the time.
		codestrings = strconv.Itoa(http.StatusOK) + ":1"
	}

	aCodestrings := strings.Split(codestrings, ",")
	codes := make([]codeAndSlices, len(aCodestrings))

	for i, codestring := range aCodestrings {
		codeAndSlice, err := validateCodeAndSlices(codestring)
		if err != nil {
			return []codeAndSlices{{http.StatusBadRequest, 1}}, err
		}
		codes[i] = codeAndSlice
	}

	return codes, nil
}

// code must be HTTP response code
func validateCodeAndSlices(codecount string) (codeAndSlices, error) {
	flavor := strings.Split(codecount, ":")

	// Demand code or code:number
	if len(flavor) == 0 || len(flavor) > 2 {
		return codeAndSlices{http.StatusBadRequest, 9999}, fmt.Errorf("invalid %q (want code or code:count)", codecount)
	}

	n, err := strconv.Atoi(flavor[0])
	if err != nil {
		return codeAndSlices{http.StatusBadRequest, 9999}, err
	}

	if n < http.StatusOK || n >= 600 {
		return codeAndSlices{http.StatusBadRequest, 9999}, fmt.Errorf("invalid HTTP response code %v", n)
	}

	count := 1
	if len(flavor) > 1 {
		count, err = strconv.Atoi(flavor[1])
		if err != nil {
			return codeAndSlices{http.StatusBadRequest, 9999}, err
		}
		if count < 0 {
			return codeAndSlices{http.StatusBadRequest, 9999}, fmt.Errorf("invalid count %v", count)
		}
	}

	return codeAndSlices{n, count}, nil
}

// Client side
type job func(int, io.Writer) error

const (
	hostKey = "Host"
)

// EchoClient controls the client
type EchoClient struct {
	count     int
	timeout   time.Duration
	qps       int
	url       string
	headerKey string
	headerVal string
	msg       string

	caFile   string
	grpcConn *grpc.ClientConn

	httpClient *http.Client
	wsClient   *websocket.Dialer
	grpcClient echopb.EchoTestServiceClient
}

func (ec *EchoClient) makeHTTPRequest(i int, w io.Writer) error {
	req, err := http.NewRequest("GET", ec.url, nil)
	if err != nil {
		return err
	}

	if ec.headerKey == hostKey {
		req.Host = ec.headerVal
	} else if ec.headerKey != "" {
		req.Header.Add(ec.headerKey, ec.headerVal)
	}

	resp, err := ec.httpClient.Do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != 200 && w != nil {
		fmt.Fprintf(w, "[%d] StatusCode=%d\n", i, resp.StatusCode)
	}

	data, err := ioutil.ReadAll(resp.Body)
	_ = resp.Body.Close()

	if err != nil {
		return err
	}

	for _, line := range strings.Split(string(data), "\n") {
		if line != "" {
			if w != nil {
				fmt.Fprintf(w, "[%d body] %s\n", i, line)
			}
		}
	}

	return nil
}

func (ec *EchoClient) makeWebSocketRequest(i int, w io.Writer) error {
	req := make(http.Header)

	if ec.headerKey == hostKey {
		req.Add("Host", ec.headerVal)
	} else if ec.headerKey != "" {
		req.Add(ec.headerKey, ec.headerVal)
	}

	conn, _, err := ec.wsClient.Dial(ec.url, req)
	if err != nil {
		// timeout or bad handshake
		return err
	}
	// nolint: errcheck
	defer conn.Close()

	err = conn.WriteMessage(websocket.TextMessage, []byte(ec.msg))
	if err != nil {
		return err
	}

	_, resp, err := conn.ReadMessage()
	if err != nil {
		return err
	}

	for _, line := range strings.Split(string(resp), "\n") {
		if line != "" {
			if w != nil {
				fmt.Fprintf(w, "[%d body] %s\n", i, line)
			}
		}
	}

	return nil
}

func (ec *EchoClient) makeGRPCRequest(i int, w io.Writer) error {
	req := &echopb.EchoRequest{Message: fmt.Sprintf("request #%d", i)}
	resp, err := ec.grpcClient.Echo(context.Background(), req)
	if err != nil {
		return err
	}

	// when the underlying HTTP2 request returns status 404, GRPC
	// request does not return an error in grpc-go.
	// instead it just returns an empty response
	for _, line := range strings.Split(resp.GetMessage(), "\n") {
		if line != "" {
			if w != nil {
				fmt.Fprintf(w, "[%d body] %s\n", i, line)
			}
		}
	}
	return nil
}

// Initialize the http/ws/grpc client and return the function to call.
func (ec *EchoClient) setupDefaultTest() (job, error) {
	if strings.HasPrefix(ec.url, "http://") || strings.HasPrefix(ec.url, "https://") {
		/* #nosec */
		client := &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: true,
				},
			},
			Timeout: ec.timeout,
		}
		ec.httpClient = client
		return ec.makeHTTPRequest, nil
	} else if strings.HasPrefix(ec.url, "grpc://") || strings.HasPrefix(ec.url, "grpcs://") {
		secure := strings.HasPrefix(ec.url, "grpcs://")
		var address string
		if secure {
			address = ec.url[len("grpcs://"):]
		} else {
			address = ec.url[len("grpc://"):]
		}

		// grpc-go sets incorrect authority header
		authority := address
		if ec.headerKey == hostKey {
			authority = ec.headerVal
		}

		// transport security
		security := grpc.WithInsecure()
		if secure {
			creds, err := credentials.NewClientTLSFromFile(ec.caFile, authority)
			if err != nil {
				return nil, err
			}
			security = grpc.WithTransportCredentials(creds)
		}

		var err error
		ctx, cancel := context.WithTimeout(context.Background(), ec.timeout)
		defer cancel()

		ec.grpcConn, err = grpc.DialContext(ctx, address,
			security,
			grpc.WithAuthority(authority),
			grpc.WithBlock())
		if err != nil {
			return nil, err
		}
		client := echopb.NewEchoTestServiceClient(ec.grpcConn)
		ec.grpcClient = client
		return ec.makeGRPCRequest, nil
	} else if strings.HasPrefix(ec.url, "ws://") || strings.HasPrefix(ec.url, "wss://") {
		/* #nosec */
		client := &websocket.Dialer{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
			HandshakeTimeout: ec.timeout,
		}
		ec.wsClient = client
		return ec.makeWebSocketRequest, nil
	}

	return nil, fmt.Errorf("invalid URL %s", ec.url)
}

func echoClientHandler(w http.ResponseWriter, r *http.Request) {

	_ = r.ParseForm()

	// ca not yet supported

	ec := &EchoClient{
		url:       r.FormValue("url"),
		headerKey: r.FormValue("key"),
		headerVal: r.FormValue("val"),
		msg:       r.FormValue("msg"),
		timeout:   15 * time.Second,
	}

	qpsS := r.FormValue("qps")
	if len(qpsS) > 0 {
		ec.qps, _ = strconv.Atoi(qpsS)
	}
	countS := r.FormValue("count")
	if len(qpsS) > 0 {
		ec.count, _ = strconv.Atoi(countS)
	}

	j, err := ec.setupDefaultTest()
	if j == nil {
		fmt.Fprintf(w, "Error: %v", err)
		w.WriteHeader(501)
		return
	}
	defer func() {
		if ec.grpcConn != nil {
			if err1 := ec.grpcConn.Close(); err1 != nil {
				log.Println(err1)
			}
		}
	}()

	if ec.qps == 0 {
		// one request
		err = j(0, w)
	} else {

		sleepTime := time.Second / time.Duration(ec.qps)
		throttle := time.NewTicker(sleepTime)

		var wg sync.WaitGroup
		var m sync.Mutex

		for i := 0; i < ec.count; i++ {
			<-throttle.C
			wg.Add(1)

			ic := i
			go func() {
				defer wg.Done()
				e := j(ic, w)
				if e != nil {
					m.Lock()
					err = e
					m.Unlock()
				}
			}()
		}
		wg.Wait()
		throttle.Stop()
	}

	if err != nil {
		fmt.Fprintf(w, "Error %s\n", err)
		w.WriteHeader(500)
		return
	}
	w.WriteHeader(200)
}


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

<title>Uses of Class OpenSourceExtensions.UnorderedPair</title>
<meta name="date" content="2014-11-24">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
OpenSourceExtensions.UnorderedPair

Packages that use UnorderedPair

Package
Description

bartMachine

The code for the implementation of the BART algorithm as described in detail in:

OpenSourceExtensions

This is the code for BART that makes use of open source libraries that
 were needed to be modified slightly.

Uses of UnorderedPair in bartMachine

Method parameters in bartMachine with type arguments of type UnorderedPair

Modifier and Type
Method and Description

void
bartMachineTreeNode.findInteractions(java.util.HashSet<UnorderedPair<java.lang.Integer>> set_of_interaction_pairs)

A wrapper to find all interactions recursively by checking all splits underneath this node

Uses of UnorderedPair in OpenSourceExtensions

Methods in OpenSourceExtensions with parameters of type UnorderedPair

Modifier and Type
Method and Description

int
UnorderedPair.compareTo(UnorderedPair<E> o)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package q2

import (
	"errors"

	"github.com/boltdb/bolt"
	"github.com/pzduniak/reql"
)

func (d *Database) branchRoot(tx *bolt.Tx, args []interface{}) (interface{}, error) {
	// Less than 2 -> error
	if len(args) < 2 {
		return nil, errors.New("Branch requires 2 or more arguments")
	}

	// Two parameters are cond, action
	if len(args) == 2 || len(args) == 3 {
		cond, err := d.Execute(tx, args[0].(*reql.Term))
		if err != nil {
			return nil, err
		}

		result, ok := cond.(bool)
		if !ok {
			return nil, errors.New("First parameter of Branch had an invalid type")
		}

		if len(args) == 2 {
			if !result {
				return nil, nil
			}
		} else {
			return d.Execute(tx, args[2].(*reql.Term))
		}

		return d.Execute(tx, args[1].(*reql.Term))
	}

	// Ensure proper arguments count
	if (len(args)-3)%2 != 0 {
		return nil, errors.New("Elif actions in Branch must consist of two arguments")
	}

	for i := 0; i < len(args); i += 2 {
		// Execute the condition
		cond, err := d.Execute(tx, args[i].(*reql.Term))
		if err != nil {
			return nil, err
		}

		// Cast it
		result, ok := cond.(bool)
		if !ok {
			return nil, errors.New("First parameter of Branch had an invalid type")
		}

		// Return the truthy value
		if result {
			return d.Execute(tx, args[i+1].(*reql.Term))
		}
	}

	// Return the false value
	return d.Execute(tx, args[len(args)-1].(*reql.Term))
}

func (d *Database) branch(tx *bolt.Tx, root interface{}, args []interface{}) (interface{}, error) {
	return d.branchRoot(tx, append([]interface{}{root}, args...))
}


text:
package com.alexgilleran.icesoap.parser.impl.stringparsers;

import com.alexgilleran.icesoap.annotation.XMLField;

public class DoubleParser implements StringParser<Double> {

	@Override
	public Double parse(String stringValue, XMLField xmlField) {
		return Double.parseDouble(stringValue);
	}

}


text:
void bessel_tests_01()
{
#ifdef TEST_MPFR
#if MPFR_VERSION < MPFR_VERSION_NUM(3, 0, 0)
   time_proc("Bessel Functions (50 digit precision)", "mpfr_float_50", test_bessel<boost::multiprecision::mpfr_float_50>, 1);
#else
   time_proc("Bessel Functions (50 digit precision)", "mpfr_float_50", test_bessel<boost::multiprecision::mpfr_float_50>, mpfr_buildopt_tls_p() ? 3 : 1);
#endif
#endif
}


text:
package it.polito.tesi.model;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jgrapht.alg.ConnectivityInspector;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultDirectedWeightedGraph;
import org.jgrapht.graph.DefaultWeightedEdge;

import com.javadocmd.simplelatlng.LatLngTool;
import com.javadocmd.simplelatlng.util.LengthUnit;

import it.polito.tesi.FermataNumero;
import it.polito.tesi.LineaNumero;
import it.polito.tesi.bean.Agenzia;
import it.polito.tesi.bean.Corsa;
import it.polito.tesi.bean.Fermata;
import it.polito.tesi.bean.Linea;
import it.polito.tesi.bean.Passaggio;
import it.polito.tesi.bean.Servizio;
import it.polito.tesi.dao.GtfsDao;

public class Model {

	private	Map<String, Agenzia> agenzie ;
	private	Map<String, Linea> linee ;
	private	Map<String, Fermata> fermate ;
	private Map<String, Servizio> servizi ;
	private Map<String, Corsa> corse ;

	private DefaultDirectedWeightedGraph<FermataSuLinea, DefaultWeightedEdge> grafo ;

	private Map<Fermata, Set<FermataSuLinea>> fermateSuLinea ;

	private List<DefaultWeightedEdge> pathEdgeList = null;
	private double pathTempoTotale = 0;

	private List<PassaggioCorsa> passaggiSimulazione ;

	private Simulatore sim ;

	public Model() {
	}

	public void creaModel() {

		// caricamento dati in memoria

		GtfsDao dao = new GtfsDao();
		this.agenzie = dao.getAllAgencies(); // tutte le agenzie
		this.linee = dao.getAllRoutes();
		this.fermate = dao.getAllStops();	  // fermate
		this.servizi = dao.getAllServices();  // mi dice quando passa una linea
		this.corse = dao.getAllTrips(linee, servizi);
		dao.loadPassaggi(corse, fermate);

//		System.out.println("fermate "+fermate.values().size());
//		System.out.println("agenzie "+agenzie.values().size());
//		System.out.println("servizi "+servizi.values().size());
//		System.out.println("linee "+linee.values().size());
//		System.out.println("corse "+corse.values().size());

//		int j = 0 ;
//		for(Corsa c : corse.values()){
//			j+=c.getPassaggi().size();
//		}
//		System.out.println("passaggi "+j);

		this.fermateSuLinea = new HashMap<>();
		for(Fermata f : this.fermate.values())
			fermateSuLinea.put(f, new HashSet<FermataSuLinea>());
	}

	public void creaGrafo(LocalDateTime dataOra, int tempoSimulazione, boolean connesso){

		grafo = new DefaultDirectedWeightedGraph<FermataSuLinea,DefaultWeightedEdge>(DefaultWeightedEdge.class);
		passaggiSimulazione = new ArrayList<>();

		for (Corsa c : this.corse.values()){
//			System.out.println(c.getServizio());

			int dayOfWeek = dataOra.getDayOfWeek().getValue()-1;
			if(c.getServizio().getSettimana()[dayOfWeek]==1){ // aggiungo l'arco solo se nel giorno indicato

					LocalTime lt1 = dataOra.toLocalTime() ;

					List<Passaggio> passaggi = c.getPassaggi() ;
					// aggiunta dei vertici
					for(Passaggio p : passaggi){
//						System.out.println(p.getOraPartenza().toSecondOfDay() + " / " + lt1.toSecondOfDay() + " / " +
//								(p.getOraPartenza().toSecondOfDay()-lt1.toSecondOfDay())+ " / " + (tempoSimulazione*3600) ) ;
						int delta = p.getOraArrivo().toSecondOfDay()-lt1.toSecondOfDay() ;

						if(delta>=0 && delta <= (3600*tempoSimulazione)) passaggiSimulazione.add(new PassaggioCorsa(p,c)) ;

							FermataSuLinea fsl = new FermataSuLinea(p.getFermata(), c.getLinea()) ;
							this.fermateSuLinea.get(p.getFermata()).add(fsl);
							if(!grafo.containsVertex(fsl)){
								grafo.addVertex(fsl);
			//					System.out.println(fsl.toString());
							}

					}

					// aggiunta dei nodi
					for(int i = 0 ; i < passaggi.size()-1 ; i++){
						int delta = passaggi.get(i).getOraArrivo().toSecondOfDay()-lt1.toSecondOfDay() ;
						if ( delta <= tempoSimulazione*3600 && delta >= 0)
						{
							FermataSuLinea fslP = new FermataSuLinea(passaggi.get(i).getFermata(), c.getLinea()) ;
							FermataSuLinea fslA = new FermataSuLinea(passaggi.get(i+1).getFermata(), c.getLinea()) ;

							if (fslP != null && fslA != null && !fslP.equals(fslA)) {

								double velocita = 30;
								double distanza = LatLngTool.distance(fslP.getPosition(), fslA.getPosition(), LengthUnit.KILOMETER);
								double tempo = (distanza / velocita) * 60 * 60;
//								System.out.println(fslP + " / " + fslA);
								// Aggiungo un arco pesato tra le due fermate
								DefaultWeightedEdge link = grafo.addEdge(fslP, fslA);
								if (link != null) {
									grafo.setEdgeWeight(link, tempo);
								}
							}
						}
					}

			}//end if day
		}
//		System.out.println("Grafo creato: " + grafo.vertexSet().size() + " nodi, " + grafo.edgeSet().size() + " archi");

		// aggiungo i collegamenti da una parte all'altra della stazione
		for (Set<FermataSuLinea> fsl : fermateSuLinea.values()){

			for(FermataSuLinea fslA : fsl){
				for(FermataSuLinea fslB : fsl){

					if (fslA != null && fslB != null && !fslA.equals(fslB)) {

						DefaultWeightedEdge link = grafo.addEdge(fslA, fslB);
						if (link != null) {
							grafo.setEdgeWeight(link, 60 * 5 ); // 5 minuti per andare da una banchina all'altra
//							System.out.println(link.toString());
						}
					}
				}
			}
		}

		// aggiungo le fermate raggiungibili a piedi oppure per far diventare il grafo connesso ...

		ConnectivityInspector<FermataSuLinea,DefaultWeightedEdge> ci = new ConnectivityInspector<FermataSuLinea,DefaultWeightedEdge>(grafo);

		double dMax=0 ;
		if(connesso)
			dMax = 3; // per evitare loop infiniti
		else
			dMax = 1.7 ; // mezz'ora a piedi

		double dist = 1.6 ;

		while(!ci.isGraphConnected() && dist<dMax){
				for(FermataSuLinea i : grafo.vertexSet()){
					for(FermataSuLinea j : grafo.vertexSet()){

						if(i!=null && j!=null && !i.equals(j) && !grafo.containsEdge(i, j)){

								double velocita = 5 ; // velocità a piedi
								double distanza = LatLngTool.distance(i.getPosition(), j.getPosition(), LengthUnit.KILOMETER);
								double tempo = (distanza / velocita) * 60 * 60;

								if(distanza<dist){ // a tentativi in base al db
									DefaultWeightedEdge link = grafo.addEdge(i, j);
									if (link != null) {
										grafo.setEdgeWeight(link, tempo);
									}
								}
						}

					}
				}
			dist+=0.1;
//			System.out.println(ci.isGraphConnected());
		}

		System.out.println("Grafo creato: " + grafo.vertexSet().size() + " nodi, " + grafo.edgeSet().size() + " archi");
//

	}

	public void calcolaPercorso(Fermata partenza, Fermata arrivo){

		DijkstraShortestPath<FermataSuLinea, DefaultWeightedEdge> dijkstra;

		// Usati per salvare i valori temporanei
		double pathTempoTotaleTemp;

		// Usati per salvare i valori migliori
		List<DefaultWeightedEdge> bestPathEdgeList = null;
		double bestPathTempoTotale = Double.MAX_VALUE;

		for (FermataSuLinea fslP : fermateSuLinea.get(partenza)) {
			for (FermataSuLinea fslA : fermateSuLinea.get(arrivo)) {

				dijkstra = new DijkstraShortestPath<FermataSuLinea, DefaultWeightedEdge>(grafo, fslP, fslA);

//				System.out.println(fslA.equals(fslP));
//				double distanza = LatLngTool.distance(fslA.getPosition(), fslP.getPosition(), LengthUnit.KILOMETER);
//				System.out.println(distanza);

				pathTempoTotaleTemp = dijkstra.getPathLength();

				if (pathTempoTotaleTemp < bestPathTempoTotale) {
					bestPathTempoTotale = pathTempoTotaleTemp;
					bestPathEdgeList = dijkstra.getPathEdgeList();
				}
			}
		}

		pathEdgeList = bestPathEdgeList;
		pathTempoTotale = bestPathTempoTotale;

	}

	public String getPercorsoEdgeList() {
		StringBuilder risultato = new StringBuilder();

		if (pathEdgeList == null || pathEdgeList.size()==0)
			risultato.append("Non è stato creato un percorso.\n\n");
		else{

			risultato.append("Percorso del flusso:\n\n");

			Linea lineaTemp = grafo.getEdgeSource(pathEdgeList.get(0)).getLinea();
			risultato.append("Da "+ grafo.getEdgeSource(pathEdgeList.get(0)).getName() +" Prendo Linea: " + lineaTemp.getShortName() + "\n[");

			for (DefaultWeightedEdge edge : pathEdgeList) {

				if (!grafo.getEdgeTarget(edge).getLinea().equals(lineaTemp)) {
					risultato.setLength(risultato.length() - 2);
					risultato.append("]\nVado a piedi alla Fermata:"+
							grafo.getEdgeTarget(edge).getName()+
							"\nCambio su Linea: " + grafo.getEdgeTarget(edge).getLinea() + "\n[");

					lineaTemp = grafo.getEdgeTarget(edge).getLinea();

				} else {
					risultato.append(grafo.getEdgeTarget(edge).getName());
					risultato.append(", ");
				}
			}
			risultato.setLength(risultato.length() - 2);
			risultato.append("]\n\n");
		}
			return risultato.toString();
	}

	public Map<String, Fermata> getFermate() {
		if(this.fermate==null){
			GtfsDao dao = new GtfsDao();
			this.fermate=dao.getAllStops();
			}
		return fermate;
	}

	public double getPercorsoTempoTotale() {

		if (pathEdgeList == null || pathEdgeList.size()==0)
			return -1 ;

		return pathTempoTotale;
	}

	public Map<String, Linea> getLinee() {
		if(this.linee==null){
			GtfsDao dao = new GtfsDao();
			this.linee=dao.getAllRoutes();
			}
		return this.linee;
	}

	public Map<String, Agenzia> getAgenzie() {
		if(this.agenzie==null){
			GtfsDao dao = new GtfsDao();
			this.agenzie=dao.getAllAgencies();
			}
		return this.agenzie;
	}

	public void Simula(int capienza, int nPersFermata, int intervallo, double probLinea, double probFlusso, double probCambio, double coefficiente){

			sim = new Simulatore(grafo, linee, passaggiSimulazione, fermateSuLinea, pathEdgeList,
					capienza, nPersFermata, intervallo, probLinea, probFlusso, probCambio, coefficiente) ;
			sim.run();
//			System.out.println("sod " + sim.getClientiSoddisfatti()) ;
//			System.out.println("parz " + sim.getClientiParzialmenteSoddisfatti()) ;
//			System.out.println("in " + sim.getClientiInsoddisfatti() ) ;
	}

	public int getClientiSoddisfati() {
		return this.sim.getClientiSoddisfatti() ;
	}

	public int getClientiParzSoddisfati() {
		return this.sim.getClientiParzialmenteSoddisfatti() ;
	}

	public int getClientiInoddisfati() {
		return this.sim.getClientiInsoddisfatti() ;
	}

	public List<FermataNumero> getSoddFermata() {
		List<FermataNumero> fn = new ArrayList<>() ;
		Map<Fermata, Integer> k = this.sim.getSoddFermata() ;

		for (Map.Entry<Fermata, Integer> entry : k.entrySet()){
			if( entry.getValue() > 0 ){
				fn.add(new FermataNumero(entry.getKey(), entry.getValue()));
			}
		}
		Collections.sort(fn);
		return fn ;
	}

	public List<LineaNumero> getSoddLinea() {

		List<LineaNumero> ln = new ArrayList<>() ;
		Map<Linea, Integer> k = this.sim.getSoddLinea() ;

		for (Map.Entry<Linea, Integer> entry : k.entrySet()){
			if( entry.getValue() > 0 ){
				ln.add(new LineaNumero(entry.getKey(), entry.getValue()));
			}
		}
		Collections.sort(ln);
		return ln ;

	}

}


text:
/*
 * cxa_config.h
 *
 * Created: 5/25/2015 8:55:08 PM
 *  Author: Christopher Armenio
 */

#ifndef CXA_CONFIG_H_
#define CXA_CONFIG_H_

#define CXA_ASSERT_EXIT_FUNC(eStat)					while(1);
#define CXA_ASSERT_LINE_NUM_ENABLE
#define CXA_ASSERT_MSG_ENABLE

#define CXA_CONSOLE_ENABLE
#define CXA_CONSOLE_MAXNUM_COMMANDS					16

#define CXA_FILE_DISABLE

#define CXA_IOSTREAM_FORMATTED_BUFFERLEN_BYTES		80

#define CXA_LINE_ENDING								"\r\n"

#define CXA_LOGGER_TIME_ENABLE

#define CXA_MQTT_CLIENT_MAXNUM_LISTENERS				4
#define	CXA_MQTT_MESSAGEFACTORY_MESSAGE_SIZE_BYTES	256

#define CXA_NETWORK_WIFIMGR_MAXNUM_LISTENERS			3

#define CXA_RUNLOOP_MAXNUM_ENTRIES 					30
#define CXA_RUNLOOP_INFOPRINT_PERIOD_MS				0

//#define CXA_STATE_MACHINE_ENABLE_LOGGING
#define CXA_STATE_MACHINE_ENABLE_TIMED_STATES
#define CXA_STATE_MACHINE_MAXNUM_STATES				12

#endif /* CXA_CONFIG_H_ */