text:
const express = require('express')
const cors = require('cors')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const kv = require('beepboop-persist')()
const slack = require('slack')

const port = process.env.PORT || 3100
const token = process.env.SLACK_TOKEN

const ohsTeam = {
  U1CTUKMT9: {}, // Zoé
  // U40MZ9EL9: {}, // Tugba
  U0BU8V7N0: {}, // Trev
  // U2NC0H2BS: {}, // Temi
  U0BUEB5BK: {}, // Paolo
  U0BU8SV4K: {}, // Michele
  // U1KU01R4K: {}, // Kristina
  U162CB0LC: {}, // James
  U0C160N8N: {}, // Christean
  U0BUPA30R: {}, // Chris
  U1CU5P4H0: {}, // Anna
}

const orbitTeam = {
  U2L4F0AF3: {}, // James
}

let team = ohsTeam

const slapp = Slapp({
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

// fetch users and store as team members

const loadTeamCache = () => new Promise((resolve) => {
  kv.get('team', (err, storedTeam) => {
    console.log('loadTeamCache done', storedTeam)

    if (err) throw err
    team = storedTeam
    resolve(storedTeam)
  })
})

const saveTeamCache = (team = team) => new Promise((resolve) => {
  kv.set('team', team, (err) => {
    console.log('set team')
    console.log(err)
    if (err) throw err
    resolve(team)
  })
})

const updateTeamCache = (members) => new Promise((resolve) => {
  members.forEach((member) => {
    if (!team[member.id]) return
    team[member.id] = Object.assign({}, team[member.id], member)
  })
  resolve(team)
})

const fetchTeam = () => new Promise((resolve) => {
  console.log('fetchTeam')

  slack.users.list({ token }, (err, data) => {
    if (err) throw err

    const { members } = data
    console.log(`Fetched ${members.length} users from Slack`)

    resolve(members)
  })
})

// commands

slapp.command('/location', '(.*)', (msg, text, location) => {
  if (!team[msg.body.user_id])
    return msg.respond(`You are not added as a team member`)

  team[msg.body.user_id].location = location

  msg.respond(`Your location has been set as _${location}_`)
})

// public api

const app = slapp.attachToExpress(express())

app.use(cors())

app.get('/', (req, res) => {
  res.send('Hello world.')
})

app.get('/team', (req, res) => {
  fetchTeam()
    .then(updateTeamCache)
    .then(saveTeamCache)
    .then((team) => res.send({ team }))
    .catch((message) => res.send({ message, team }))
})

app.get('/reset', (req, res) => {
  team = ohsTeam

  saveTeamCache(team)
    .then(() => res.send())
})

// load data and start server
loadTeamCache()
  .then(() => {
    app.listen(port, (err) => {
      if (err) return console.error(err)
      console.log(`Listening on port ${port}`)
    })
  })

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.Devices.Client.Exceptions
{
    using System;
    using System.Runtime.Serialization;
    using Microsoft.Azure.Devices.Client.Extensions;

#if !WINDOWS_UWP
    [Serializable]
#endif
#if !WINDOWS_UWP // Exporting custom exception types is not allowed in WinRT
    public
#endif
    class IotHubNotFoundException : IotHubException
    {
        public IotHubNotFoundException(string iotHubName)
            : base("IoT hub not found: {0}".FormatInvariant(iotHubName))
        {
        }

        public IotHubNotFoundException(string iotHubName, string trackingId)
            : base("IoT hub not found: {0}".FormatInvariant(iotHubName), trackingId)
        {
        }

#if !WINDOWS_UWP
        IotHubNotFoundException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }
}


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

namespace Glav.CognitiveServices.FluentApi.Luis.Domain
{
    public enum LuisAppSlot
    {
        Staging,
        Production
    }
}


text:
package main

import (
	"net/http"
)

func SetupErrorMessages() {
	ErrorMessages = map[int]string{
		http.StatusNotFound:            "That page doesn't exist",
		http.StatusUnauthorized:        "You're not Dave! You need to Login!",
		http.StatusInternalServerError: "Something is going horribly wrong!",
		http.StatusBadRequest:          "You can't do that!",
	}
}

func httpError(code int, w http.ResponseWriter, req *http.Request, ctx *Context, pjax bool) error {
	w.WriteHeader(code)
	message := ""
	if _, ok := ErrorMessages[code]; ok {
		message = ErrorMessages[code]
	}
	return T("error.html", pjax).Execute(w, map[string]interface{}{
		"ctx":     ctx,
		"code":    code,
		"message": message,
	})
}

func notFound(w http.ResponseWriter, req *http.Request, ctx *Context, pjax bool) error {
	return httpError(http.StatusNotFound, w, req, ctx, pjax)
}

func notAuthed(w http.ResponseWriter, req *http.Request, ctx *Context, pjax bool) error {
	return httpError(http.StatusUnauthorized, w, req, ctx, pjax)
}

func InternalError(w http.ResponseWriter, req *http.Request, ctx *Context, pjax bool) error {
	return httpError(http.StatusInternalServerError, w, req, ctx, pjax)
}

func badRequest(w http.ResponseWriter, req *http.Request, ctx *Context, pjax bool) error {
	return httpError(http.StatusBadRequest, w, req, ctx, pjax)
}


text:
<config>
    <tabs>
        <coefficient_extension module="coefficient">
            Tandem
            <sort_order>99999</sort_order>
        </coefficient_extension>
    </tabs>
    <sections>
        <coefficient translate="label" module="coefficient">
            Tandem Extension
            <tab>coefficient_extension</tab>
            <frontend_type>text</frontend_type>
            <sort_order>1000</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>
            <groups>
                <api translate="label">
                    <expanded>1</expanded>
                    API Configuration
                    <comment>This extension provides an API that Tandem uses to synchronize your customers, products, and sales.</comment>
                    <frontend_type>text</frontend_type>
                    <sort_order>1</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <enabled translate="label">
                            API Enabled
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>2</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </enabled>
                        <apikey translate="label">
                            API Key
                            <frontend_type>text</frontend_type>

                            <comment>This is used to identify requests from Tandem.</comment>
                            <backend_model>coefficient/adminhtml_apikey</backend_model>
                            <sort_order>3</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <depends><enabled>1</enabled></depends>
                        </apikey>
                        <secret translate="label">
                            Secret
                            <frontend_type>text</frontend_type>

                            <comment>This is used to authenticate requests from Tandem.
                                Treat this like a password and never share it with anyone.</comment>
                            <backend_model>coefficient/adminhtml_secret</backend_model>
                            <sort_order>4</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <depends><enabled>1</enabled></depends>
                        </secret>

                        <generate_button translate="button_label">
                            <button_label>Generate A New Secret</button_label>
                            <frontend_model>coefficient/adminhtml_generatebutton</frontend_model>
                            <sort_order>5</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <depends><enabled>1</enabled></depends>
                        </generate_button>
                    </fields>
                </api>
            </groups>

        </coefficient>
    </sections>
</config>


text:
#include <string>

#include "modsecurity/actions/action.h"
#include "src/actions/transformations/transformation.h"

#ifndef SRC_ACTIONS_TRANSFORMATIONS_URL_ENCODE_H_
#define SRC_ACTIONS_TRANSFORMATIONS_URL_ENCODE_H_

#ifdef __cplusplus
namespace modsecurity {
class Transaction;

namespace actions {
namespace transformations {

class UrlEncode : public Transformation {
 public:

    explicit UrlEncode(const std::string &action) ;

    std::string evaluate(const std::string &exp,
        Transaction *transaction) override;

    std::string url_enc(const char *input,
        unsigned int input_len, int *changed);
};

}  // namespace transformations
}  // namespace actions
}  // namespace modsecurity

#endif

#endif  // SRC_ACTIONS_TRANSFORMATIONS_URL_ENCODE_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phaeopeltis cyperi Bat.

### Remarks
null


text:
var mongoose =  require('mongoose');
var TeamModel = require('../model/team');
var request = require('request');
var db = require('../db')();
console.log('AFTER DB COnnection');

function processData(data){
	var len = data.length;
	data.forEach(function(team, index){

		var newTeam = new TeamModel();
		newTeam.address=team.address;
		newTeam.draws= team.draws;
		newTeam.foundedYear= team.foundedYear;
		newTeam.goalsAgainst= team.goalsAgainst;
		newTeam.goalsDiff= team.goalsDiff;
		newTeam.goalsFor= team.goalsFor;
		newTeam.group= team.group;
		newTeam.groupPoints= team.groupPoints;
		newTeam.groupRank= team.groupRank;
		newTeam.homeStadium= team.homeStadium;
		newTeam.id= team.id;
		newTeam.logo= team.logo;
		newTeam.losses= team.losses;
		newTeam.matchesPlayed= team.matchesPlayed;
		newTeam.name= team.name;
		newTeam.stadiumCapacity= team.stadiumCapacity;
		newTeam.type= team.type;
		newTeam.website= team.website;
		newTeam.wins= team.wins;

		newTeam.save(function(err){
			if (err) throw err;
			console.log('New Team: ' + newTeam.name + ' created');
			if(len- 1 === index){
				 process && process.exit();
			}
		});

	});
}

request("http://worldcup.kimonolabs.com/api/teams?apikey=ad2ff693e51d4cc636bdd59c3daf4e2a", function(err, response, body) {
  processData(JSON.parse(body));
});


text:
"""
Module with interface for picking authors from authority base in NK's Aleph.
"""
#
# Imports =====================================================================
import json
from os.path import join

from browser import html
from browser import alert
from browser import document

from .shared import make_request
from .shared import func_on_enter

from .log_view2 import LogView
from .progressbar import AuthorBar
from .author_switcher import SWITCHER_EL
from .overlay_controller import BlackOverlay

# virtual filesystem / modules provided by REST API
from virtual_fs import settings

# Functions & classes =========================================================
class AuthorPicker(object):
    """
    This component is responsible for generating the interface for picking
    authors from Aleph.
    """
    original_author_el = document["author"]

    div_el = document["author_picker"]  # whole <div>
    input_el = document["author_input"]  # <input> for author's name
    search_btn_el = document["search_author"]  # trigger the search of author
    select_el = document["author_select"]  # <select> element with authors
    storno_btn_el = document["storno_author"]  # used to storno the picking
    pick_btn_el = document["pick_author"]  # used to accept the selected author

    overlay = BlackOverlay()

    code_to_data = {}  # this is used to translate select back to data
    selected_code = None

    @classmethod
    def show(cls):
        """
        Show the author picker.
        """
        cls.div_el.style.display = "block"
        cls.hide_errors()

        cls.overlay.show()
        cls.overlay.el.bind("click", lambda x: cls.hide())

    @classmethod
    def hide(cls):
        """
        Hide the author picker.
        """
        cls.overlay.hide()
        cls.div_el.style.display = "none"

    @classmethod
    def hide_errors(cls):
        """
        Hide errors shown by validators.
        """
        cls.select_el.style.border = "0"
        cls.input_el.style.border = "0"

    @classmethod
    def _pick_selected_option(cls):
        """
        Select handler for authors.
        """
        for option in cls.select_el:
            # if the select is empty
            if not hasattr(option, "selected"):
                return None

            if option.selected:
                return option.value

        return None

    @classmethod
    def on_pick_button_pressed(cls, ev):
        """
        Callback called when the user press the button for accepting the picked
        author.

        This element calls validations, before accepting the choice.
        """
        cls.hide_errors()

        selected_code = cls._pick_selected_option()
        if not selected_code:
            cls.select_el.style.border = "2px solid red"
            return

        cls.selected_code = selected_code
        cls.code = str(selected_code)
        cls.original_author_el.value = cls.code_to_data[selected_code].get(
            "alt_name",
            str(cls.code_to_data[selected_code])
        )
        cls.hide()

    @classmethod
    def set_select(cls, authors):
        """
        Put data into ``<select>`` element.

        Args:
            authors (dict): Dictionary with author informations returned from
                aleph REST API. Format:
                ``{"name": .., "code": .., "linked_forms": ["..",]}``.
        """
        cls.select_el.html = ""

        if not authors:
            cls.select_el.disabled = True
            cls.select_el <= html.OPTION("Nic nenalezeno!")
            return

        cls.select_el.disabled = False
        for author_dict in authors:
            name = author_dict.get("name")
            code = author_dict.get("code")
            alt_name = author_dict.get("alt_name", name)

            if not (name and code):
                continue

            cls.code_to_data[code] = author_dict
            cls.select_el <= html.OPTION(alt_name, value=code)

    @classmethod
    def bind(cls):
        """
        Bind the callbacks to the buttons.
        """
        document["show_author_picker"].bind("click", lambda x: cls.show())

        cls.storno_btn_el.bind("click", lambda x: cls.hide())
        cls.pick_btn_el.bind("click", cls.on_pick_button_pressed)

    @classmethod
    def __get__(cls, obj, objtype):
        if not SWITCHER_EL.checked:
            return None

        return cls.code_to_data[cls.selected_code]

    @classmethod
    def __set__(cls, obj, value):
        # called by reset()
        if not value:
            cls.selected_code = None
            cls.original_author_el.value = ""
            return

        if type(value) in [list, tuple]:
            value = value[0]

        code = value["code"]
        cls.code_to_data[code] = value
        cls.selected_code = code

        cls.original_author_el.value = cls.code_to_data[code].get(
            "alt_name",
            str(cls.code_to_data[code])
        )

    @classmethod
    def validate(cls):
        """
        Validate required elements.
        """
        if not SWITCHER_EL.checked:
            return True

        if not cls.selected_code:
            cls.original_author_el.style.border = "2px solid red"
            return False

        cls.original_author_el.style.border = "0"
        return True

class AuthorPickerAdapter(AuthorPicker):
    """
    Adapter of the :class:`AuthorPicker` to aleph REST API.

    This adapter is mapped to the key / button press. It then launches querying
    of the REST API in periodic interval, updating the progress bar and so on.
    """
    @classmethod
    def on_complete(cls, req):
        """
        Callback called when the request was received.
        """
        # handle http errors
        if not (req.status == 200 or req.status == 0):
            alert("Couldn't connect to authority base.")
            LogView.add(
                "Error when calling Aleph authority base: %s" % req.text
            )
            AuthorBar.hide()
            return

        AuthorBar.hide()
        cls.set_select(json.loads(req.text))

    @classmethod
    def start(cls, ev):
        """
        Event handler which starts the request to REST API.
        """
        # somehow the first call doesn't stop the propagation
        ev.stopPropagation()
        ev.preventDefault()

        # make sure, that `author` was filled
        author = cls.input_el.value.strip()
        if not author:
            cls.input_el.style.border = "2px solid red"
            return

        cls.hide_errors()

        AuthorBar.show(50)
        make_request(
            url=join(settings.API_PATH, "aleph/authors_by_name"),
            data={"name": author},
            on_complete=cls.on_complete
        )

    @classmethod
    def bind(cls):
        """
        Bind the buttons to adapter's event handler.
        """
        super(cls, cls).bind()

        cls.search_btn_el.bind("click", cls.start)
        cls.input_el.bind("keypress", func_on_enter(cls.start))

AuthorPickerAdapter.bind()


text:
module SingaporeCPFCalculator
  module Year2014
    module SPR2GG

      # Payment calculator for Singapore's Central Provident Fund for employee's age 50 and below.
      class Age50BelowContributionCalculator < Year2014::Base

        extend Requirements::Group50YearsAndBelow

        private

        def tc_rate_1
          "0.09"
        end

        def tc_rate_2
          "0.24"
        end

        def adjustment_rate
          "0.45"
        end

        def ec_rate
          "0.15"
        end

      end

    end
  end
end


text:
from alphatwirl.selection.modules import All
import unittest

##__________________________________________________________________||
class MockEvent(object): pass

##__________________________________________________________________||
class MockEventSelection(object):
    def __init__(self):
        self.isBeginCalled = False
        self.isEndCalled = False
        self.ret = True

    def begin(self, event):
        self.isBeginCalled = True

    def __call__(self, event):
        return self.ret

    def end(self):
        self.isEndCalled = True

##__________________________________________________________________||
class Test_All(unittest.TestCase):

    def test_empty(self):
        obj = All()

        event = MockEvent()
        self.assertTrue(obj(event))

    def test_standard(self):
        obj = All()
        selection1 = MockEventSelection()
        selection2 = MockEventSelection()

        obj.add(selection1)
        obj.add(selection2)

        self.assertFalse(selection1.isBeginCalled)
        self.assertFalse(selection2.isBeginCalled)

        self.assertFalse(selection1.isEndCalled)
        self.assertFalse(selection2.isEndCalled)

        event = MockEvent()
        obj.begin(event)
        self.assertTrue(selection1.isBeginCalled)
        self.assertTrue(selection2.isBeginCalled)

        event = MockEvent()
        selection1.ret = True
        selection2.ret = True
        self.assertTrue(obj(event))

        event = MockEvent()
        selection1.ret = True
        selection2.ret = False
        self.assertFalse(obj(event))

        event = MockEvent()
        selection1.ret = False
        selection2.ret = True
        self.assertFalse(obj.event(event))

        event = MockEvent()
        selection1.ret = False
        selection2.ret = False
        self.assertFalse(obj.event(event))

        obj.end()
        self.assertTrue(selection1.isEndCalled)
        self.assertTrue(selection2.isEndCalled)

##__________________________________________________________________||


text:
package jp.gr.java_conf.onkohdondo.kareoke.util;

import java.util.ArrayList;

import processing.core.PApplet;

public class Node {
	private double start;
	private double length;
	private String str;
	private String ruby;
	private Music parent;
	private ArrayList<Double> timing;

	public Node(double arg0, double arg1, String arg2,Music arg3){
		start=arg0;
		length=arg1;
		str=arg2;
		parent=arg3;
		ruby="";
		timing=new ArrayList<Double>();
		timing.add(start);
	}

	public double getStart(){
		return start;
	}

	public double getLength(){
		return length;
	}

	public double getEnd(){
		return start+length;
	}

	public String getMain(){
		return str;
	}

	public void setLength(double arg0){
		length=arg0;
	}

	public void setStr(String arg0){
		str=arg0;
	}

	public String toString(){
//		return (int)(start/(60000.0/186*4)*16)/16.0+"->"+
//				(int)(length/(60000.0/186*4)*16)/16.0+" "+str+
//				(isRuby()?"<"+ruby+">":"")+timing;
		return start+"->"+
			length+" "+str+
			(isRuby()?"<"+ruby+">":"")+timing;
	}

	public String getRuby() {
		return ruby;
	}

	public void setRuby(String ruby) {
		this.ruby = ruby;
	}

	public boolean isRuby(){
		return !ruby.equals("");
	}

	public double getWidth(PApplet p2){
		double ret0=getMainWidth(p2),ret1=getRubyWidth(p2);
		return ret0>ret1?ret0:ret1;
	}

	public double getMainInset(PApplet p2) {
		double ret0=getMainWidth(p2),ret1=getRubyWidth(p2);
		if(ret0<ret1) return (ret1-ret0)/2;
		return 0;
	}

	public double getRubyInset(PApplet p2){
		double ret0=getMainWidth(p2),ret1=getRubyWidth(p2);
		if(ret0>ret1)
			return (ret0-ret1)/2;
		return 0;
	}

	public double getMainWidth(PApplet p2){
		p2.textFont(parent.kareokeFontB,parent.kareokeSizeB);
		return p2.textWidth(str);
	}

	public double getRubyWidth(PApplet p2){
		p2.textFont(parent.kareokeFontB,parent.kareokeSizeS);
		return p2.textWidth(ruby);
	}

	public ArrayList<Double> getTiming(){
		return timing;
	}

	public double getTiming(int arg0){
		if(arg0==timing.size()){
			return getEnd();
		}
		return timing.get(arg0);
	}

	public void addTiming(double arg0){
		timing.add(arg0);
	}

}


text:
using ::testing::AssertionSuccess;

namespace http2 {
namespace test {
namespace {

class HpackBlockDecoderTest : public RandomDecoderTest {
 protected:
  HpackBlockDecoderTest() : listener_(&collector_), decoder_(&listener_) {
    stop_decode_on_done_ = false;
    decoder_.Reset();
    // Make sure logging doesn't crash. Not examining the result.
    std::ostringstream strm;
    strm << decoder_;
  }

  DecodeStatus StartDecoding(DecodeBuffer* db) override {
    collector_.Clear();
    decoder_.Reset();
    return ResumeDecoding(db);
  }

  DecodeStatus ResumeDecoding(DecodeBuffer* db) override {
    DecodeStatus status = decoder_.Decode(db);

    // Make sure logging doesn't crash. Not examining the result.
    std::ostringstream strm;
    strm << decoder_;

    return status;
  }

  AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* db,
                                               const Validator& validator) {
    bool return_non_zero_on_first = false;
    return RandomDecoderTest::DecodeAndValidateSeveralWays(
        db, return_non_zero_on_first, validator);
  }

  AssertionResult DecodeAndValidateSeveralWays(const HpackBlockBuilder& hbb,
                                               const Validator& validator) {
    DecodeBuffer db(hbb.buffer());
    return DecodeAndValidateSeveralWays(&db, validator);
  }

  AssertionResult DecodeHpackExampleAndValidateSeveralWays(
      quiche::QuicheStringPiece hpack_example,
      Validator validator) {
    std::string input = HpackExampleToStringOrDie(hpack_example);
    DecodeBuffer db(input);
    return DecodeAndValidateSeveralWays(&db, validator);
  }

  uint8_t Rand8() { return Random().Rand8(); }

  std::string Rand8String() { return Random().RandString(Rand8()); }

  HpackBlockCollector collector_;
  HpackEntryDecoderVLoggingListener listener_;
  HpackBlockDecoder decoder_;
};

// http://httpwg.org/specs/rfc7541.html#rfc.section.C.2.1
TEST_F(HpackBlockDecoderTest, SpecExample_C_2_1) {
  auto do_check = [this]() {
    VERIFY_AND_RETURN_SUCCESS(collector_.ValidateSoleLiteralNameValueHeader(
        HpackEntryType::kIndexedLiteralHeader, false, "custom-key", false,
        "custom-header"));
  };
  const char hpack_example[] = R"(
      40                                      | == Literal indexed ==
      0a                                      |   Literal name (len = 10)
      6375 7374 6f6d 2d6b 6579                | custom-key
      0d                                      |   Literal value (len = 13)
      6375 7374 6f6d 2d68 6561 6465 72        | custom-header
                                              | -> custom-key:
                                              |   custom-header
      )";
  EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
      hpack_example, ValidateDoneAndEmpty(do_check)));
  EXPECT_TRUE(do_check());
}

// http://httpwg.org/specs/rfc7541.html#rfc.section.C.2.2
TEST_F(HpackBlockDecoderTest, SpecExample_C_2_2) {
  auto do_check = [this]() {
    VERIFY_AND_RETURN_SUCCESS(collector_.ValidateSoleLiteralValueHeader(
        HpackEntryType::kUnindexedLiteralHeader, 4, false, "/sample/path"));
  };
  const char hpack_example[] = R"(
      04                                      | == Literal not indexed ==
                                              |   Indexed name (idx = 4)
                                              |     :path
      0c                                      |   Literal value (len = 12)
      2f73 616d 706c 652f 7061 7468           | /sample/path
                                              | -> :path: /sample/path
      )";
  EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
      hpack_example, ValidateDoneAndEmpty(do_check)));
  EXPECT_TRUE(do_check());
}

// http://httpwg.org/specs/rfc7541.html#rfc.section.C.2.3
TEST_F(HpackBlockDecoderTest, SpecExample_C_2_3) {
  auto do_check = [this]() {
    VERIFY_AND_RETURN_SUCCESS(collector_.ValidateSoleLiteralNameValueHeader(
        HpackEntryType::kNeverIndexedLiteralHeader, false, "password", false,
        "secret"));
  };
  const char hpack_example[] = R"(
      10                                      | == Literal never indexed ==
      08                                      |   Literal name (len = 8)
      7061 7373 776f 7264                     | password
      06                                      |   Literal value (len = 6)
      7365 6372 6574                          | secret
                                              | -> password: secret
      )";
  EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
      hpack_example, ValidateDoneAndEmpty(do_check)));
  EXPECT_TRUE(do_check());
}

// http://httpwg.org/specs/rfc7541.html#rfc.section.C.2.4
TEST_F(HpackBlockDecoderTest, SpecExample_C_2_4) {
  auto do_check = [this]() {
    VERIFY_AND_RETURN_SUCCESS(collector_.ValidateSoleIndexedHeader(2));
  };
  const char hpack_example[] = R"(
      82                                      | == Indexed - Add ==
                                              |   idx = 2
                                              | -> :method: GET
      )";
  EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
      hpack_example, ValidateDoneAndEmpty(do_check)));
  EXPECT_TRUE(do_check());
}
// http://httpwg.org/specs/rfc7541.html#rfc.section.C.3.1
TEST_F(HpackBlockDecoderTest, SpecExample_C_3_1) {
  std::string example = R"(
      82                                      | == Indexed - Add ==
                                              |   idx = 2
                                              | -> :method: GET
      86                                      | == Indexed - Add ==
                                              |   idx = 6
                                              | -> :scheme: http
      84                                      | == Indexed - Add ==
                                              |   idx = 4
                                              | -> :path: /
      41                                      | == Literal indexed ==
                                              |   Indexed name (idx = 1)
                                              |     :authority
      0f                                      |   Literal value (len = 15)
      7777 772e 6578 616d 706c 652e 636f 6d   | www.example.com
                                              | -> :authority:
                                              |   www.example.com
      )";
  HpackBlockCollector expected;
  expected.ExpectIndexedHeader(2);
  expected.ExpectIndexedHeader(6);
  expected.ExpectIndexedHeader(4);
  expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
                                          1, false, "www.example.com");
  NoArgValidator do_check = [expected, this]() {
    VERIFY_AND_RETURN_SUCCESS(collector_.VerifyEq(expected));
  };
  EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
      example, ValidateDoneAndEmpty(do_check)));
  EXPECT_TRUE(do_check());
}

// http://httpwg.org/specs/rfc7541.html#rfc.section.C.5.1
TEST_F(HpackBlockDecoderTest, SpecExample_C_5_1) {
  std::string example = R"(
      48                                      | == Literal indexed ==
                                              |   Indexed name (idx = 8)
                                              |     :status
      03                                      |   Literal value (len = 3)
      3330 32                                 | 302
                                              | -> :status: 302
      58                                      | == Literal indexed ==
                                              |   Indexed name (idx = 24)
                                              |     cache-control
      07                                      |   Literal value (len = 7)
      7072 6976 6174 65                       | private
                                              | -> cache-control: private
      61                                      | == Literal indexed ==
                                              |   Indexed name (idx = 33)
                                              |     date
      1d                                      |   Literal value (len = 29)
      4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013
      2032 303a 3133 3a32 3120 474d 54        |  20:13:21 GMT
                                              | -> date: Mon, 21 Oct 2013
                                              |   20:13:21 GMT
      6e                                      | == Literal indexed ==
                                              |   Indexed name (idx = 46)
                                              |     location
      17                                      |   Literal value (len = 23)
      6874 7470 733a 2f2f 7777 772e 6578 616d | https://www.exam
      706c 652e 636f 6d                       | ple.com
                                              | -> location:
                                              |   https://www.example.com
      )";
  HpackBlockCollector expected;
  expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
                                          8, false, "302");
  expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
                                          24, false, "private");
  expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
                                          33, false,
                                          "Mon, 21 Oct 2013 20:13:21 GMT");
  expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
                                          46, false, "https://www.example.com");
  NoArgValidator do_check = [expected, this]() {
    VERIFY_AND_RETURN_SUCCESS(collector_.VerifyEq(expected));
  };
  EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
      example, ValidateDoneAndEmpty(do_check)));
  EXPECT_TRUE(do_check());
}

// Generate a bunch of HPACK block entries to expect, use those expectations
// to generate an HPACK block, then decode it and confirm it matches those
// expectations. Some of these are invalid (such as Indexed, with index=0),
// but well-formed, and the decoder doesn't check for validity, just
// well-formedness. That includes the validity of the strings not being checked,
// such as lower-case ascii for the names, and valid Huffman encodings.
TEST_F(HpackBlockDecoderTest, Computed) {
  HpackBlockCollector expected;
  expected.ExpectIndexedHeader(0);
  expected.ExpectIndexedHeader(1);
  expected.ExpectIndexedHeader(126);
  expected.ExpectIndexedHeader(127);
  expected.ExpectIndexedHeader(128);
  expected.ExpectDynamicTableSizeUpdate(0);
  expected.ExpectDynamicTableSizeUpdate(1);
  expected.ExpectDynamicTableSizeUpdate(14);
  expected.ExpectDynamicTableSizeUpdate(15);
  expected.ExpectDynamicTableSizeUpdate(30);
  expected.ExpectDynamicTableSizeUpdate(31);
  expected.ExpectDynamicTableSizeUpdate(4095);
  expected.ExpectDynamicTableSizeUpdate(4096);
  expected.ExpectDynamicTableSizeUpdate(8192);
  for (auto type : {HpackEntryType::kIndexedLiteralHeader,
                    HpackEntryType::kUnindexedLiteralHeader,
                    HpackEntryType::kNeverIndexedLiteralHeader}) {
    for (bool value_huffman : {false, true}) {
      // An entry with an index for the name. Ensure the name index
      // is not zero by adding one to the Rand8() result.
      expected.ExpectNameIndexAndLiteralValue(type, Rand8() + 1, value_huffman,
                                              Rand8String());
      // And two entries with literal names, one plain, one huffman encoded.
      expected.ExpectLiteralNameAndValue(type, false, Rand8String(),
                                         value_huffman, Rand8String());
      expected.ExpectLiteralNameAndValue(type, true, Rand8String(),
                                         value_huffman, Rand8String());
    }
  }
  // Shuffle the entries and serialize them to produce an HPACK block.
  expected.ShuffleEntries(RandomPtr());
  HpackBlockBuilder hbb;
  expected.AppendToHpackBlockBuilder(&hbb);

  NoArgValidator do_check = [expected, this]() {
    VERIFY_AND_RETURN_SUCCESS(collector_.VerifyEq(expected));
  };
  EXPECT_TRUE(
      DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check)));
  EXPECT_TRUE(do_check());
}

}  // namespace
}  // namespace test
}  // namespace http2


text:
package org.olat.core.gui.control.generic.textmarker;

import java.text.Collator;
import java.util.Locale;

import org.dom4j.Element;

/**
 *
 * Description: The TextMarker object represents the data
 *         structure for a single text marking The CSS class for formatting and
 *         the hoover text are optional
 *
 * @author gnaegi <www.goodsolutions.ch>
 * Initial Date: Jul 14, 2006
 *
 */
public class TextMarker implements Comparable {
	// XML names for the elements
	public static final String XML_CSS_CLASS_ELEMENT = "cssClass";
	public static final String XML_HOOVER_TEXT_ELEMENT = "hooverText";
	public static final String XML_MARKED_TEXT_ELEMENT = "markedText";
	public static final String XML_TEXT_MARKER_ELEMENT = "textMarker";
	// Default CSS classes
	public static final String CSS_MARK_GLOSSAR = "o_tm_glossary";
	public static final String CSS_MARK_RED = "o_tm_red";
	public static final String CSS_MARK_YELLOW = "o_tm_yellow";
	public static final String CSS_MARK_GREEN = "o_tm_green";
	public static final String CSS_MARK_BLUE = "o_tm_blue";

	/** This text will be marked. Can be a ';' separated list of keywords to have alias. */
	private String markedText;
	private String hooverText;
	private String cssClass;

	/**
	 * Constructor
	 *
	 * @param markedText Text to be marked
	 * @param cssClass CSS class, can be null
	 * @param hooverText The hoover text, can be null
	 */
	public TextMarker(String markedText, String cssClass, String hooverText) {
		this.markedText = markedText;
		this.cssClass = cssClass;
		this.hooverText = hooverText;
	}

	/**
	 * Constructor, used to create an object from an XML element
	 *
	 * @param textMarkerElement
	 */
	public TextMarker(Element textMarkerElement) {
		Element markedTexEl = textMarkerElement.element(XML_MARKED_TEXT_ELEMENT);
		this.markedText = (markedTexEl == null ? null : markedTexEl.getStringValue());
		Element hooverEl = textMarkerElement.element(XML_HOOVER_TEXT_ELEMENT);
		this.hooverText = (hooverEl == null ? null : hooverEl.getStringValue());
		Element cssEl = textMarkerElement.element(XML_CSS_CLASS_ELEMENT);
		this.cssClass = (cssEl == null ? null : cssEl.getStringValue());
	}

	/**
	 * Adds this text marker object to the give root element as XML object
	 *
	 * @param root
	 */
	public void addToElement(Element root) {
		Element textMarker = root.addElement(XML_TEXT_MARKER_ELEMENT);
		textMarker.addElement(XML_MARKED_TEXT_ELEMENT).addCDATA(markedText);
		if (hooverText != null) textMarker.addElement(XML_HOOVER_TEXT_ELEMENT).addCDATA(hooverText);
		if (cssClass != null) textMarker.addElement(XML_CSS_CLASS_ELEMENT).addCDATA(cssClass);
	}

	// general getters and setters
	public String getCssClass() {
		return cssClass;
	}

	public void setCssClass(String cssClass) {
		this.cssClass = cssClass;
	}

	public String getHooverText() {
		return hooverText;
	}

	public void setHooverText(String hooverText) {
		this.hooverText = hooverText;
	}

	/**
	 * Return the hole marked text value.
	 * @return
	 */
	public String getMarkedText() {
		return markedText;
	}

	/**
	 * Return only the first marked text in case of a ';'-separated keyword list.
	 * When the marked text is only a single keyword, this keyword will be return
	 * ( equals getMarkedText() ).
	 * @return
	 */
	public String getMarkedMainText() {
		if (markedText.indexOf(";") == -1) {
			return markedText; // no ';'delimited marked-text list
		}
		return markedText.substring(0,markedText.indexOf(";"));
	}

	/**
	 * Return only all alias keyword as ';'-separated list.
	 * When the marked text is only a single keyword, "" will be return.
	 * @return Return "" when it is a single keyword
	 */
	public String getMarkedAliasText() {
		if (markedText.indexOf(";") == -1) {
			return ""; // no ';'delimited marked-text list
		}
		return markedText.substring(markedText.indexOf(";")+1, markedText.length());
	}

	public void setMarkedText(String markedText) {
		this.markedText = markedText;
	}

	/**
	 * Comparison of two TextMarker objects is based on the markedText
	 * @param arg0
	 * @return
	 */
	public int compareTo(Object arg0) {
		// only compare against other text marker objects
		if (arg0 instanceof TextMarker) {
			TextMarker arg0Marker = (TextMarker) arg0;
			return Collator.getInstance(Locale.ENGLISH).compare(this.getMarkedText(), arg0Marker.getMarkedText());
		}
		return 0;
	}

    /**
     * Check only marked text and ignore case
     */
    public boolean equals(Object obj) {
        if (obj instanceof TextMarker) {
            TextMarker tm = (TextMarker)obj;
            if ( getMarkedText().equalsIgnoreCase(tm.getMarkedText()) ) {
                return true;
            }
        }
        return false;
    }

}


text:
[![Stories in Current Iteration](https://badge.waffle.io/cdeck3r/BattleShip.svg?label=ready&title=Current%20Iteration)](http://waffle.io/cdeck3r/BattleShip) [![Stories In Progress](https://badge.waffle.io/cdeck3r/BattleShip.svg?label=in%20progress&title=In%20Progress)](http://waffle.io/cdeck3r/BattleShip)

# Battleship Software Project

A software project is part of my lecture in Software Engineering at the Reutlingen University. Students are encouraged to develop a software using established software engineering practises including goal formulation, team constitution, requirements analysis, usage of UML, design patterns, software testing and versioning.

In the winter term 2015/16 the project is to develop is a [battleship clone](https://en.wikipedia.org/wiki/Battleship_%28game%29). The basic game rules provide a minimum set of requirements, which can be freely modified or extended by the students.

## Objective

Within the current term I want to increase my knowledge on some modern software technologies.

I have compiled the following technology mix below. I want to learn how quickly one can design, develop, test and document an application using this mix. Furthermore, I am interested in trying out microservices as an architectural style for my software.

My research questions are
* How smoothly play these technologies together?
* How steep is the learning curve?

Technology mix

* [Storiesonboard](http://storiesonboard.com/) to form a common understanding and give the requirment analysis process a direction
* [StarUML2](http://staruml.io) as UML tool for communicating software designs and documentating them
* [UMPLE](http://www.umple.org) for rapid model-driven programming
* Java is the primary programming language
* [Randoop](https://github.com/randoop) or [EvoSuite](http://www.evosuite.org/) for unit testing
* [Jolie](http://www.jolie-lang.org/) to support the implementation of a microservices based application
* [Hystrix](https://github.com/Netflix/Hystrix) to easily monitor the application
* GitHub for software versioning

[Eclipse](https://eclipse.org/) will be the primary IDE, because for most of the aforementioned technologies there is an Eclipse pluging available.

## Development Journal
The wiki pages contain my [development journal](https://github.com/cdeck3r/BattleShip/wiki) to documenting my efforts in following the objective and evaluating the results.

## Content

* User stories
* OOAD
* src
* ...

## Further Activities
If interested, you may also want to follow my lecture activities on Twitter: [@RTWIB_cdecker](https://twitter.com/rtwib_decker) or [#RTWIBSE](https://twitter.com/hashtag/RTWIBSE).

---
All software and documents are licensed under the MIT license (see LICENSE file).


text:
import logging
import logging.config
import os

LOG_SETTINGS = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'normal': {
            'format': "[%(asctime)s] %(name)s [pid:%(process)d] - %(levelname)s - %(message)s",  # noqa
            'datefmt': "%Y-%m-%d %H:%M:%S"
        },
    },
    'handlers': {
        'verbose': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'normal',
            'stream': 'ext://sys.stdout'
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'normal',
            'stream': 'ext://sys.stdout'
        },
        'error': {
            'level': 'ERROR',
            'class': 'logging.StreamHandler',
            'formatter': 'normal',
            'stream': 'ext://sys.stderr'
        },
    },
    'root': {
        'level': 'NOTSET',
        'handlers': ['console', 'error']
    },
}

LOGGING_VERBOSE = bool(os.environ.get("LOGGING_VERBOSE", False))
if LOGGING_VERBOSE:
    LOG_SETTINGS['root']['handlers'].remove('console')
    LOG_SETTINGS['root']['handlers'].append('verbose')

if os.getenv('LOGGING_FILE_CONFIG'):
    logging.config.fileConfig(os.getenv('LOGGING_FILE_CONFIG'))
else:
    logging.config.dictConfig(LOG_SETTINGS)


text:
<?php

use Illuminate\Foundation\AliasLoader;

class ServiceConfigTest extends TestCase {

	public function createApplication()
	{
	    $app = require __DIR__.'/../vendor/laravel/laravel/bootstrap/app.php';

	    $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

	    // Initial config (user defined)
	    $this->config = [
			'client' => [
        		'url' => 'http://example.com/jsonrpc',
			]
		];
		app('config')->set('rpc', $this->config);

	    $this->registerServiceProviders($app);
	    return $app;
	}

	public function testConfigDefault() {
		$rpc_config = app('config')->get('rpc');

		$this->assertContains('client', array_keys($rpc_config));
		$this->assertContains('server', array_keys($rpc_config));
		$this->assertContains('timeout', array_keys($rpc_config['client']));
		$this->assertContains('headers', array_keys($rpc_config['client']));
	}

	public function testConfigUser() {
		$rpc_config = app('config')->get('rpc');

		$this->assertEquals($this->config['client']['url'], $rpc_config['client']['url']);
	}
}


text:
namespace {
// Number of frames to use for sliding averages for pose timings,
// as used for estimating prediction times.
constexpr unsigned kSlidingAverageSize = 5;
}  // namespace

namespace vr {

BrowserRendererFactory::Params::Params(
    gvr::GvrApi* gvr_api,
    const UiInitialState& ui_initial_state,
    bool reprojected_rendering,
    bool cardboard_gamepad,
    bool pause_content,
    bool low_density,
    base::WaitableEvent* gl_surface_created_event,
    base::OnceCallback<gfx::AcceleratedWidget()> surface_callback)
    : gvr_api(gvr_api),
      ui_initial_state(ui_initial_state),
      reprojected_rendering(reprojected_rendering),
      cardboard_gamepad(cardboard_gamepad),
      pause_content(pause_content),
      low_density(low_density),
      gl_surface_created_event(gl_surface_created_event),
      surface_callback(std::move(surface_callback)) {}

BrowserRendererFactory::Params::~Params() = default;

std::unique_ptr<BrowserRenderer> BrowserRendererFactory::Create(
    VrGLThread* vr_gl_thread,
    UiFactory* ui_factory,
    std::unique_ptr<Params> params) {
  DCHECK(params);
  params->ui_initial_state.gvr_input_support = !params->cardboard_gamepad;

  auto audio_delegate = std::make_unique<SoundsManagerAudioDelegate>();
  auto ui =
      ui_factory->Create(vr_gl_thread, vr_gl_thread, nullptr, nullptr,
                         std::move(audio_delegate), params->ui_initial_state);
  std::unique_ptr<InputDelegate> input_delegate;
  if (params->cardboard_gamepad) {
    input_delegate = std::make_unique<CardboardInputDelegate>(params->gvr_api);
  } else {
    input_delegate = std::make_unique<GvrInputDelegate>(params->gvr_api);
  }
  auto graphics_delegate = std::make_unique<GvrGraphicsDelegate>(
      vr_gl_thread,
      base::BindOnce(&UiInterface::OnGlInitialized, base::Unretained(ui.get())),
      params->gvr_api, params->reprojected_rendering, params->pause_content,
      params->low_density, kSlidingAverageSize);
  auto scheduler_delegate = std::make_unique<GvrSchedulerDelegate>(
      vr_gl_thread, ui->GetSchedulerUiPtr(), params->gvr_api,
      graphics_delegate.get(), params->ui_initial_state.in_web_vr,
      params->cardboard_gamepad, kSlidingAverageSize);
  graphics_delegate->set_webxr_presentation_state(scheduler_delegate->webxr());
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(&GvrGraphicsDelegate::Init,
                     graphics_delegate->GetWeakPtr(),
                     base::Unretained(params->gl_surface_created_event),
                     std::move(params->surface_callback),
                     params->ui_initial_state.in_web_vr));
  auto browser_renderer = std::make_unique<BrowserRenderer>(
      std::move(ui), std::move(scheduler_delegate),
      std::move(graphics_delegate), std::move(input_delegate), vr_gl_thread,
      kSlidingAverageSize);
  return browser_renderer;
}

}  // namespace vr


text:
const { APPLICATION_JSON, ACCEPT, CONTENT_TYPE, X_ACCESS_TOKEN } = require("./constants");

const getJWT = function getJWT (options) {
  if (options && options.jwt) return options.jwt;
  else if (window.localStorage) {
    if (window.localStorage["JWT"]) return window.localStorage["JWT"];
    else throw Error("NO_JWT");
  } else throw Error("No localStorage available");
};

const authFetch = async function authFetch (URL, options) {
  const fetchOptions = options || {};
  const isMultipart = options && options.multipart;
  const throwHTTPErrorCodes = options && options.throwHTTPErrorCodes !== undefined ? options.throwHTTPErrorCodes : false;

  const headers = fetchOptions.headers || {};
  headers[X_ACCESS_TOKEN] = getJWT(options);
  headers[ACCEPT] = headers[ACCEPT] || APPLICATION_JSON;

  if (!isMultipart) headers[CONTENT_TYPE] = APPLICATION_JSON;

  fetchOptions.headers = headers;

  if (fetchOptions.body && typeof(fetchOptions.body) === "object" && !isMultipart) {
    fetchOptions.body = JSON.stringify(fetchOptions.body);
  }

  const res = await fetch(URL, fetchOptions);

  if (throwHTTPErrorCodes && res && res.status >= 400 && res.status <= 599) {
    throw res;
  } else {
    return res;
  }
};

module.exports = authFetch;


text:
"""Raffle View Test"""
import datetime
import re

from django.test import TransactionTestCase
from django.core.urlresolvers import reverse
from apps.managers.challenge_mgr import challenge_mgr
from apps.managers.challenge_mgr.models import RoundSetting
from apps.utils import test_utils

from apps.widgets.raffle.models import RafflePrize

class RafflePrizesTestCase(TransactionTestCase):
    """Raffle Test"""
    fixtures = ["demo_teams.json"]

    def setUp(self):
        """Set up rounds, team, and a user."""
        # Set up rounds.

        test_utils.set_three_rounds()

        # Set up user
        self.user = test_utils.setup_user(username="user", password="changeme")

        challenge_mgr.register_page_widget("win", "raffle")
        self.client.login(username="user", password="changeme")

    def testIndex(self):
        """Check that we can load the index page."""
        raffle_prize = RafflePrize(
            title="Test raffle prize",
            description="A raffle prize for testing",
            round=RoundSetting.objects.get(name="Round 3"),
            value=5,
        )
        raffle_prize.save()

        response = self.client.get(reverse("win_index"))
        self.failUnlessEqual(response.status_code, 200)
        self.assertContains(response, "Round 2 Raffle",
            msg_prefix="We should be in round 2 of the raffle.")
        print response
        self.assertContains(response,
            "Your Total Raffle Tickets: 0,",
            msg_prefix="User should not have any raffle tickets.")
        self.assertContains(response,
            "Allocated:  0,",
            msg_prefix="User should not have any raffle tickets.")
        self.assertContains(response,
            "Available: 0",
            msg_prefix="User should not have any raffle tickets.")
        deadline = challenge_mgr.get_round_info()["end"]
        date_string = deadline.strftime("%b. %d, %Y, %I:%M ")
        date_string = re.sub(r" \b0", " ", date_string)
        #self.assertContains(response, "Deadline for Round 2 submissions: " + date_string,
        #    msg_prefix="Raffle should have the correct deadline.")

        # Give the user some points and see if their tickets update.
        profile = self.user.get_profile()
        profile.add_points(25, datetime.datetime.today(), "test")
        profile.save()
        response = self.client.get(reverse("win_index"))
        self.assertContains(response,
            "Your Total Raffle Tickets: 1",
            msg_prefix="User should have 1 raffle ticket.")
        self.assertContains(response,
            "Allocated:  0,",
            msg_prefix="User should have 1 raffle ticket.")
        self.assertContains(response,
            "Available: 1",
            msg_prefix="User should have 1 raffle ticket.")

    def testAddRemoveTicket(self):
        """Test that we can add and remove a ticket for a prize."""
        raffle_prize = RafflePrize(
            title="Test raffle prize",
            description="A raffle prize for testing",
            round=RoundSetting.objects.get(name="Round 2"),
            value=5,
        )
        raffle_prize.save()

        profile = self.user.get_profile()
        profile.add_points(25, datetime.datetime.today(), "test")
        profile.save()

        # Test that we can add a ticket.
        response = self.client.get(reverse("win_index"))
        self.assertContains(response, reverse("raffle_add_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should be a url to add a ticket.")

        # Test adding a ticket to a prize.
        response = self.client.post(reverse("raffle_add_ticket", args=(raffle_prize.id,)),
            follow=True)
        self.failUnlessEqual(response.status_code, 200)
        self.assertContains(response,
            "Your Total Raffle Tickets: 1",
            msg_prefix="User should have one allocated ticket.")
        self.assertContains(response,
            "Allocated:  1,",
            msg_prefix="User should have one allocated ticket.")
        self.assertContains(response,
            "Available: 0",
            msg_prefix="User should have one allocated ticket.")
        self.assertContains(response, reverse("raffle_remove_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should be an url to remove a ticket.")
        self.assertNotContains(response, reverse("raffle_add_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should not be an url to add a ticket.")

        # Test adding another ticket to the prize.
        profile.add_points(25, datetime.datetime.today(), "test")
        profile.save()
        response = self.client.post(reverse("raffle_add_ticket", args=(raffle_prize.id,)),
            follow=True)
        self.assertContains(response,
            "Your Total Raffle Tickets: 2",
            msg_prefix="User should have two allocated tickets.")
        self.assertContains(response,
            "Allocated:  2,",
            msg_prefix="User should have two allocated tickets.")
        self.assertContains(response,
            "Available: 0",
            msg_prefix="User should have two allocated tickets.")

        # Test removing a ticket.
        response = self.client.post(reverse("raffle_remove_ticket", args=(raffle_prize.id,)),
            follow=True)
        self.assertContains(response,
            "Your Total Raffle Tickets: 2",
            msg_prefix="User should have one allocated ticket and one available.")
        self.assertContains(response,
            "Allocated:  1,",
            msg_prefix="User should have one allocated ticket and one available.")
        self.assertContains(response,
            "Available: 1",
            msg_prefix="User should have one allocated ticket and one available.")
        self.assertContains(response, reverse("raffle_add_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should be a url to add a ticket.")
        self.assertContains(response, reverse("raffle_remove_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should be an url to remove a ticket.")

    def testAddRemoveWithoutTicket(self):
        """Test that the user cannot remove a ticket from a prize they did not
        allocate tickets in."""
        raffle_prize = RafflePrize(
            title="Test raffle prize",
            description="A raffle prize for testing",
            round=RoundSetting.objects.get(name="Round 1"),
            value=5,
        )
        raffle_prize.save()

        # Test removing a ticket.
        response = self.client.post(reverse("raffle_remove_ticket", args=(raffle_prize.id,)),
            follow=True)
        self.failUnlessEqual(response.status_code, 200)
        self.assertContains(response,
            "Your Total Raffle Tickets: 0",
            msg_prefix="User should have no tickets available")
        self.assertContains(response,
            "Allocated:  0,",
            msg_prefix="User should have no tickets available")
        self.assertContains(response,
            "Available: 0",
            msg_prefix="User should have no tickets available")
        self.assertNotContains(response, reverse("raffle_add_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should not be a url to add a ticket.")
        self.assertNotContains(response, reverse("raffle_remove_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should not be a url to remove a ticket.")

    def testAddWithoutTicket(self):
        """
        Test that the user cannot add a ticket to a raffle if they don't have any tickets.
        """
        raffle_prize = RafflePrize(
            title="Test raffle prize",
            description="A raffle prize for testing",
            round=RoundSetting.objects.get(name="Round 1"),
            value=5,
        )
        raffle_prize.save()

        # Test adding a ticket.
        response = self.client.post(reverse("raffle_add_ticket", args=(raffle_prize.id,)),
            follow=True)
        self.failUnlessEqual(response.status_code, 200)
        self.assertContains(response,
            "Your Total Raffle Tickets: 0",
            msg_prefix="User should have no tickets available")
        self.assertContains(response,
            "Allocated:  0,",
            msg_prefix="User should have no tickets available")
        self.assertContains(response,
            "Available: 0",
            msg_prefix="User should have no tickets available")
        self.assertNotContains(response, reverse("raffle_add_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should not be a url to add a ticket.")
        self.assertNotContains(response, reverse("raffle_remove_ticket", args=(raffle_prize.id,)),
            msg_prefix="There should not be a url to remove a ticket.")

    def testPrizeOutsideOfRound(self):
        """
        Test that a raffle prize outside of the round does not appear in the list.
        """

        raffle_prize = RafflePrize(
            title="Test raffle prize",
            description="A raffle prize for testing",
            round=RoundSetting.objects.get(name="Round 1"),
            value=5,
        )
        raffle_prize.save()

        response = self.client.get(reverse("win_index"))
        self.failUnlessEqual(response.status_code, 200)
        self.assertNotContains(response, "Test raffle prize")


text:
import datetime

from realtime.database.adapter import db

class TodoItems(db.Model):
    __table_args__ = ({'schema': 'flask'},
                      )
    __tablename__ = 'todo_items'
    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    title = db.Column(db.String(128))

    def __repr__(self):
        return r'<TodoItems "%s" at %s>' % (self.title, self.timestamp)

class Subscriptions(db.Model):
    __bind_key__ = 'sessions_db'
    __tablename__ = 'subscriptions'

    id = db.Column(db.Integer, primary_key=True)
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    record_id = db.Column(db.Integer)
    table_name = db.Column(db.String)

    socket_io_id = db.Column(db.String)


text:
const prettyBytes = require('pretty-bytes');

const bytes = 100000000;
const buf = Buffer.alloc(bytes);
const interval = 25;
const syncStart = Date.now();
const asyncJobs = 4;

console.log(`Registering ${asyncJobs} asynchronous jobs...`);
let i = 0;
const syncId = setInterval(() => {
	if (++i >= asyncJobs) {
		clearInterval(syncId);
	}

	const late = Date.now() - (syncStart + (interval * i));
	console.log(`Hi, I'm an asynchronous job, and I'm ${late > 10 ? `late by ${late}ms` : 'on time'}`);
}, interval);

console.log(`Encoding ${prettyBytes(bytes)} with default Node.js Buffer API...`);
buf.toString('base64');
console.log('Base64 encode complete');


text:
%Main Module for Simulation Run (mainSimRun1.m)
% of Sparse QNC

warning off;
close all;
clear all;
format long;
clc;

saveFileName='resMain1run1';

RlzS=100;

nodes=100;
iterations=20;
C0=1;                 %Capacity of Links
perNodeEdges=4;       %must be less than number of nodes

sigmaBig=5;
xRange=sigmaBig*4;
phiSparsityOrder=-1; %2
spVec=[.1 .2 .3];
bLenVec=[10:5:70];

densityRow=1;

for rlzInd=1:RlzS
    %%%Generates the random network deployment
    [htList,GWnode,B]=GenNetCapsule(nodes,perNodeEdges);

    edges=size(htList,1);
    %%%Generating NC coefficients (sparsely)
    %[A,F]=GencoefOneStep(nodes,edges,iterations,htList,densityRow); %for One Step
    [A,F]=GenQNCcoef(nodes,edges,iterations,htList);
    [Psi,PsiTot]=calculateQNC(iterations,A,F,B);
    for spInd=1:length(spVec)
        sparsityFactor=spVec(spInd);
        k=round(nodes*sparsityFactor);
        %Generate Messages
        [x,phi,xNorm1,Sdomain]=GenMess(nodes,htList,phiSparsityOrder,k,xRange,sigmaBig);

        %Perform QNC for different block lengths
        for blInd=1:length(bLenVec)
            bLen=bLenVec(blInd);
            DeltaQ=2*xRange/(2^(bLen*C0)-1);
            sigmaQ=DeltaQ^2*0.2;    %Using the experimental results
            [zTot,numMeas(:,rlzInd,blInd,spInd),nEffTot]=simulateQNC(iterations,DeltaQ,x,A,F,B,PsiTot);
            xNorm(rlzInd,blInd,spInd)=norm(x,2);
            %BP based Decoding :|
            %disp('Start Decoding');
            tic;
            [recX(:,rlzInd,blInd,spInd),recErrNormBP(:,rlzInd,blInd,spInd)]=BPdecoder(x,Sdomain,zTot,PsiTot,F,A,B,phi,k,sigmaBig,sigmaQ);
            %[recX(:,rlzInd),recErrNormBP(:,rlzInd)]=BPdecoderNBP(x,zTot,PsiTot,F,A,B,phi,k,sigmaBig,sigmaQ);
            decTimeBP(rlzInd,blInd,spInd)=toc;

            tic;
            [recXl1min(:,rlzInd,blInd,spInd),recErrNorml1min(:,rlzInd,blInd,spInd)]=L1MINdecoder(zTot,PsiTot,phi,x,DeltaQ,A,F,B);
            decTimeL1(rlzInd,blInd,spInd)=toc;
            tic;
            [recXPinv(:,rlzInd,blInd,spInd),recErrNormPinv(:,rlzInd,blInd,spInd)]=PINVdecoder(zTot,PsiTot,phi,x);
            decTimePI(rlzInd,blInd,spInd)=toc;
            fprintf([num2str(bLen) '-']);
        end
        fprintf('\n');
    end
    disp(['- Realization ' num2str(rlzInd) '/' num2str(RlzS) ' is done.']);
end

save(saveFileName);


text:
describe TreeNode::Switch do
  subject { described_class.new(object, nil, nil) }
  let(:object) { FactoryBot.create(:switch, :name => "light") }

  include_examples 'TreeNode::Node#key prefix', 'sw-'
  include_examples 'TreeNode::Node#icon', 'ff ff-network-switch'
  include_examples 'TreeNode::Node#tooltip prefix', 'Switch'
end


text:
package com.invisiblecollector;

import com.invisiblecollector.exceptions.IcException;

public interface IThrowingBuilder2<ReturnT, Arg1T, Arg2T> {
  ReturnT build(Arg1T arg1, Arg2T arg2) throws IcException;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Portfolio Item - Start Bootstrap Template</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/portfolio-item.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Start Bootstrap

                        About

                        Services

                        Contact

        Creative, Logical, Delightful

S MARUYAMA

Portfolio Website

Portfolio Item
                        Item Subheading

Project Description

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae. Sed dui lorem, adipiscing in adipiscing et, interdum nec metus. Mauris ultricies, justo eu convallis placerat, felis enim.

Project Details

Lorem Ipsum

Dolor Sit Amet

Consectetur

Adipiscing Elit

Related Projects

Copyright © Your Website 2014


text:
'use strict';

const opentelemetry = require('@opentelemetry/api');
const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
const { SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-base');
const { JaegerExporter } = require('@opentelemetry/exporter-jaeger');
const { IORedisInstrumentation } = require('@opentelemetry/instrumentation-ioredis');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');

const provider = new NodeTracerProvider();

const exporter = new JaegerExporter({ serviceName: 'ioredis-example' });

provider.addSpanProcessor(new SimpleSpanProcessor(exporter));

// Initialize the OpenTelemetry APIs to use the BasicTracer bindings
provider.register();

registerInstrumentations({
  instrumentations: [
    new IORedisInstrumentation(),
  ],
});

module.exports = opentelemetry.trace.getTracer('ioredis-example');


text:
var webpack = require("webpack");

var envReplacements = new webpack.DefinePlugin({
  __SERVER_URL__:    JSON.stringify(process.env.SERVER_URL || 'http://localhost:3000'),
  __FIREBASE_HOST__: JSON.stringify(process.env.FIREBASE_HOST)
});

module.exports = {
  devtool: "source-map",

  entry: "./app/App.js",
  output: {
    filename: "public/bundle.js"
  },
  module: {
    loaders: [
      {test: /\.js$/, loader: 'jsx-loader?harmony'}
    ]
  },
  plugins: [envReplacements]
};


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.ogcs.netty.handler.mq</title>
<meta name="date" content="2017-07-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.ogcs.netty.handler.mq

类

LogicProcessor

MessageQueueHandler


text:
// Package server exposes an HTTP interface to the xrefs and filetree
// services.
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"path/filepath"

	"kythe.io/kythe/go/services/filetree"
	"kythe.io/kythe/go/services/search"
	"kythe.io/kythe/go/services/xrefs"
	ftsrv "kythe.io/kythe/go/serving/filetree"
	srchsrv "kythe.io/kythe/go/serving/search"
	xsrv "kythe.io/kythe/go/serving/xrefs"
	"kythe.io/kythe/go/storage/leveldb"
	"kythe.io/kythe/go/storage/table"

	"golang.org/x/net/context"
)

var (
	servingTable    = flag.String("serving_table", "/srv/table", "LevelDB serving table path")
	publicResources = flag.String("public_resources", "/srv/public", "Path to directory of static resources to serve")
	listeningAddr   = flag.String("listen", "localhost:8080", "Listening address for HTTP server")
)

func main() {
	flag.Parse()

	db, err := leveldb.Open(*servingTable, nil)
	if err != nil {
		log.Fatalf("Error opening db at %q: %v", *servingTable, err)
	}
	defer db.Close()
	tbl := &table.KVProto{db}

	ctx := context.Background()
	xrefs.RegisterHTTPHandlers(ctx, &xsrv.Table{tbl}, http.DefaultServeMux)
	filetree.RegisterHTTPHandlers(ctx, &ftsrv.Table{tbl}, http.DefaultServeMux)
	search.RegisterHTTPHandlers(ctx, &srchsrv.Table{&table.KVInverted{db}}, http.DefaultServeMux)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, filepath.Join(*publicResources, filepath.Clean(r.URL.Path)))
	})

	http.HandleFunc("/_ah/health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "ok")
	})
	http.HandleFunc("/_ah/start", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "sure, we'll start!")
	})

	log.Printf("Server listening on %q", *listeningAddr)
	log.Fatal(http.ListenAndServe(*listeningAddr, nil))
}


text:
import React, { Component } from 'react'
import DOMAIN_LIST from '../domains'

class User extends Component {
  constructor(props) {
    super(props)
    this.state = {
      name: "",
      email: "",
      password: "",
      isCustomDomain: false,
      isUserSubmitted: false,
      isCardCharged: false,
      togglePaymentForm: false,
      toggleCompanyForm: false
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.isUserSubmitted !== nextProps.isUserSubmitted) {
      this.setState({isUserSubmitted: nextProps.isUserSubmitted})
    }

    if (this.state.isCardCharged !== nextProps.isCardCharged) {
      this.setState({isCardCharged: nextProps.isCardCharged})
    }
  }

  changeHandler(which, e) {
    this.state[which] = e.target.value
    this.setState(this.state);
  }

  validateEmail(e) {
    e.preventDefault();

    let domain = this.state.email.replace(/.*@/, "")
    // let isCustomDomain = DOMAIN_LIST.indexOf(domain) === -1
    let isCustomDomain = true // add company details for all Email ids.

    if (isCustomDomain) {
      this.state.isCustomDomain = isCustomDomain

      // Show payment form if buy plan chosen, and card is not charged
      if (this.props.buyPlan && !this.state.isCardCharged) {
        this.state.togglePaymentForm = true
        this.state.toggleCompanyForm = false
      } else {
        this.state.togglePaymentForm = false
        this.state.toggleCompanyForm = true
      }
    }

    this.state.isUserSubmitted = true
    this.setState(this.state)
    this.props.setUserDetails(this.state)
  }

  render() {
    return (
      <div>
        <form onSubmit={this.validateEmail.bind(this)} className={this.state.isUserSubmitted ? 'hide' : ''}>
          <input type="text"
                value={this.state.name}
                onChange={this.changeHandler.bind(this, 'name')}
                className="loginInput from-control"
                id="SignupName"
                placeholder="Full Name" required/>

          <input  type="email"
                  value={this.state.email}
                  onChange={this.changeHandler.bind(this, 'email')}
                  className="loginInput from-control"
                  id="SignupEmail"
                  placeholder="Email" required />

          <input  type="password"
                  value={this.state.password}
                  onChange={this.changeHandler.bind(this, 'password')}
                  className="loginInput from-control"
                  id="SignupPassword"
                  placeholder="Password" required />

          <button className="loginbtn"
                  id="SignupBtn"
                  type="submit"> Sign up for CloudBoost
          </button>
        </form>
      </div>
    )
  }
}

export default User


text:
namespace impala {

class FreePool;
class MemPool;
class RuntimeState;

/// This class actually implements the interface of FunctionContext. This is split to
/// hide the details from the external header.
/// Note: The actual user code does not include this file.
class FunctionContextImpl {
 public:
  /// Create a FunctionContext for a UDF. Caller is responsible for deleting it.
  static impala_udf::FunctionContext* CreateContext(RuntimeState* state, MemPool* pool,
      const impala_udf::FunctionContext::TypeDesc& return_type,
      const std::vector<impala_udf::FunctionContext::TypeDesc>& arg_types,
      int varargs_buffer_size = 0, bool debug = false);

  /// Create a FunctionContext for a UDA. Identical to the UDF version except for the
  /// intermediate type. Caller is responsible for deleting it.
  static impala_udf::FunctionContext* CreateContext(RuntimeState* state, MemPool* pool,
      const impala_udf::FunctionContext::TypeDesc& intermediate_type,
      const impala_udf::FunctionContext::TypeDesc& return_type,
      const std::vector<impala_udf::FunctionContext::TypeDesc>& arg_types,
      int varargs_buffer_size = 0, bool debug = false);

  FunctionContextImpl(impala_udf::FunctionContext* parent);

  /// Checks for any outstanding memory allocations. If there is unfreed memory, adds a
  /// warning and frees the allocations. Note that local allocations are freed with the
  /// MemPool backing pool_.
  void Close();

  /// Returns a new FunctionContext with the same constant args, fragment-local state, and
  /// debug flag as this FunctionContext. The caller is responsible for calling delete on
  /// it.
  impala_udf::FunctionContext* Clone(MemPool* pool);

  /// Allocates a buffer of 'byte_size' with "local" memory management. These
  /// allocations are not freed one by one but freed as a pool by FreeLocalAllocations()
  /// This is used where the lifetime of the allocation is clear.
  /// For UDFs, the allocations can be freed at the row level.
  /// TODO: free them at the batch level and save some copies?
  uint8_t* AllocateLocal(int byte_size);

  /// Frees all allocations returned by AllocateLocal().
  void FreeLocalAllocations();

  /// Sets constant_args_. The AnyVal* values are owned by the caller.
  void SetConstantArgs(const std::vector<impala_udf::AnyVal*>& constant_args);

  uint8_t* varargs_buffer() { return varargs_buffer_; }

  std::vector<impala_udf::AnyVal*>* staging_input_vals() { return &staging_input_vals_; }

  bool debug() { return debug_; }
  bool closed() { return closed_; }

  int64_t num_updates() const { return num_updates_; }
  int64_t num_removes() const { return num_removes_; }
  void set_num_updates(int64_t n) { num_updates_ = n; }
  void set_num_removes(int64_t n) { num_removes_ = n; }
  void IncrementNumUpdates(int64_t n = 1) { num_updates_ += n; }
  void IncrementNumRemoves(int64_t n = 1) { num_removes_ += n; }

  static const char* LLVM_FUNCTIONCONTEXT_NAME;

  RuntimeState* state() { return state_; }

 private:
  friend class impala_udf::FunctionContext;

  /// Preallocated buffer for storing varargs (if the function has any). Allocated and
  /// owned by this object, but populated by an Expr function.
  //
  /// This is the first field in the class so it's easy to access in codegen'd functions.
  /// Don't move it or add fields above unless you know what you're doing.
  uint8_t* varargs_buffer_;
  int varargs_buffer_size_;

  /// Parent context object. Not owned
  impala_udf::FunctionContext* context_;

  /// Pool to service allocations from.
  FreePool* pool_;

  /// We use the query's runtime state to report errors and warnings. NULL for test
  /// contexts.
  RuntimeState* state_;

  /// If true, indicates this is a debug context which will do additional validation.
  bool debug_;

  impala_udf::FunctionContext::ImpalaVersion version_;

  /// Empty if there's no error
  std::string error_msg_;

  /// The number of warnings reported.
  int64_t num_warnings_;

  /// The number of calls to Update()/Remove().
  int64_t num_updates_;
  int64_t num_removes_;

  /// Allocations made and still owned by the user function. Only used if debug_ is true
  /// because it is very expensive to maintain.
  std::map<uint8_t*, int> allocations_;
  /// Allocations owned by Impala.
  std::vector<uint8_t*> local_allocations_;

  /// The function state accessed via FunctionContext::Get/SetFunctionState()
  void* thread_local_fn_state_;
  void* fragment_local_fn_state_;

  /// The number of bytes allocated externally by the user function. In some cases,
  /// it is too inconvenient to use the Allocate()/Free() APIs in the FunctionContext,
  /// particularly for existing codebases (e.g. they use std::vector). Instead, they'll
  /// have to track those allocations manually.
  int64_t external_bytes_tracked_;

  /// Type descriptor for the intermediate type of a UDA. Set to INVALID_TYPE for UDFs.
  impala_udf::FunctionContext::TypeDesc intermediate_type_;

  /// Type descriptor for the return type of the function.
  impala_udf::FunctionContext::TypeDesc return_type_;

  /// Type descriptors for each argument of the function.
  std::vector<impala_udf::FunctionContext::TypeDesc> arg_types_;

  /// Contains an AnyVal* for each argument of the function. If the AnyVal* is NULL,
  /// indicates that the corresponding argument is non-constant. Otherwise contains the
  /// value of the argument.
  std::vector<impala_udf::AnyVal*> constant_args_;

  /// Used by ScalarFnCall to store the arguments when running without codegen. Allows us
  /// to pass AnyVal* arguments to the scalar function directly, rather than codegening a
  /// call that passes the correct AnyVal subclass pointer type. Note that this is only
  /// used for non-variadic arguments; varargs are always stored in varargs_buffer_.
  std::vector<impala_udf::AnyVal*> staging_input_vals_;

  /// Indicates whether this context has been closed. Used for verification/debugging.
  bool closed_;
};

}

namespace impala_udf {

/// Temporary ArrayVal definition. This is not ready for public consumption because users
/// must have access to our internal tuple layout.
struct ArrayVal : public AnyVal {
  uint8_t* ptr;
  int num_tuples;

  /// Construct an ArrayVal from ptr/num_tuples. Note: this does not make a copy of ptr so
  /// the buffer must exist as long as this ArrayVal does.
  ArrayVal(uint8_t* ptr = NULL, int num_tuples = 0) : ptr(ptr), num_tuples(num_tuples) {}

  static ArrayVal null() {
    ArrayVal av;
    av.is_null = true;
    return av;
  }
};

}

#endif


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \DateTime
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(name="created", type="datetime")
     */
    protected $created;

    /**
     * @var \DateTime
     * @Gedmo\Timestampable(on="update")
     * @ORM\Column(name="updated", type="datetime")
     */
    protected $updated;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="deleted", type="datetime", nullable=true)
     */
    protected $deleted = null;

    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Task", mappedBy="user", cascade={"persist"})
     */
    protected $tasks;

    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\TaskJobTime", mappedBy="user", cascade={"persist"})
     */
    protected $taskJobTimes;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return User
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     * @return User
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Add tasks
     *
     * @param \AppBundle\Entity\Task $tasks
     * @return User
     */
    public function addTask(\AppBundle\Entity\Task $tasks)
    {
        $this->tasks[] = $tasks;

        return $this;
    }

    /**
     * Remove tasks
     *
     * @param \AppBundle\Entity\Task $tasks
     */
    public function removeTask(\AppBundle\Entity\Task $tasks)
    {
        $this->tasks->removeElement($tasks);
    }

    /**
     * Get tasks
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTasks()
    {
        return $this->tasks;
    }

    /**
     * Set deleted
     *
     * @param \DateTime $deleted
     * @return User
     */
    public function setDeleted($deleted)
    {
        $this->deleted = $deleted;

        return $this;
    }

    /**
     * Get deleted
     *
     * @return \DateTime
     */
    public function getDeleted()
    {
        return $this->deleted;
    }

    /**
     * Add taskJobTimes
     *
     * @param \AppBundle\Entity\TaskJobTime $taskJobTimes
     * @return User
     */
    public function addTaskJobTime(\AppBundle\Entity\TaskJobTime $taskJobTimes)
    {
        $this->taskJobTimes[] = $taskJobTimes;

        return $this;
    }

    /**
     * Remove taskJobTimes
     *
     * @param \AppBundle\Entity\TaskJobTime $taskJobTimes
     */
    public function removeTaskJobTime(\AppBundle\Entity\TaskJobTime $taskJobTimes)
    {
        $this->taskJobTimes->removeElement($taskJobTimes);
    }

    /**
     * Get taskJobTimes
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTaskJobTimes()
    {
        return $this->taskJobTimes;
    }
}


text:
<?php
/**
 * 获取用户授权信息接口.
 *
 * @author lvshuang1201@gmail.com
 */
namespace Top\Component\WeixinAuth;

class UserAuth extends AccessToken
{

    protected $weixinCodeUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?'; // 获取code地址
    protected $accessTokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
    protected $callBackUrl; // 微信回调地址
    protected $grantType = 'client_credential';
    protected $code;

    protected function initConfig($config)
    {
        parent::initConfig($config);
        if (!empty($config['auth_callback'])) {
            throw new \Top\Common\BusinessException('weixin auth callback url not config');
        }
        $this->callBackUrl = $config['auth_callback'];
    }

    public function setCode($code)
    {
        if (empty($code)) {
            throw new \Top\Common\BusinessException('weixin auth code empty');
        }
        $this->code = $code;
    }

    /**
     * 返回跳转到微信获取code的地址.
     *
     * @return string
     */
    public function getCodeRedrict()
    {
        $params = array(
            'appid' => $this->appId,
            'redrict_uri' => $this->callBackUrl,
            'response_type' => 'code',
            'scope' => 'snsapi_userinfo',
            'state' => time(),
        );
        return $this->weixinCodeUrl . urlencode(http_build_query($params)) . '#wechat_redrict';
    }

    protected function buildGetAccessTokenParams()
    {
        if (empty($this->code)) {
            throw new \Top\Common\BusinessException('weixin auth code not set');
        }
        return array(
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'code' => $this->code,
            'grant_type' => $this->grantType,
        );
    }

}


text:
namespace Alchemy4Tridion.Plugins.GUI.Configuration.Extensions
{
    /// <summary>
    /// Represents an applied to view in the configuration.
    /// </summary>
    public class ApplyView
    {
        /// <summary>
        /// Gets or sets the control id the extension is applied to.
        /// </summary>
        public string ControlId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the name of the view to apply the extension to.
        /// </summary>
        public string Name
        {
            get;
            set;
        }
    }
}


text:
<?php

require_once dirname(__FILE__).'/errors/ValidationException.php';

/**
 * The ValidationErrorList class defines a well-formed collection of
 * ValidationExceptions so that groups of validation functions can be
 * called in a non-blocking fashion.
 *
 *

 *
 *

 *
 * To use the ValidationErrorList to execute groups of validation
 * attempts, your controller code would look something like:
 *
 *

 * ValidationErrorList() errorList = new ValidationErrorList();.
 * String name  = getValidInput("Name", form.getName(), "SomeESAPIRegExName1", 255, false, errorList);
 * String address = getValidInput("Address", form.getAddress(), "SomeESAPIRegExName2", 255, false, errorList);
 * Integer weight = getValidInteger("Weight", form.getWeight(), 1, 1000000000, false, errorList);
 * Integer sortOrder = getValidInteger("Sort Order", form.getSortOrder(), -100000, +100000, false, errorList);
 * request.setAttribute( "ERROR_LIST", errorList );
 *

 *
 * The at your view layer you would be able to retrieve all
 * of your error messages via a helper function like:
 *
 *

 * public static ValidationErrorList getErrors() {
 *     HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest();
 *     ValidationErrorList errors = new ValidationErrorList();
 *     if (request.getAttribute(Constants.ERROR_LIST) != null) {
 *        errors = (ValidationErrorList)request.getAttribute("ERROR_LIST");
 *     }
 * 	   return errors;
 * }
 *

 *
 * You can list all errors like:
 *
 *

 * <%
 *      for (Object vo : errorList.errors()) {
 *         ValidationException ve = (ValidationException)vo;
 * %>
 * <%= ESAPI.encoder().encodeForHTML(ve.getMessage()) %>

 * <%
 *     }
 * %>
 *

 *
 * And even check if a specific UI component is in error via calls like:
 *
 *

 * ValidationException e = errorList.getError("Name");
 *

 *
 * @author
 * @since 1.4
 */
class ValidationErrorList {

	/**
	 * Error list of ValidationException's
	 */
	// private HashMap errorList = new HashMap();

	/**
	 * Adds a new error to list with a unique named context.
	 * No action taken if either element is null.
	 * Existing contexts will be overwritten.
	 *
	 * @param context unique named context for this ValidationErrorList
	 * @param ve
	 */
	public function addError($context, $ve) {
//		if (getError(context) != null) throw new RuntimeException("Context (" + context + ") already exists, programmer error");
//
//		if ((context != null) && (ve != null)) {
//			errorList.put(context, ve);
//		}
	}

	/**
	 * Returns list of ValidationException, or empty list of no errors exist.
	 *
	 * @return List
	 */
	public function errors() {
//		return new ArrayList( errorList.values() );
	}

	/**
	 * Retrieves ValidationException for given context if one exists.
	 *
	 * @param context unique name for each error
	 * @return ValidationException or null for given context
	 */
	public function getError($context) {
//		if (context == null) return null;
//		return (ValidationException)errorList.get(context);
	}

	/**
	 * Returns true if no error are present.
	 *
	 * @return boolean
	 */
	public function isEmpty() {
//		return errorList.isEmpty();
	}

	/**
	 * Returns the numbers of errors present.
	 *
	 * @return boolean
	 */
	public function size() {
//		return errorList.size();
	}
}


text:
type Email = string

// Data from nodemailer
export type DeliveryResult = {
  messageId: string
  envelope: Object
  accepted: string[] // email addresses
  rejected: string[]
  pending: string[]
  response: string
}

export type MessageOptions = Object

export type SmtpConfig = {
  service: string
  auth: SmtpAuthConfig
}

type SmtpAuthConfig = {
  type: "OAuth2"
  accessToken: string
  clientId: string
  clientSecret: string
  expires: number
  refreshToken: string
  service: string
  user: Email
}

export interface Transporter {
  sendMail(message: MessageOptions): Promise<DeliveryResult>
}


text:
"""
This file will contain objects used to represent the independent intermediate
format of the program.

Initially it's being a bridging/extraction point.
"""

class iiNode(object): # This is to allow intermediate thunk check whether it has an iiNode or not...
    tag = "iinode"
    def __init__(self):
        raise TypeError("Abstract Base class method called")
    def __json__(self):
        raise TypeError("Abstract Base class method called")

class iiProgram(iiNode):
    tag = "program"
    def __init__(self, name, includes, identifiers, statements):
        self.name = name
        self.includes = includes[:]         # Create shallow clone of includes
        self.global_identifiers = identifiers
        self.statements = statements

    def __json__(self):
        # Backwards compatibility thunk - later will be used for debugging/a pretty printing representation
        program = {}
        program["name"] = self.name
        program["includes"] = sorted(self.includes)
        program["main"] = {}

        program["main"]["c_frame"] = {}
        program["main"]["c_frame"]["identifiers"] = self.global_identifiers
        program["main"]["c_frame"]["statements"] = self.statements
        print("PROGRAM", program)
        result = {"PROGRAM" : program }
        return result

class iiAssignment(iiNode):
    tag = "assignment"
    def __init__(self, lvalue, assignment_op, rvalue):
        self.lvalue = lvalue
        self.assignment_op = assignment_op
        self.rvalue= rvalue
    def __json__(self):
        return ["assignment", self.lvalue, self.assignment_op, self.rvalue ]

class iiOperator(iiNode):
    tag = "operator"
    def __init__(self, operator, args):
        # FIXME: This is a transform that should happen outside this file...
        if operator=="op_plus":
            self.operator = "plus"

        elif operator=="op_minus":
            self.operator = "minus"

        elif operator=="op_times":
            self.operator = "times"

        elif operator=="op_divide":
            self.operator = "divide"

        elif operator=="or_operator":
            self.operator = "boolean_or"

        elif operator=="and_operator":
            self.operator = "boolean_and"

        elif operator=="not_operator":
            self.operator = "boolean_not"

        else:
            raise ValueError("Cannot represent operator", (operator, args) )

        self.tag = "op"

#        self.operator = operator
        self.args = args

    def __json__(self):
        return ["operator", self.operator, self.args ]

class iiFunctionCall(iiNode):
    tag = "function_call"
    def __init__(self, func_object, args):
        self.iifunc_object = func_object
        self.iifunc_call_args = args

    def __json__(self):
        return ["function_call", self.iifunc_object, self.iifunc_call_args ]

class iiAttributeAccess(iiNode):
    tag = "attributeaccess"
    def __init__(self, expression, attribute):
        self.expression = expression
        self.attribute = attribute

    def __json__(self):
        return ["attributeaccess", self.expression, self.attribute]

class iiIdentifier(iiNode):
    tag = "identifier"
    def __init__(self, identifier):
        self.identifier = identifier

    def __json__(self):
        return ["identifier", self.identifier]

class iiString(iiNode):
    tag = "string"
    def __init__(self, the_string):
        self.the_string = the_string

    def __json__(self):
        return ["string", self.the_string]

class iiInteger(iiNode):
    tag = "integer"
    def __init__(self, the_integer):
        self.the_integer = the_integer

    def __json__(self):
        return ["integer", self.the_integer]

class iiFloat(iiNode):
    tag = "double"
    def __init__(self, the_float):
        self.the_float = the_float

    def __json__(self):
        return ["double", self.the_float]

class iiBoolean(iiNode):
    tag = "boolean"
    def __init__(self, the_boolean):
        self.the_boolean = the_boolean

    def __json__(self):
        return ["boolean", self.the_boolean]

class iiComparison(iiNode):
    tag = "op"
    def __init__(self, comparator, left, right):
        self.comparator = comparator # FIXME: Do we still need comparator? It's just a special case operator, right?
        self.operator = comparator
        self.args = [ left, right ]
        self.left = left
        self.right = right
    def __json__(self):
        return ["op", self.comparator, self.left, self.right]

class iiWhileStatement(iiNode):
    tag = "while_statement"
    def __init__(self, condition, statements):
        self.condition = condition
        self.statements = statements

    def __json__(self):
        return ["while_statement", self.condition] + self.statements

class iiIterator(iiNode):
    tag = "iterator"
    def __init__(self, expression):
        self.expression = expression

    def __json__(self):
        return ["iterator", self.expression]

class iiForStatement(iiNode):
    tag = "for_statement"
    def __init__(self, lvalue, iterator, statements, for_statement_PyNode):
        self.lvalue = lvalue
        self.iterator = iterator
        self.statements = statements
        self.for_statement_PyNode = for_statement_PyNode

    def __json__(self):
        return ["for_statement", self.lvalue, self.iterator, self.statements, self.for_statement_PyNode]

class iiDefStatement(iiNode):
    tag = "func_defintion"
    def __init__(self, name, params, block, def_statement_PyNode):
        self.name = name
        self.params = params
        self.block = block
        self.def_statement_PyNode = def_statement_PyNode

    def __json__(self):
        return ["func_defintion", self.name, self.params, self.block, repr(self.def_statement_PyNode) ]

class iiPassStatement(iiNode):
    tag = "pass_statement"
    def __init__(self):
        pass

    def __json__(self):
        return ["pass_statement"]

class iiBreakStatement(iiNode):
    tag = "break_statement"
    def __init__(self):
        pass
    def __json__(self):
        return ["break_statement"]

class iiContinueStatement(iiNode):
    tag = "continue_statement"
    def __init__(self):
        pass

    def __json__(self):
        return ["continue_statement"]

class iiExpressionStatement(iiNode):
    tag = "expression_statement"
    def __init__(self, expression):
        self.expression = expression

    def __json__(self):
        return ["expression_statement", self.expression]

class iiIdentifierDeclaration(iiNode):
    tag = "identifier"
    def __init__(self, name, value_type):
        self.value_type = value_type
        self.name = name

    def __json__(self):
        return ["identifier", self.value_type, self.name]

class iiElifClause(iiNode):
    tag = "elif_clause"
    def __init__(self, condition, statements, extended_clause=None):
        self.condition = condition
        self.statements = statements
        self.extended_clause = extended_clause

    def __json__(self):
        if self.extended_clause:
            return ["elif_clause", self.condition, self.statements, self.extended_clause]
        else:
            return ["elif_clause", self.condition, self.statements]

class iiElseClause(iiNode):
    tag = "else_clause"
    def __init__(self, statements ):
        self.statements = statements

    def __json__(self):
        return ["else_clause", self.statements]

class iiIfStatement(iiNode):
    tag = "if_statement"
    def __init__(self, condition, statements, extended_clause=None):
        self.condition = condition
        self.statements = statements
        self.extended_clause = extended_clause

    def __json__(self):
        if self.extended_clause:
            return ["if_statement", self.condition, self.statements, self.extended_clause]
        else:
            return ["if_statement", self.condition, self.statements]


text:
<module xmlns="urn:jboss:module:1.0" name="com.nerdwin15.wildfly.rewriter.wildfly-rewriter-adapter-api">
  <resources>
    <!-- Insert resources here -->
  </resources>

  <dependencies>
    <module name="org.wildfly.extension.undertow"/>
    <module name="io.undertow.core"/>
    <module name="io.undertow.servlet"/>
    <module name="org.slf4j" />
    <module name="org.jboss.msc" />
  </dependencies>
</module>


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

<title>ScanParameters (Hibernate JavaDocs)</title>
<meta name="date" content="2017-01-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.hibernate.boot.archive.scan.spi

Interface ScanParameters

All Known Implementing Classes:

StandardScanParameters

public interface ScanParameters

A "parameter object" passed to Scanner.scan(org.hibernate.boot.archive.scan.spi.ScanEnvironment, org.hibernate.boot.archive.scan.spi.ScanOptions, org.hibernate.boot.archive.scan.spi.ScanParameters) to help support future
 changes in terms of needing to pass additional stuff to scanning.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2001-2017 Red Hat, Inc.  All Rights Reserved.