text:
/**
 * @file bcm283x_spi0.c
 * @brief
 * @author kpishere
 * @version 0.1
 * @date 2021.07.16
 */
#include <errno.h>

#include <drivers/common/memory.h>
#include <drivers/spi.h>
#include <embox/unit.h>
#include <framework/mod/options.h>
#include <hal/reg.h>
#include <util/log.h>
#include <util/math.h>
#include <kernel/printk.h>
#include <asm/delay.h>
#include <assert.h>

#include <drivers/dma/pl330_dma.h>

#include <drivers/gpio/gpio.h>
#include <drivers/gpio/bcm283x/bcm283x_gpio.h>
#include <drivers/spi.h>

#include "bcm283x_spi0.h"

#define PBASE                     OPTION_GET(NUMBER,base_addr)
#define SPI_BUS_CLOCK_DIVISOR     OPTION_GET(NUMBER,spi_bus_clock_divisor)
#define SPI_INT0                  OPTION_GET(NUMBER,spi_int)

// command block must be 256 bit aligned in memory
#define MEM_ALGN_256 (0x00000020)

// Toggle an extra GPIO pin at various points to debug/test timing
#if 0
    #define DRIVER_TESTING
    #define PIN ( 1 << 25 )
#endif

/* Errata to BCM2835 behaviour: documentation states that the SPI0 DLEN register is only used for DMA.
 * However, even when DMA is not being utilized, setting it from a value != 0 or 1 gets rid of an
 * excess idle clock cycle that is present when transmitting each byte. (by default in Polled SPI
 * Mode each 8 bits transfer in 9 clocks) With DLEN=2 each byte is clocked to the bus in 8 cycles,
 * observed to improve max throughput from 56.8mbps to 63.3mbps (+11.4%, quite close to the
 * theoretical +12.5%)
 * https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=181154
 */
#define DLEN_NO_DMA_VALUE 2;

typedef struct {
    uint32_t cs; /* SPI Master Control and Status */

/* RW: DMA Mode (DMAEN set)
    If TA is clear, the first 32-bit write to this register will control
    SPIDLEN and SPICS. Subsequent reads and writes will be taken as
    four-byte data words to be read/written to the FIFOs Poll/Interrupt
    Mode (DMAEN clear, TA set) Writes to the register write bytes to TX FIFO.
    Reads from register read bytes from the RX FIFO
 */
    uint32_t fifo; /* SPI Master TX and RX FIFOs */

/* RW: 15:0 Clock Divider SCLK = Core Clock / CDIV
    If CDIV is set to 0, the divisor is 65536. The divisor must be a power of 2.
    Odd numbers rounded down. The maximum SPI clock rate is of the APB clock.
 */
    uint32_t clk; /* SPI Master Clock Divider */

/* RW: 15:0 Data Length - The number of bytes to transfer.
    This field is only valid for DMA mode (DMAEN set) and controls how many bytes
    to transmit (and therefore receive).
 */
    uint32_t dlen; /* SPI Master Data Length */

/* RW: 3:0 This sets the Output Hold delay in APB clocks. A value of 0 causes a 1 clock delay. */
    uint32_t ltoh; /* SPI LOSSI mode TOH */

/* RW: This register controls the generation of the DREQ and Panic signals to an
    external DMA engine The DREQ signals are generated when the FIFOs reach their
    defined levels and need servicing. The Panic signals instruct the external DMA engine
    to raise the priority of its AXI requests.*/
    uint32_t dc; /* SPI DMA DREQ Controls */
} Bcm283x_spi0;

#define REGS_SPI0 ((Bcm283x_spi0 *)(PBASE))
#define BCM283X_SPI0_TX_FIFO_LEN (16*sizeof(uint32_t))
#define BCM283X_SPI0_RX_FIFO_LEN (16*sizeof(uint32_t))
#define BCM283X_SPI0_TX_FIFO_FL  (4*sizeof(uint32_t))
#define BCM283X_SPI0_RX_FIFO_HW  (3*sizeof(uint32_t))

static int bcm283x_spi0_init(void) {
    uint32_t pins_spi_Alt0 =( 1 << 7 ) | ( 1 << 8 ) | ( 1 << 9 ) | ( 1 << 10 ) | ( 1 << 11 );
    gpio_setup_mode(GPIO_PORT_A, pins_spi_Alt0, GPIO_MODE_OUT_ALTERNATE | GPIO_ALTERNATE(GFAlt0) );

#ifdef DRIVER_TESTING
    gpio_setup_mode(GPIO_PORT_A, PIN, GPIO_MODE_OUTPUT);
#endif

    // Initialize the Control and Status register to defaults:
    //CS=0 (Chip Select), CPHA=0 (Clock Phase), CPOL=0 (Clock Polarity),
    //CSPOL=0 (Chip Select Polarity), TA=0 (Transfer not active), and reset TX and RX queues.
    REGS_SPI0->cs = SPI0_CS(0);
    REGS_SPI0->clk = SPI_BUS_CLOCK_DIVISOR;
    REGS_SPI0->dlen = DLEN_NO_DMA_VALUE;

    return 0;
}

irq_return_t bcm283x_spi_intrd_irq_handler(unsigned int irq_nr, void *data);

static int bcm283x_spi0_attach(struct spi_device *dev) {
    int res = 0;

    if( !(REGS_SPI0->cs & SPI0_CS_INTD) && !(REGS_SPI0->cs & SPI0_CS_INTR) ) {
        res = irq_attach(SPI_INT0, bcm283x_spi_intrd_irq_handler, 0x00, dev, "SPI0 IRQ");
    }
    return res;
}

static int bcm283x_spi0_select(struct spi_device *dev, int cs) {
    int res = 0;
    if (cs < 0 || cs > 3) {
        log_error("Only cs=0..3 are avalable!");
        return -EINVAL;
    }
    if( dev->flags & SPI_CS_ACTIVE ) {
    }
    if( dev->flags & SPI_CS_INACTIVE ) {
    }

    // If flag set for either interrupt option, register interrupt function
    if( dev->flags & SPI_CS_IRQD ) {
        res = bcm283x_spi0_attach(dev);
        REGS_SPI0->cs |= SPI0_CS_INTD;
    }
    if( dev->flags & SPI_CS_IRQR ) {
        res = bcm283x_spi0_attach(dev);
        REGS_SPI0->cs |= SPI0_CS_INTR;
    }
    // If no flags set for interrupt, detatch interrupt
    if( !(dev->flags & SPI_CS_IRQR) && !(dev->flags & SPI_CS_IRQD)
        && irq_nr_valid(SPI_INT0) == 0 ) {
        res = irq_detach(SPI_INT0, dev);
    }

    // Enable DMA
    if( dev->flags & SPI_CS_DMAEN
        && !(REGS_SPI0->cs & SPI0_CS_DMAEN) ) {
        assert( dev->dma_chan_out != dev->dma_chan_in );

        REGS_SPI0->cs |= SPI0_CS_DMAEN;
        REGS_SPI0->dc = dev->dma_levels;

        /* Set Panic and Priority levels at High 2/3rds and then Low 1/3rd respectively
         * If they are not set, DMA_LEVELS() must be about double higher.
         */
        dma_config_extended(dev->dma_chan_in, NULL, DMA_CS_PANIC_PRIORITY(0x0C) | DMA_CS_PRIORITY(0x06) );
        // Channel out receives data from SPI fifo to memory in
        dma_config_extended(dev->dma_chan_out, dev->dma_complete, DMA_CS_PANIC_PRIORITY(0x0C) | DMA_CS_PRIORITY(0x06));
    }

    // If no flags set for interrupt, cause interrupt to detatch
    if( !(dev->flags & SPI_CS_DMAEN) && (REGS_SPI0->cs & SPI0_CS_DMAEN) ) {
        dma_config_extended(dev->dma_chan_out, NULL, 0x00);
        REGS_SPI0->cs &= ~( SPI0_CS_DMAEN );
    }

    // set default CPHA=0 (Clock Phase), CPOL=0 (Clock Polarity)
    REGS_SPI0->cs &= ~(SPI0_CS_CPOL | SPI0_CS_CPHA);
    if(dev->flags & SPI_CS_MODE(SPI_MODE_1)) REGS_SPI0->cs |= SPI0_CS_CPHA;
    if(dev->flags & SPI_CS_MODE(SPI_MODE_2)) REGS_SPI0->cs |= SPI0_CS_CPOL;

    // A clock divisor value is set
    if( (dev->flags >> 16) ) {
        REGS_SPI0->clk = (dev->flags >> 16);
    }

    // Set the CS lines
    REGS_SPI0->cs &= ~SPI0_CS(0xFF);
    REGS_SPI0->cs |= SPI0_CS(cs);

    // Set the CS hold delay
    REGS_SPI0->ltoh = 0;
    return res;
}

static int bcm283x_spi0_do_transfer(struct spi_device *dev, uint8_t *inbuf
        , uint8_t *outbuf, int tx_count, int rx_count) {
    int tx_cnt, rx_cnt;

    irq_lock();
    tx_cnt = rx_cnt = 0;
    /* Do not add log_debug() or some another stuff here, */
    while ( ( tx_cnt < tx_count && inbuf != NULL )
        ||  (rx_cnt < rx_count && outbuf != NULL ) ) {
        if(tx_cnt < tx_count ) {
            if( inbuf != NULL ) {
                // Wait for FIFO to have 1-byte space
                while( !(REGS_SPI0->cs & SPI0_CS_TXD) ) {
#ifdef DRIVER_TESTING
                    gpio_set(GPIO_PORT_A, PIN, GPIO_PIN_HIGH );
                    gpio_set(GPIO_PORT_A, PIN, GPIO_PIN_LOW );
#endif
                };
                REGS_SPI0->fifo = inbuf[tx_cnt++];
            } else {
                // write without waiting for buffer ready
                REGS_SPI0->fifo = 0x00;
            }
        }
        if( rx_cnt < rx_count && outbuf != NULL ) {
            while ( !(REGS_SPI0->cs & SPI0_CS_RXD) ); // Wait for rx byte
            outbuf[rx_cnt++] = REGS_SPI0->fifo;
        }
    }
    // read out FIFO incoming buffer
    while( REGS_SPI0->cs & SPI0_CS_RXD ) {
        uint32_t discard;
        discard += REGS_SPI0->fifo;
    }
    // Wait for tx to complete
    while( !(REGS_SPI0->cs & SPI0_CS_DONE) ) {
#ifdef DRIVER_TESTING
        gpio_set(GPIO_PORT_A, PIN, GPIO_PIN_HIGH );
        gpio_set(GPIO_PORT_A, PIN, GPIO_PIN_LOW );
#endif
    };
    irq_unlock();

    return max(tx_cnt, rx_cnt);
}

// Interrupt for data send required or complete
irq_return_t bcm283x_spi_intrd_irq_handler(unsigned int irq_nr, void *data) {
    irq_return_t ret = IRQ_HANDLED;
    struct spi_device *dev = (struct spi_device *)data;

    // Transmit and receive with CS asserted
    if( (REGS_SPI0->cs & (SPI0_CS_DONE | SPI0_CS_TA)) && dev->count > 0 ) {
        dev->count -= bcm283x_spi0_do_transfer(dev, dev->in, dev->out, min(BCM283X_SPI0_TX_FIFO_FL,dev->count)
            , min(BCM283X_SPI0_TX_FIFO_FL,dev->count));
        if(dev->count <= 0) REGS_SPI0->cs &= ~SPI0_CS_TA; // De-assert
        if(dev->send_complete && dev->count <= 0 ) dev->send_complete(dev);
    }

    // Receive with CS un-asserted
    if( (REGS_SPI0->cs & SPI0_CS_RXR) ) {
        dev->count = bcm283x_spi0_do_transfer(dev, dev->in, dev->out, min(BCM283X_SPI0_RX_FIFO_HW,dev->count)
            , min(BCM283X_SPI0_RX_FIFO_HW,dev->count));
        if(dev->received_data && dev->count > 0 ) dev->send_complete(dev);
    }
    return ret;
}

Dma_conbk *bcm283x_init_dma_block_spi_in(struct spi_device *dev, Dma_mem_handle *mem_handle
, uint32_t offset, void *src, uint32_t bytes, Dma_conbk *next_conbk, bool int_enable) {
    assert( (((uint32_t)(mem_handle->physical_addr) + offset) & ~MEM_ALGN_256 ) == ((uint32_t)(mem_handle->physical_addr) + offset));

    Dma_conbk *cbp = (Dma_conbk *)(mem_handle->physical_addr + offset);
    cbp->ti = DMA_TI_PERMAP(DMA_PERMAP_SPI_TX) | DMA_TI_SRC_INC | DMA_TI_DEST_DREQ | DMA_TI_WAIT_RESP;
    cbp->dest_ad = (uint32_t)DMA_PERF_TO_BUS((uint32_t)&(REGS_SPI0->fifo));
    cbp->stride = 0x0;

    cbp->source_ad = (uint32_t)DMA_PHYS_TO_BUS((uint32_t)src);
    cbp->txfr_len = bytes;
    cbp->nextconbk = ( next_conbk == NULL ? 0x00 : (uint32_t)DMA_PHYS_TO_BUS((uint32_t)next_conbk) );

    if(int_enable) cbp->ti |= DMA_TI_INTEN;
    else cbp->ti &= ~DMA_TI_INTEN;

    return cbp;
}

Dma_conbk *bcm283x_init_dma_block_spi_out(struct spi_device *dev, Dma_mem_handle *mem_handle, uint32_t offset
, void *dest, uint32_t bytes, Dma_conbk *next_conbk, bool int_enable) {
    assert( (((uint32_t)(mem_handle->physical_addr) + offset) & ~MEM_ALGN_256 ) == ((uint32_t)(mem_handle->physical_addr) + offset));

    Dma_conbk *cbp = (Dma_conbk *)(mem_handle->physical_addr + offset);
    cbp->ti = DMA_TI_PERMAP(DMA_PERMAP_SPI_RX) | DMA_TI_DEST_INC | DMA_TI_SRC_DREQ | DMA_TI_WAIT_RESP;
    cbp->source_ad = (uint32_t)DMA_PERF_TO_BUS((uint32_t)&(REGS_SPI0->fifo));
    cbp->stride = 0x0;

    cbp->dest_ad = (uint32_t)DMA_PHYS_TO_BUS((uint32_t)dest);
    cbp->txfr_len = bytes;
    cbp->nextconbk = ( next_conbk == NULL ? 0x00 : (uint32_t)DMA_PHYS_TO_BUS((uint32_t)next_conbk) );

    if(int_enable) cbp->ti |= DMA_TI_INTEN;
    else cbp->ti &= ~DMA_TI_INTEN;

    return cbp;
}

/*
    // Hi 16 bits are length, lower 8 bits are the lower 8 bits of SPI control register
 *
 * For SPI Device: txfr_len is in top sixteen bits and control register settings are in [7:0]
 * (the bottom eight bits) for TA = 1, CS, CPOL, CPHA
*/

static int bcm283x_spi0_transfer(struct spi_device *dev, uint8_t *inbuf
        , uint8_t *outbuf, int count) {

    // Interrupt mode
    if( ( (REGS_SPI0->cs & SPI0_CS_INTD) || (REGS_SPI0->cs & SPI0_CS_INTR) ) ) {
        if(count < 0) {
            // count < 0 is signal to trigger interrupt and return
            dev->count = -1 * count;    /* set the target amount to output in series of interrupt transfers */
            dev->in = inbuf;
            dev->out = outbuf;
            REGS_SPI0->dlen = DLEN_NO_DMA_VALUE;
            REGS_SPI0->cs |= SPI0_CS_CLEAR( SPI0_tx_fifo | SPI0_rx_fifo ) | SPI0_CS_TA; // clear FIFO and Assert
            return 0;
        } else {
            // called in interrupt handler to send/receive data
            dev->count -= bcm283x_spi0_do_transfer(dev, inbuf, outbuf, min(BCM283X_SPI0_TX_FIFO_FL,count), BCM283X_SPI0_RX_FIFO_HW);
            REGS_SPI0->cs &= ~SPI0_CS_TA; // De-assert
            return 0;
        }
    }

    // DMA Mode
    if(REGS_SPI0->cs & SPI0_CS_DMAEN) {
        REGS_SPI0->dlen = count;

        // Receive - start dma transfer
        dma_transfer_conbk(dev->dma_chan_out, (volatile Dma_conbk *)outbuf);
        // Transmit - start dma transfer
        dma_transfer_conbk(dev->dma_chan_in, (volatile Dma_conbk *)inbuf);
        // Activate SPI
        REGS_SPI0->cs |= SPI0_CS_ADCS | SPI0_CS_CLEAR( SPI0_tx_fifo | SPI0_rx_fifo ) | SPI0_CS_TA; // clear FIFO and Assert
    } else {
        // Poll mode - bytes send, bytes receive
        REGS_SPI0->cs |= SPI0_CS_CLEAR( SPI0_tx_fifo | SPI0_rx_fifo ) | SPI0_CS_TA; // clear FIFO and Assert

        /* because we need to write all tx data before transfer competed. */
        REGS_SPI0->dlen = DLEN_NO_DMA_VALUE;

        bcm283x_spi0_do_transfer(dev, inbuf, outbuf, count, count);
        REGS_SPI0->cs &= ~SPI0_CS_TA; // De-assert
    }
    return 0;
}

struct spi_ops bcm283x_spi0_ops = {
    .select   = bcm283x_spi0_select,
    .transfer = bcm283x_spi0_transfer,
    .init_dma_block_spi_in = bcm283x_init_dma_block_spi_in,
    .init_dma_block_spi_out = bcm283x_init_dma_block_spi_out
};

PERIPH_MEMORY_DEFINE(bcm283x_spi0, PBASE, sizeof(Bcm283x_spi0));

SPI_DEV_DEF("spi0", &bcm283x_spi0_ops, REGS_SPI0, 0);

EMBOX_UNIT_INIT(bcm283x_spi0_init);


text:
'use strict';

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx Preprocessor
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2013 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Lucas Dohmen
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var extend = require("underscore").extend,
  coffeeScript = require("coffee-script");

function ArrayIterator(arr) {
  this.array = arr;
  this.currentLineNumber = -1;
}

extend(ArrayIterator.prototype, {
  next: function () {
      this.currentLineNumber += 1;
    return this.array[this.currentLineNumber];
  },

  current: function () {
      return this.array[this.currentLineNumber];
  },

  hasNext: function () {
      return this.currentLineNumber < (this.array.length - 1);
  },

  replaceWith: function (newLine) {
      this.array[this.currentLineNumber] = newLine;
  },

  entireString: function () {
      return this.array.join("\n");
  },

  getCurrentLineNumber: function () {
      if (this.hasNext()) {
      return this.currentLineNumber;
    }
  }
});

function Preprocessor(input, type) {
  if (type === 'coffee') {
    input = coffeeScript.compile(input, {bare: true});
  }

  this.iterator = new ArrayIterator(input.replace('\r', '').split("\n"));
  this.inJSDoc = false;
}

extend(Preprocessor.prototype, {
  result: function () {
      return this.iterator.entireString();
  },

  convert: function () {
      while (this.searchNext()) {
      this.convertLine();
    }
    return this;
  },

  searchNext: function () {
      while (this.iterator.hasNext()) {
      if (this.isJSDoc(this.iterator.next())) {
        return true;
      }
    }
  },

  convertLine: function () {
      this.iterator.replaceWith(
      "applicationContext.comment(\"" + this.stripComment(this.iterator.current()) + "\");"
    );
  },

  getCurrentLineNumber: function () {
      return this.iterator.getCurrentLineNumber();
  },

  // helper

  stripComment: function (str) {
      return str.replace(/^\s*\/\*\*/, '').       // start of JSDoc comment
               replace(/^(.*?)\*\/.*$/, '$1').  // end of JSDoc comment
               replace(/^\s*\*/, '').           // continuation of JSDoc comment
               replace(/\\/g, '\\\\').          // replace backslashes
               replace(/"/g, '\\"').            // replace quotes
               trim();                          // remove leading and trailing spaces
  },

  isJSDoc: function (str) {
      var matched;

    if (this.inJSDoc) {
      if (str.match(/\*\//)) {
        // end of multi-line JSDoc comment
        this.inJSDoc = false;
      }
      matched = true;
    } else {
      if (str.match(/^\s*\/\*\*(.*?\*)?\//)) {
        // a single-line JSDoc comment
        matched = true;
      }
      else if (str.match(/^\s*\/\*\*/)) {
        // beginning of a multi-line JSDoc comment
        matched = true;
        this.inJSDoc = true;
      }
    }

    return matched;
  }
});

function preprocess(input, type) {
  var processor = new Preprocessor(input, type);
  return processor.convert().result();
}

// Only Exported for Tests, please use `process`
exports.Preprocessor = Preprocessor;

// process(str) returns the processed String
exports.preprocess = preprocess;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

/// Local Variables:
/// mode: outline-minor
/// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
/// End:

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import socket
import signal
import struct
import thread
from cStringIO import StringIO
from traceback import print_exc, print_stack

from BitTorrent import BTFailure, WARNING, CRITICAL, FAQ_URL

noSignals = True

if os.name == 'nt':
    try:
        from twisted.internet import iocpreactor
        iocpreactor.proactor.install()
        noSignals = False
    except:
        # just as limited (if not more) as select, and also (supposedly) buggy
        #try:
        #    from twisted.internet import win32eventreactor
        #    win32eventreactor.install()
        #except:
        #    pass
        pass
else:
    try:
        from twisted.internet import kqreactor
        kqreactor.install()
    except:
        try:
            from twisted.internet import pollreactor
            pollreactor.install()
        except:
            pass

#the default reactor is select-based, and will be install()ed if another has not
from twisted.internet import reactor, task, error

import twisted.copyright
if int(twisted.copyright.version.split('.')[0]) < 2:
    raise ImportError("RawServer_twisted requires twisted 2.0.0 or greater")

from twisted.internet.protocol import DatagramProtocol, Protocol, Factory, ClientFactory
from twisted.protocols.policies import TimeoutMixin

NOLINGER = struct.pack('ii', 1, 0)

class Handler(object):

    # there is only a semantic difference between "made" and "started".
    # I prefer "started"
    def connection_started(self, s):
        self.connection_made(s)
    def connection_made(self, s):
        pass

    def connection_lost(self, s):
        pass

    # Maybe connection_lost should just have a default 'None' exception parameter
    def connection_failed(self, addr, exception):
        pass

    def connection_flushed(self, s):
        pass
    def data_came_in(self, addr, datagram):
        pass

class ConnectionWrapper(object):
    def __init__(self, rawserver, handler, context, tos=0):
        self.dying = 0
        self.ip = None
        self.port = None
        self.transport = None
        self.reset_timeout = None

        self.post_init(rawserver, handler, context)

        self.tos = tos

        self.buffer = OutputBuffer(self)

    def post_init(self, rawserver, handler, context):
        self.rawserver = rawserver
        self.handler = handler
        self.context = context
        if self.rawserver:
            self.rawserver.single_sockets[self] = self

    def get_socket(self):
        s = None
        try:
            s = self.transport.getHandle()
        except:
            try:
                # iocpreactor doesn't implement ISystemHandle like it should
                s = self.transport.socket
            except:
                pass
        return s

    def attach_transport(self, transport, reset_timeout):
        self.transport = transport
        self.reset_timeout = reset_timeout

        try:
            address = self.transport.getPeer()
        except:
            try:
                # udp, for example
                address = self.transport.getHost()
            except:
                if not self.transport.__dict__.has_key("state"):
                    self.transport.state = "NO STATE!"
                sys.stderr.write("UNKNOWN HOST/PEER: " + str(self.transport) + ":" + str(self.transport.state)+ ":" + str(self.handler) + "\n")
                print_stack()
                # fallback incase the unknown happens,
                # there's no use raising an exception
                address = ("unknown", -1)
                pass

        try:
            self.ip = address.host
            self.port = address.port
        except:
            #unix sockets, for example
            pass

        if self.tos != 0:
            s = self.get_socket()

            try:
                s.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, self.tos)
            except:
                pass

    def sendto(self, packet, flags, addr):
        # all this can go away once we pin down the bug
        if not hasattr(self.transport, "listening"):
            self.rawserver.errorfunc(WARNING, "UDP port never setup properly when asked to write")
        elif not self.transport.listening:
            self.rawserver.errorfunc(WARNING, "UDP port cleaned up already when asked to write")

        ret = None
        try:
            ret = self.transport.write(packet, addr)
        except Exception, e:
            self.rawserver.errorfunc(WARNING, "UDP sendto failed: %s" % str(e))

        return ret

    def write(self, b):
        self.buffer.add(b)

    def _flushed(self):
        s = self
        #why do you tease me so?
        if s.handler is not None:
            #calling flushed from the write is bad form
            self.rawserver.add_task(s.handler.connection_flushed, 0, (s,))

    def is_flushed(self):
        return self.buffer.is_flushed()

    def shutdown(self, how):
        if how == socket.SHUT_WR:
            self.transport.loseWriteConnection()
            self.buffer.stopWriting()
        elif how == socket.SHUT_RD:
            self.transport.stopListening()
        else:
            self.close()

    def close(self):
        self.buffer.stopWriting()

        # opt for no "connection_lost" callback since we know that
        self.dying = 1

        if self.rawserver.config['close_with_rst']:
            try:
                s = self.get_socket()
                s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, NOLINGER)
            except:
                pass

        if self.rawserver.udp_sockets.has_key(self):
            # udp connections should only call stopListening
            self.transport.stopListening()
        else:
            self.transport.loseConnection()

class OutputBuffer(object):

    def __init__(self, connection):
        self.connection = connection
        self.consumer = None
        self.buffer = StringIO()

    def is_flushed(self):
        return (self.buffer.tell() == 0)

    def add(self, b):
        # sometimes we get strings, sometimes we get buffers. ugg.
        if (isinstance(b, buffer)):
            b = str(b)
        self.buffer.write(b)

        if self.consumer is None:
            self.beginWriting()

    def beginWriting(self):
        self.stopWriting()
        self.consumer = self.connection.transport
        self.consumer.registerProducer(self, False)

    def stopWriting(self):
        if self.consumer is not None:
            self.consumer.unregisterProducer()
        self.consumer = None

    def resumeProducing(self):
        if self.consumer is not None:
            if self.buffer.tell() > 0:
                self.consumer.write(self.buffer.getvalue())
                self.buffer.seek(0)
                self.buffer.truncate(0)
                self.connection._flushed()
            else:
                self.stopWriting()

    def pauseProducing(self):
        pass

    def stopProducing(self):
        pass

class CallbackConnection(object):

    def attachTransport(self, transport, connection, *args):
        s = connection
        if s is None:
            s = ConnectionWrapper(*args)

        s.attach_transport(transport, self.optionalResetTimeout)
        self.connection = s

    def connectionMade(self):
        s = self.connection
        s.handler.connection_started(s)
        self.optionalResetTimeout()

    def connectionLost(self, reason):
        reactor.callLater(0, self.post_connectionLost, reason)

    #twisted api inconsistancy workaround
    #sometimes connectionLost is called (not fired) from inside write()
    def post_connectionLost(self, reason):
        #hack to try and dig up the connection if one was ever made
        if not self.__dict__.has_key("connection"):
            self.connection = self.factory.connection
        if self.connection is not None:
            self.factory.rawserver._remove_socket(self.connection)

    def dataReceived(self, data):
        self.optionalResetTimeout()

        s = self.connection
        s.rawserver._make_wrapped_call(s.handler.data_came_in,
                                       (s, data), s)

    def datagramReceived(self, data, (host, port)):
        s = self.connection
        s.rawserver._make_wrapped_call(s.handler.data_came_in,
                                       ((host, port), data), s)

    def connectionRefused(self):
        s = self.connection
        dns = (s.ip, s.port)
        reason = "connection refused"

        if not s.dying:
            # this might not work - reason is not an exception
            s.handler.connection_failed(dns, reason)

            #so we don't get failed then closed
            s.dying = 1

        s.rawserver._remove_socket(s)

    def optionalResetTimeout(self):
        if self.can_timeout:
            self.resetTimeout()

class CallbackProtocol(CallbackConnection, TimeoutMixin, Protocol):

    def makeConnection(self, transport):
        self.can_timeout = 1
        self.setTimeout(self.factory.rawserver.config['socket_timeout'])
        self.attachTransport(transport, self.factory.connection, *self.factory.connection_args)
        Protocol.makeConnection(self, transport)

class CallbackDatagramProtocol(CallbackConnection, DatagramProtocol):

    def startProtocol(self):
        self.can_timeout = 0
        self.attachTransport(self.transport, self.connection, ())
        DatagramProtocol.startProtocol(self)

    def connectionRefused(self):
        # we don't use these at all for udp, so skip the CallbackConnection
        DatagramProtocol.connectionRefused(self)

class OutgoingConnectionFactory(ClientFactory):

    def clientConnectionFailed(self, connector, reason):
        peer = connector.getDestination()
        dns = (peer.host, peer.port)
        # opt-out
        if not self.connection.dying:
            # this might not work - reason is not an exception
            self.connection.handler.connection_failed(dns, reason)

            #so we don't get failed then closed
            self.connection.dying = 1

        self.rawserver._remove_socket(self.connection)

def UnimplementedWarning(msg):
    #ok, I think people get the message
    #print "UnimplementedWarning: " + str(msg)
    pass

#Encoder calls stop_listening(socket) then socket.close()
#to us they mean the same thing, so swallow the second call
class CloseSwallower:
    def close(self):
        pass

#storage for socket creation requestions, and proxy once the connection is made
class SocketProxy(object):
    def __init__(self, port, bind, reuse, tos, protocol):
        self.port = port
        self.bind = bind
        self.reuse = reuse
        self.tos = tos
        self.protocol = protocol
        self.connection = None

    def __getattr__(self, name):
        try:
            return getattr(self.connection, name)
        except:
            raise AttributeError, name

def default_error_handler(level, message):
    print message

class RawServerMixin(object):

    def __init__(self, doneflag, config, noisy=True,
                 errorfunc=default_error_handler, tos=0):
        self.doneflag = doneflag
        self.noisy = noisy
        self.errorfunc = errorfunc
        self.config = config
        self.tos = tos
        self.ident = thread.get_ident()

    def _make_wrapped_call(self, function, args, wrapper=None, context=None):
        try:
            function(*args)
        except KeyboardInterrupt:
            raise
        except Exception, e:         # hopefully nothing raises strings
            # Incoming sockets can be assigned to a particular torrent during
            # a data_came_in call, and it's possible (though not likely) that
            # there could be a torrent-specific exception during the same call.
            # Therefore read the context after the call.
            if wrapper is not None:
                context = wrapper.context
            if self.noisy and context is None:
                data = StringIO()
                print_exc(file=data)
                data.seek(-1)
                self.errorfunc(CRITICAL, data.read())
            if context is not None:
                context.got_exception(e)

    # must be called from the main thread
    def install_sigint_handler(self):
        signal.signal(signal.SIGINT, self._handler)

    def _handler(self, signum, frame):
        self.external_add_task(self.doneflag.set, 0)
        # Allow pressing ctrl-c multiple times to raise KeyboardInterrupt,
        # in case the program is in an infinite loop
        signal.signal(signal.SIGINT, signal.default_int_handler)

class RawServer(RawServerMixin):

    def __init__(self, doneflag, config, noisy=True,
                 errorfunc=default_error_handler, tos=0):
        RawServerMixin.__init__(self, doneflag, config, noisy, errorfunc, tos)

        self.listening_handlers = {}
        self.single_sockets = {}
        self.udp_sockets = {}
        self.live_contexts = {None : 1}
        self.listened = 0

    def add_context(self, context):
        self.live_contexts[context] = 1

    def remove_context(self, context):
        del self.live_contexts[context]

    def autoprune(self, f, *a, **kw):
        if self.live_contexts.has_key(kw['context']):
            f(*a, **kw)

    def add_task(self, func, delay, args=(), context=None):
        assert thread.get_ident() == self.ident
        assert type(args) == list or type(args) == tuple

        #we're going to check again later anyway
        #if self.live_contexts.has_key(context):
        reactor.callLater(delay, self.autoprune, self._make_wrapped_call,
                          func, args, context=context)

    def external_add_task(self, func, delay, args=(), context=None):
        assert type(args) == list or type(args) == tuple
        reactor.callFromThread(self.add_task, func, delay, args, context)

    def create_unixserversocket(filename):
        s = SocketProxy(0, filename, True, 0, 'tcp')
        s.factory = Factory()

        if s.reuse == False:
            UnimplementedWarning("You asked for reuse to be off when binding. Sorry, I can't do that.")

        listening_port = reactor.listenUNIX(s.bind, s.factory)
        listening_port.listening = 1
        s.listening_port = listening_port

        return s
    create_unixserversocket = staticmethod(create_unixserversocket)

    def create_serversocket(port, bind='', reuse=False, tos=0):
        s = SocketProxy(port, bind, reuse, tos, 'tcp')
        s.factory = Factory()

        if s.reuse == False:
            UnimplementedWarning("You asked for reuse to be off when binding. Sorry, I can't do that.")

        try:
            listening_port = reactor.listenTCP(s.port, s.factory, interface=s.bind)
        except error.CannotListenError, e:
            if e[0] != 0:
                raise e.socketError
            else:
                raise
        listening_port.listening = 1
        s.listening_port = listening_port

        return s
    create_serversocket = staticmethod(create_serversocket)

    def create_udpsocket(port, bind='', reuse=False, tos=0):
        s = SocketProxy(port, bind, reuse, tos, 'udp')
        s.protocol = CallbackDatagramProtocol()
        c = ConnectionWrapper(None, None, None, tos)
        s.connection = c
        s.protocol.connection = c

        if s.reuse == False:
            UnimplementedWarning("You asked for reuse to be off when binding. Sorry, I can't do that.")

        try:
            listening_port = reactor.listenUDP(s.port, s.protocol, interface=s.bind)
        except error.CannotListenError, e:
            raise e.socketError
        listening_port.listening = 1
        s.listening_port = listening_port

        return s
    create_udpsocket = staticmethod(create_udpsocket)

    def start_listening(self, serversocket, handler, context=None):
        s = serversocket
        s.factory.rawserver = self
        s.factory.protocol = CallbackProtocol
        s.factory.connection = None
        s.factory.connection_args = (self, handler, context, serversocket.tos)

        if not s.listening_port.listening:
            s.listening_port.startListening()
            s.listening_port.listening = 1

        self.listening_handlers[s] = s.listening_port

        #provides a harmless close() method
        s.connection = CloseSwallower()

    def start_listening_udp(self, serversocket, handler, context=None):
        s = serversocket

        c = s.connection
        c.post_init(self, handler, context)

        if not s.listening_port.listening:
            s.listening_port.startListening()
            s.listening_port.listening = 1

        self.listening_handlers[serversocket] = s.listening_port

        self.udp_sockets[c] = c

    def stop_listening(self, serversocket):
        listening_port = self.listening_handlers[serversocket]
        try:
            listening_port.stopListening()
            listening_port.listening = 0
        except error.NotListeningError:
            pass
        del self.listening_handlers[serversocket]

    def stop_listening_udp(self, serversocket):
        listening_port = self.listening_handlers[serversocket]
        listening_port.stopListening()
        del self.listening_handlers[serversocket]
        del self.udp_sockets[serversocket.connection]
        del self.single_sockets[serversocket.connection]

    def start_connection(self, dns, handler, context=None, do_bind=True):
        addr = dns[0]
        port = int(dns[1])

        bindaddr = None
        if do_bind:
            bindaddr = self.config['bind']
            if bindaddr and len(bindaddr) >= 0:
                bindaddr = (bindaddr, 0)
            else:
                bindaddr = None

        factory = OutgoingConnectionFactory()
        factory.protocol = CallbackProtocol
        factory.rawserver = self

        c = ConnectionWrapper(self, handler, context, self.tos)

        factory.connection = c
        factory.connection_args = ()

        connector = reactor.connectTCP(addr, port, factory, bindAddress=bindaddr)

        self.single_sockets[c] = c
        return c

    def async_start_connection(self, dns, handler, context=None, do_bind=True):
        self.start_connection(dns, handler, context, do_bind)

    def wrap_socket(self, sock, handler, context=None, ip=None):
        raise Unimplemented("wrap_socket")

    def listen_forever(self):
        self.ident = thread.get_ident()
        if self.listened:
            UnimplementedWarning("listen_forever() should only be called once per reactor.")
        self.listened = 1

        l = task.LoopingCall(self.stop)
        l.start(1, now = False)

        if noSignals:
            reactor.run(installSignalHandlers=False)
        else:
            reactor.run()

    def listen_once(self, period=1e9):
        UnimplementedWarning("listen_once() Might not return until there is activity, and might not process the event you want. Use listen_forever().")
        reactor.iterate(period)

    def stop(self):
        if (self.doneflag.isSet()):

            for connection in self.single_sockets.values():
                try:
                    #I think this still sends all the data
                    connection.close()
                except:
                    pass

            reactor.suggestThreadPoolSize(0)
            reactor.stop()

    def _remove_socket(self, s):
        # opt-out
        if not s.dying:
            self._make_wrapped_call(s.handler.connection_lost, (s,), s)
            s.handler = None

        del self.single_sockets[s]


text:
title: OneNote
inshort: Prise dans le navigateur [Evernote]
translator: Microsoft Cognitive Services
---

OneNote Online est une version basée sur un navigateur de OneNote, Microsoft
qualité commerciale app de prise de notes OneNote Online est un \"lite\ » version
de l'application de bureau à part entière et propose des horaires d'ouverture rapides pour
lecture et l'édition des fichiers .one portable. OneNote Online est idéal pour les
prendre des notes centralisés organisé par pages, sections et livres, comme
Comment carnets d'ouvrage.

La plupart des fichiers OneNote seront ouvrira directement dans OneNote Online lors de l'utilisation
SharePoint Online, OneDrive pour les entreprises, équipes de MS, Yammer, perspectives, et
certaines autres applications Office 365. Fichiers ouverts en mode lecture. Pour modifier la
fichiers, cliquez simplement sur le \"Edit Notebook\ » bouton et choisissez de modifier la
fichier dans OneNote Online (directement dans le navigateur) ou OneNote (sur le Bureau
App).

Fonctionnalité dans OneNote Online est généralement limitée aux quotidiens
prise de notes, tables de mise en forme, simple du texte, des liens hypertexte, la page et
change de section, mais il offre un excellent support pour
[la co-création](http://icsh.pt/CoAuthoring) (édition en simultané
plusieurs utilisateurs). Toutes les modifications apportées dans OneNote Online sont enregistrées
automatiquement ; Il n'y a aucun enregistrement bouton.

Originel voudrez éviter des tâches plus complexes comme l'encre, les formes, les audio et
vidéo d'enregistrement et en insérant des symboles (entre autres) dans OneNote Online.

Si OneNote Online doesn\ ' t fournissent les fonctionnalités, vous devez faire le travail,
Cliquez simplement sur le \"Edit en OneNote\ » bouton dans la barre de menu pour accéder à
la version de bureau de l'application et ses fonctionnalités plus complexes.

Ressources
---------

-[Différences de fonctionnalités entre OneNote et OneNote
    En ligne](https://support.office.com/en-us/article/Differences-between-using-a-notebook-in-the-browser-and-in-OneNote-a3d1fc13-ac74-456b-b391-b633a62aa83f)
    \[Microsoft\]

Applications similaires
--------------------

-Evernote

-Google feuilles

-Microsoft Word Notebook Layout (MacOS uniquement)

Vos commentaires
---------

-[OneNote en ligne UserVoice](https://onenote.uservoice.com/forums/327183-onenote-online)
    \[UserVoice\]

Auteur
---------

-[Matt Wade](https://www.linkedin.com/in/thatmattwade/), bureau Services MVP


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

namespace IflySdk.Enum
{
    public enum ServiceStatus
    {
        Running,
        Stopping,
        Stopped,
    }
}


text:
<?php

class Core_Form_ServiceItem_Edit extends Core_Form_ServiceItem_Create
{
    protected $_serviceProductModel;

    protected $_serviceProductId;

    public function __construct($_serviceProductModel)
    {
        $this->_serviceProductModel = $_serviceProductModel;
        $this->_serviceProductId =
                            $this->_serviceProductModel->getServiceProductId();
        parent::__construct();
    }

    /*
     * @return Zend_Form
     */
    public function init()
    {
        parent::init();
        $defaultValues = $this->_serviceProductModel->fetch();
        $this->populate($defaultValues);
    }
}


text:
INSERT INTO spaces (created_at, updated_at, id, name, description) VALUES (now(),now(), '{{index . 0}}','{{index . 1}}','{{index . 2}}');
ALTER TABLE work_item_link_types ADD space_id uuid DEFAULT '{{index . 0}}' NOT NULL;
-- Once we set the values to the default. We drop this default constraint
ALTER TABLE work_item_link_types ALTER space_id DROP DEFAULT;

ALTER TABLE work_item_link_types ADD FOREIGN KEY (space_id) REFERENCES spaces(id) ON DELETE CASCADE;

-- Create indexes
CREATE INDEX ix_space_id ON work_item_link_types USING btree (space_id);


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import queryString from 'query-string';
import get from 'lodash/get';
// TODO: remove use of humps when refactoring
import { camelizeKeys as camelizeKeysDeep } from 'humps';
import Loader from 'react-loader';

import CheckedProgressSteps from '../../shared/progress-steps/CheckedProgressSteps';
import injectT from '../../i18n/injectT';
import PageWrapper from '../PageWrapper';
import apiClient from '../../../src/common/api/client';
import PaymentFailed from './PaymentFailed';
import PaymentSuccess from './PaymentSuccess';

const stepIds = [
  'ReservationPhase.informationTitle',
  'ReservationPhase.paymentTitle',
  'ReservationPhase.confirmationTitle',
];

const loadReservation = id => apiClient.get(`reservation/${id}`).then(({ data }) => camelizeKeysDeep(data));
const loadResource = id => apiClient.get(`resource/${id}`).then(({ data }) => camelizeKeysDeep(data));

class ReservationPaymentReturnPage extends Component {
  state = {
    isLoading: true,
    reservation: null,
    resource: null,
  };

  componentDidMount() {
    this.loadData();
  }

  loadData = () => {
    const reservationId = this.getQueryParam('reservation_id');
    const reservationPromise = loadReservation(reservationId);
    const resourcePromise = reservationPromise.then(r => loadResource(r.resource));
    Promise.all([reservationPromise, resourcePromise])
      .then(([reservation, resource]) => {
        this.setState({
          reservation,
          resource,
          isLoading: false,
        });
      })
      .catch(() => this.setState({ isLoading: false }));
  };

  getQueryParam = (paramName) => {
    const { location } = this.props;
    const params = queryString.parse(location.search);
    const param = get(params, paramName);
    return param;
  };

  render() {
    const { t } = this.props;
    const {
      reservation,
      resource,
      isLoading,
    } = this.state;
    const status = this.getQueryParam('payment_status');
    const title = t('ReservationPage.newReservationTitle');
    const steps = stepIds.map(msgId => t(msgId));
    const completedSteps = status === 'success' ? steps : [t('ReservationPhase.informationTitle')];
    return (
      <PageWrapper title={title} transparent>

              {title}

            <CheckedProgressSteps
              className="app-ReservationFailedPage__progress-steps"
              completedSteps={completedSteps}
              steps={steps}
            />
            <Loader loaded={!isLoading}>
              {status === 'success' && (
                <PaymentSuccess reservation={reservation} resource={resource} />
              )}
              {status === 'failure' && <PaymentFailed resourceId={resource ? resource.id : ''} />}
            </Loader>

      </PageWrapper>
    );
  }
}

ReservationPaymentReturnPage.propTypes = {
  t: PropTypes.func,
  location: PropTypes.object,
};

export default injectT(ReservationPaymentReturnPage);


text:
"""
onedrive-d
A Microsoft OneDrive client for Linux.
:copyright: (c) Xiangyu Bu
:license: MIT
"""

import sys
from setuptools import setup, find_packages

from onedrived import __author__, __email__, __homepage__, __project__, __version__

with open('requirements.txt', 'r') as f:
    install_requires = f.readlines()

test_requires = [
    'requests-mock',
]

with open('README.md', 'r') as f:
    readme = f.read()

python_version = sys.version_info

if python_version < (3, 3):
    raise Exception('%s %s only supports Python 3.3 and newer.' % (__project__, __version__))

if python_version < (3, 4):
    install_requires.append('asyncio')
    install_requires.append('enum34')

if python_version < (3, 5):
    install_requires.append('dbus-python')

setup(
    name=__project__,
    version=__version__,
    author=__author__,
    author_email=__email__,
    url=__homepage__,
    description='A Microsoft OneDrive client for Linux written in Python 3.',
    license='MIT',
    long_description=readme,
    packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    include_package_data=True,
    package_data={
            'onedrived': ['data/*', 'lang/*']
    },
    package_dir={'onedrived': 'onedrived'},
    entry_points={
        'console_scripts': [
            'onedrived = onedrived.od_main:main',
            'onedrived-pref = onedrived.od_pref:main'
        ],
        'gui_scripts': []
    },
    install_requires=install_requires,
    tests_require=test_requires,
    test_suite='tests',
    zip_safe=False
)


text:
require './spec/spec_helper'
require 'midori-contrib'

RSpec.describe Midori::Contrib do
  describe 'version' do
    it 'should be readable' do
      expect(Midori::Contrib::VERSION).to be_a(String)
      # Backwards compatibility
      expect(MidoriContrib::VERSION).to be_a(String)
    end
  end
end


text:
module ConfigAgent
  module Country
    VERSION = "0.0.1"
  end
end


text:
Pinned Sites is a small api providing most all functionality for doing IE9+ site pinning. For a working example see http://jamie-altizer.github.com/pinnedsites/

## Breaking changes with version 0.2.0.0

* Pinned.Jumplist.build() went from `Pinned.Jumplist.build(object)` to `Pinned.Jumplist.build(name, items)` where items is an array
* Pinned.ThumbBar.build() went from `Pinned.ThumbBar.build(object)` to `Pinned.ThumbBar.build(buttons, keepOnUnload)` where buttons is an array

## Basic API

isPinned() - Will return true/false whether site is pinned or not.

	Pinned.isPinned();

init() - Will initialize the site with the appropriate meta tags. If values are not provided, they will be determined from the site (e.g. start-url will be the current url). All fields are optional.

	Pinned.init({'name': 'My Pinned Site', 'tooltip': 'This site is AWESOME', 'startUrl': 'http://domain', 'windowSize': 'width=800;height=600', 'color': 'limegreen'});

addToStartMenu() - Will open a special window from IE that allows the user to add a link to their Start Menu. This is to be used in conjunction with a click event or something of the sort.

	Click here to add a link to the Start Menu!

## Tasks API

build() - Will build/add the provided tasks as tasks via the meta tags. If the "icon" field is left out, it automatically tries "/favicon.ico" at the location the action refers to. E.g. action = http://www.google.com, the default icon will be http://www.google.com/favicon.ico.

	Pinned.Tasks.build([
		{ 'name': 'Search', 'action': 'http://www.google.com' },
		{ 'name': 'CNN', 'action': 'http://www.cnn.com' }]);

## Taskbar API

flash(intervalInSeconds) - Will flash the taskbar button at the interval provided, when the window is not active. Default interval is 3.

	Pinned.Taskbar.flash(5); //will flash the taskbar every 5 seconds

## Overlay API

This library will automatically remove all overlay icons when leaving the page.

add(iconUri) - Will add an overlay icon to the taskbar button where iconUri is the path to the icon file.  These icons should be 16x16 and the taskbar properties cannot be set to "small icons"

	Pinned.Overlay.add('http://domain/overlay.ico');

blink(iconUri, startTimeInSeconds, durationInSeconds) - Will add the icon after the startTimeInSeconds has elapsed and clear the icon after the durationInSeconds. Default startTimeInSeconds is 5 and durationInSeconds is 3.

	Pinned.Overlay.blink('http://domain/overlay.ico', 5, 3);

removeAfter(iconUri, durationInSeconds) - Will add the icon and clear it after the specified duration. Default durationInSeconds is 5.

	Pinned.Overlay.removeAfter('http://domain/overlay.ico', 5);

clear() - Will clear the overlay icon from the taskbar.

	Pinned.Overlay.clear();

## Jumplist API

build(name, items) - Will build the dynamic jumplist from the provided array. It will also write to the console log when enough jumplist items have been added to go beyond the "typical" (10 items) maximum viewable or beyond the maximum supported by Windows (20 items). If you leave out the 'icon' the script will look for the favicon (see Tasks for an example)

	Pinned.Jumplist.clear();
    Pinned.Jumplist.build('Jumplist Example',[
            { 'name': 'Item 1', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 2', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 3', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 4', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 5', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 6', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 7', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 8', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 9', 'action': 'http://domain', 'icon': 'http://domain/example.ico' },
            { 'name': 'Item 10', 'action': 'http://domain', 'icon': 'http://domain/example.ico' }]);

Important notes:

* the dynamic jumplist acts as a stack when adding items... the first item added shows at the bottom
* most users can only see 10 jumplist items (unless they modify their taskbar settings) and the Tasks for pinned sites make up part of the total viewable

clear() - Will clear the dynamic jumplist.

## Thumbnail ThumbBar API

The callbacks provided will be called with two parameters: buttonId and styles. Styles will be empty if none were provided. The callback is intended to handle all functionality desired upon click, this includes determining the current style and then changing it with Pinned.ThumbBar.changeStyle().

build(buttons, keepOnload) - Will build the thumbbar and show it. If not specified with keepOnUnload = true, the thumbbar will be cleared upon leaving the window.

### Basic buttons

    Pinned.ThumbBar.build([{ 'name': 'Button1', 'icon': 'http://localhost/jamie/pinnedsites/style1.ico', 'callback': ButtonCallbackExample.button1 },
         { 'name': 'Button2', 'icon': 'http://localhost/jamie/pinnedsites/style2.ico', 'callback': ButtonCallbackExample.button2}], false);

### Styled buttons

The first button is "styled" and the second is not. If you do not set "current," the default will be the first style.

	Pinned.ThumbBar.build([
		{'styles': [
				{'icon': 'style1.ico', 'tooltip': 'Diamond Button', 'current': true},
				{'icon': 'style2.ico', 'tooltip': 'Circle Button'}],
		 'callback': ChangeStyleExample.button1},
        {'tooltip': 'Pin Button', 'icon': 'pin.ico', 'callback': ChangeStyleExample.button2}],
        false);

changeStyle(buttonId, styleId) - Will set the appropriate style.current to true and tell IE to switch the button

	Pinned.ThumbBar.changeStyle(someButtonProvided, styleIdDesired);

hideAll() - Will hide all buttons on the thumbbar.

	Pinned.ThumbBar.hideAll();


text:
namespace Habitat.Search.Models
{
  using Habitat.Framework.Indexing.Models;
  using Sitecore.Data.Items;

  public class SearchSettings : ISearchSettings
  {
    public Item ConfigurationItem { get; set; }
    public string Query { get; set; }
    public string SearchBoxTitle { get; set; }
    public string SearchResultsUrl { get; set; }
    public Item Root { get; set; }
  }
}


text:
c3_chart_internal_fn.getScale = function C3_INTERNAL_getScale(min, max, scaleType) {
    // keep compatibility
    if (typeof scaleType === 'boolean' && scaleType === true) {
        scaleType = 'timeseries';
    } else if (typeof scaleType === 'boolean') {
        scaleType = 'linear';
    }

    var customScale;
    // meybe customized scale
    if (typeof scaleType === 'function') {
        customScale = scaleType;
        scaleType = 'custom';
    } else if (typeof scaleType === 'string' && typeof this.d3.scale[scaleType] === 'function') {
        customScale = this.d3.scale[scaleType];
        scaleType = 'custom';
    }

    var scale;
    switch (scaleType) {
        case 'timeseries':
            scale = this.d3.time.scale();
            break;
        case 'custom':
            scale = customScale();
            break;
        default:
            scale = this.d3.scale.linear();
            break;
    }
    return scale.range([min, max]);
};
c3_chart_internal_fn.getScaleType = function () {
    return this.config.axis_x_scale_type;
};
c3_chart_internal_fn.getScaleTypeY = function () {
    return this.config.axis_y_scale_type;
};
c3_chart_internal_fn.getX = function C3_INTERNAL_getX(min, max, domain, offset) {
    var $$ = this,
        scale = $$.getScale(min, max, $$.isTimeSeries() ? true : $$.getScaleType()),
        _scale = domain ? scale.domain(domain) : scale,
        key;
    // Define customized scale if categorized axis
    if ($$.isCategorized()) {
        offset = offset || function () {
            return 0;
        };
        scale = function (d, raw) {
            var v = _scale(d) + offset(d);
            return raw ? v : Math.ceil(v);
        };
    } else {
        scale = function (d, raw) {
            var v = _scale(d);
            return raw ? v : Math.ceil(v);
        };
    }
    // define functions
    for (key in _scale) {
        scale[key] = _scale[key];
    }
    scale.orgDomain = function () {
        return _scale.domain();
    };
    // define custom domain() for categorized axis
    if ($$.isCategorized()) {
        scale.domain = function (domain) {
            if (!arguments.length) {
                domain = this.orgDomain();
                return [domain[0], domain[1] + 1];
            }
            _scale.domain(domain);
            return scale;
        };
    }
    return scale;
};
c3_chart_internal_fn.getY = function C3_INTERNAL_getY(min, max, domain) {
    var scale = this.getScale(min, max, this.isTimeSeriesY() ? true : this.getScaleTypeY());
    if (domain) {
        scale.domain(domain);
    }
    return scale;
};
c3_chart_internal_fn.getYScale = function C3_INTERNAL_getYScale(id) {
    return this.axis.getId(id) === 'y2' ? this.y2 : this.y;
};
c3_chart_internal_fn.getSubYScale = function C3_INTERNAL_getSubYScale(id) {
    return this.axis.getId(id) === 'y2' ? this.subY2 : this.subY;
};
c3_chart_internal_fn.updateScales = function C3_INTERNAL_updateScales() {
    var $$ = this,
        config = $$.config,
        forInit = !$$.x;
    // update edges
    $$.xMin = config.axis_rotated ? 1 : 0;
    $$.xMax = config.axis_rotated ? $$.height : $$.width;
    $$.yMin = config.axis_rotated ? 0 : $$.height;
    $$.yMax = config.axis_rotated ? $$.width : 1;
    $$.subXMin = $$.xMin;
    $$.subXMax = $$.xMax;
    $$.subYMin = config.axis_rotated ? 0 : $$.height2;
    $$.subYMax = config.axis_rotated ? $$.width2 : 1;
    // update scales
    $$.x = $$.getX($$.xMin, $$.xMax, forInit ? undefined : $$.x.orgDomain(), function () {
        return $$.xAxis.tickOffset();
    });
    $$.y = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y_default : $$.y.domain());
    $$.y2 = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y2_default : $$.y2.domain());
    $$.subX = $$.getX($$.xMin, $$.xMax, $$.orgXDomain, function (d) {
        return d % 1 ? 0 : $$.subXAxis.tickOffset();
    });
    $$.subY = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y_default : $$.subY.domain());
    $$.subY2 = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y2_default : $$.subY2.domain());
    // update axes
    $$.xAxisTickFormat = $$.axis.getXAxisTickFormat();
    $$.xAxisTickValues = $$.axis.getXAxisTickValues();
    $$.yAxisTickValues = $$.axis.getYAxisTickValues();
    $$.y2AxisTickValues = $$.axis.getY2AxisTickValues();

    $$.xAxis = $$.axis.getXAxis($$.x, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer, false, false);
    $$.subXAxis = $$.axis.getXAxis($$.subX, $$.subXOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer, false, false);
    $$.yAxis = $$.axis.getYAxis($$.y, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, config.axis_y_tick_outer, false, false, false);
    $$.y2Axis = $$.axis.getYAxis($$.y2, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, config.axis_y2_tick_outer, false, false, true);

    // Set initialized scales to brush and zoom
    if (!forInit) {
        if ($$.brush) {
            $$.brush.scale($$.subX);
        }
        if (config.zoom_enabled) {
            $$.zoom.scale($$.x);
        }
    }
    // update for arc
    if ($$.updateArc) {
        $$.updateArc();
    }
};


text:
import csv
import itertools
import operator
import numpy as np
import nltk
import sys
import os
import time
from datetime import datetime

infile = 'Data/reddit-comments-2015-08.csv'
outfile = "Data/reddit-comments-2015-08-tokenized.txt"

unknown_token = "UNKNOWN_TOKEN"
sentence_start_token = "SENTENCE_START"
sentence_end_token = "SENTENCE_END"

# Read the data and append SENTENCE_START and SENTENCE_END tokens
print "Reading ", infile
with open(infile, 'rb') as f:
    reader = csv.reader(f, skipinitialspace=True)
    reader.next()
    # Split full comments into sentences
    sentences = itertools.chain(*[nltk.sent_tokenize(x[0].decode('utf-8').lower()) for x in reader])
    # Append SENTENCE_START and SENTENCE_END
    sentences = ["%s %s %s" % (sentence_start_token, x, sentence_end_token) for x in sentences]
print "Parsed %d sentences." % (len(sentences))

# Tokenize the sentences into words
tokenized_sentences = [nltk.word_tokenize(sent) for sent in sentences]

print "Writing ", outfile
with open(outfile, 'wb') as f:
    for sent in tokenized_sentences:
        line = " ".join(sent) + "\n"
        f.write(line.encode('utf-8'))

###############################################################################################

# test code:
vocabulary_size = 8000
# Count the word frequencies
word_freq = nltk.FreqDist(itertools.chain(*tokenized_sentences))
print "Found %d unique words tokens." % len(word_freq.items())

# Get the most common words and build index_to_word and word_to_index vectors
vocab = word_freq.most_common(vocabulary_size-1)
index_to_word = [x[0] for x in vocab]
index_to_word.append(unknown_token)
word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)])

print "Using vocabulary size %d." % vocabulary_size
print "The least frequent word in our vocabulary is '%s' and appeared %d times." % (vocab[-1][0], vocab[-1][1])

# Replace all words not in our vocabulary with the unknown token
for i, sent in enumerate(tokenized_sentences):
    tokenized_sentences[i] = [w if w in word_to_index else unknown_token for w in sent]

print "\nExample sentence: '%s'" % sentences[0]
print "\nExample sentence after Pre-processing: '%s'" % tokenized_sentences[0]

# Create the training data
X_train = np.asarray([[word_to_index[w] for w in sent[:-1]] for sent in tokenized_sentences])
y_train = np.asarray([[word_to_index[w] for w in sent[1:]] for sent in tokenized_sentences])

print "data shapes:"
print "X: ", X_train.shape
print "y: ", y_train.shape


text:
package org.necros.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;

public class RequestUtils {
	private static final Logger logger = LoggerFactory.getLogger(RequestUtils.class);

	private Map<String, ObjectFactory<? extends Object>> beanFactories;
	private ClassCache classCache;

	public Object requestToObject(HttpServletRequest req, String clazz) {
		Object obj = clazzToInstance(clazz);
		if (obj == null) {
			obj = requestToMap(req);
		} else {
			assignRequestToObject(req, obj);
		}
		return obj;
	}

	public String requestBody(HttpServletRequest req) throws IOException {
		BufferedReader r = req.getReader();
		StringWriter w = new StringWriter();
		char[] buff = new char[4096];
		int cnt = 0;
		while ((cnt = r.read(buff, 0, buff.length)) > 0) {
			w.write(buff, 0, cnt);
		}
		return w.toString();
	}

	public void assignRequestToObject(HttpServletRequest req, Object obj) {
		ServletRequestDataBinder binder = new ServletRequestDataBinder(obj);
		initBinder(binder, req);
		binder.bind(req);
	}

	public String absolutePath(HttpServletRequest req, String relativePath) {
		return absoluteContextPath(req) + relativePath;
	}

	public static String absoluteContextPath(HttpServletRequest req) {
		int p = req.getLocalPort();
		return req.getScheme() + "://" + req.getLocalAddr() + (p == 80 ? "" : (":" + p)) + req.getContextPath();
	}

	private void initBinder(ServletRequestDataBinder binder, HttpServletRequest req) {
		ConversionService cs = (ConversionService) req.getAttribute(ConversionService.class.getName());
		if (cs == null) {
			logger.warn("Conversion service not found.");
		} else {
			if (logger.isTraceEnabled()) {
				logger.trace("Conversion from string to date: " + cs.canConvert(String.class, Date.class));
			}
		}
		binder.setConversionService(cs);
	}

	private Object clazzToInstance(String clazz) {
		logger.debug("Initializing class instance: " + clazz);
		if (!StringUtils.hasText(clazz))
			return null;
		if (beanFactories != null && !beanFactories.isEmpty()) {
			ObjectFactory<? extends Object> factory = beanFactories.get(clazz);
			if (factory != null) return factory.getObject();
		}
		try {
			Class<? extends Object> cls = classCache.get(clazz);
			if (cls == null) {
				return null;
			}
			return cls.newInstance();
		} catch (Throwable t) {
			logger.error("Error creating bean instance.", t);
			return null;
		}
	}

	public Object requestToMap(HttpServletRequest req) {
		Map<String, Object> r = new HashMap<String, Object>();
		for (Entry<String, String[]> e: req.getParameterMap().entrySet()) {
			String k = e.getKey();
			String[] v = e.getValue();
			if (v != null)
				r.put(k, StringUtils.arrayToCommaDelimitedString(v));
		}
		return r;
	}

	public ClassCache getClassCache() {
		return classCache;
	}

	public void setClassCache(ClassCache classCache) {
		this.classCache = classCache;
	}
}


text:
require('./common');
var api  = require('../lib');
var nock = require('nock');

describe('promise tests', function() {

  it('should correctly make an auth call', function(done) {
    var client = api.createClient();

    nock('https://api.losant.com', {
      reqheaders: {
        Accept: 'application/json',
      }
    }).post('/auth/user', {
      email: 'myemail@myemail.com',
      password: 'mypassword'
    }).query({ _actions: false, _embedded: true, _links: true})
    .reply(200, '{"userId":"theUserId","token":"an auth token string"}',
      { 'Content-Type': 'application/json' });

    client.auth.authenticateUser({ credentials: {
      email: 'myemail@myemail.com',
      password: 'mypassword'
    }}).then(function(response) {
      response.should.deepEqual({
        userId: 'theUserId',
        token: 'an auth token string',
      });
      nock.isDone().should.be.true();
      done();
    }).catch(function(err) {
      done(err);
    });
  });

  it('should correctly make a call with a token', function(done){
    var client = api.createClient({ accessToken: 'my token' });

    nock('https://api.losant.com', {
      reqheaders: {
        Accept: 'application/json',
        Authorization: 'Bearer my token'
      }
    }).get('/applications')
    .query({ _actions: false, _embedded: true, _links: true})
    .reply(200, '{"count":0,"items":[]}', { 'Content-Type': 'application/json' });

    client.applications.get().then(function(response) {
      response.should.deepEqual({
        count: 0,
        items: [],
      });
      nock.isDone().should.be.true();
      done();
    }).catch(function(err) {
      done(err);
    });
  });

  it('should correctly make calls with nested query params', function(done){
    var client = api.createClient({ accessToken: 'my token' });

    nock('https://api.losant.com', {
      reqheaders: {
        Accept: 'application/json',
        Authorization: 'Bearer my token'
      }
    }).get('/applications/appId/devices')
    .query({ _actions: false, _embedded: true, _links: true, tagFilter: [
      { key: 'key2' },
      { key: 'key1', value: 'value1' },
      { value: 'value2' },
    ]})
    .reply(200, '{"count":0,"items":[]}', { 'Content-Type': 'application/json' });

    client.devices.get({
      applicationId: 'appId',
      tagFilter: [
        { key: 'key2' },
        { key: 'key1', value: 'value1' },
        { value: 'value2' },
      ]
    }).then(function(response) {
      response.should.deepEqual({
        count: 0,
        items: [],
      });
      nock.isDone().should.be.true();
      done();
    }).catch(function(err) {
      done(err);
    });
  });

  it('should correctly make a call with an error', function(done){
    var client = api.createClient({ accessToken: 'my token' });

    nock('https://api.losant.com', {
      reqheaders: {
        Accept: 'application/json',
        Authorization: 'Bearer my token'
      }
    }).get('/applications/badId')
    .query({ _actions: false, _embedded: true, _links: true })
    .reply(404, '{"type":"NotFound","message":"Application was not found"}',
      { 'Content-Type': 'application/json' });

    client.application.get({ applicationId: 'badId' }).then(function(response) {
      done(new Error('Should not be here - ' + JSON.stringify(response)));
    }).catch(function(err) {
      err.statusCode.should.equal(404);
      err.type.should.equal('NotFound');
      err.message.should.equal('Application was not found');
      nock.isDone().should.be.true();
      done();
    });
  });

});


text:
This is a quick and dirty experimental project on generating pdfs with prawn in Rails.

The pdfs contain sample exam question for Managerial Accounting. Questions are on NPV, IRR, Cash Budgets.

Questions are parameterized and values for Costs, Revenue, Tax are generated on random in given ranges. Answers are provided only on part of the questions. Documents could be downloaded, printed and given to students.

Start with
```bash
rails s
```

and visit

localhost:3000/tasks.pdf

#### LICENSE
Could be found in the LICENSE document.


text:
package org.keycloak.testsuite.authz;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.mappers.GroupMembershipMapper;
import org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper;
import org.keycloak.representations.idm.GroupRepresentation;
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testsuite.util.ClientBuilder;
import org.keycloak.testsuite.util.GroupBuilder;
import org.keycloak.testsuite.util.RealmBuilder;
import org.keycloak.testsuite.util.RoleBuilder;
import org.keycloak.testsuite.util.RolesBuilder;
import org.keycloak.testsuite.util.UserBuilder;

/**
 * @author Pedro Igor
 */
public class GroupPathWithoutGroupClaimPolicyTest extends GroupPathPolicyTest {

    @Override
    public void addTestRealms(List<RealmRepresentation> testRealms) {
        ProtocolMapperRepresentation groupProtocolMapper = new ProtocolMapperRepresentation();

        groupProtocolMapper.setName("groups");
        groupProtocolMapper.setProtocolMapper(GroupMembershipMapper.PROVIDER_ID);
        groupProtocolMapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        Map<String, String> config = new HashMap<>();
        config.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "groups");
        config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
        config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true");
        groupProtocolMapper.setConfig(config);

        testRealms.add(RealmBuilder.create().name("authz-test")
                .roles(RolesBuilder.create()
                        .realmRole(RoleBuilder.create().name("uma_authorization").build())
                )
                .group(GroupBuilder.create().name("Group A")
                    .subGroups(Arrays.asList("Group B", "Group D").stream().map(name -> {
                        if ("Group B".equals(name)) {
                            return GroupBuilder.create().name(name).subGroups(Arrays.asList("Group C", "Group E").stream().map(new Function<String, GroupRepresentation>() {
                                @Override
                                public GroupRepresentation apply(String name) {
                                    return GroupBuilder.create().name(name).build();
                                }
                            }).collect(Collectors.toList())).build();
                        }
                        return GroupBuilder.create().name(name).build();
                    }).collect(Collectors.toList())).build())
                .group(GroupBuilder.create().name("Group E").build())
                .user(UserBuilder.create().username("marta").password("password").addRoles("uma_authorization").addGroups("Group A"))
                .user(UserBuilder.create().username("alice").password("password").addRoles("uma_authorization"))
                .user(UserBuilder.create().username("kolo").password("password").addRoles("uma_authorization"))
                .client(ClientBuilder.create().clientId("resource-server-test")
                    .secret("secret")
                    .authorizationServicesEnabled(true)
                    .redirectUris("http://localhost/resource-server-test")
                    .defaultRoles("uma_protection")
                    .directAccessGrants())
                .build());
    }
}


text:
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/answer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/survey_answer_text_size"
        android:paddingStart="@dimen/survey_answer_padding_start"
        android:paddingEnd="@dimen/survey_answer_padding_end"
        android:paddingTop="@dimen/survey_answer_padding_top"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Ansver"/>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="0dp"
        android:layout_height="@dimen/survey_percentage_view_height"
        android:layout_marginTop="@dimen/survey_percentage_margin_vertical"
        android:layout_marginBottom="@dimen/survey_percentage_margin_vertical"
        android:background="?surveyBarStroke"
        android:orientation="horizontal"
        android:weightSum="100"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/answer"
        app:layout_constraintEnd_toStartOf="@id/radioButton">

        <View
            android:id="@+id/percentage_view"
            android:layout_width="0dp"
            android:layout_height="@dimen/survey_percentage_view_height"
            android:layout_weight="30"
            android:background="?surveyBar"/>

        <View
            android:layout_width="0dp"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <TextView
        android:id="@+id/votesCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/survey_votes_count_margin_top"
        android:layout_marginEnd="@dimen/survey_votes_count_margin_end"
        android:textSize="@dimen/survey_votes_count_text_size"
        app:layout_constraintEnd_toEndOf="@id/linearLayout"
        app:layout_constraintTop_toBottomOf="@id/answer"
        tools:text="30% (0 głosów)"/>

    <RadioButton
        android:id="@+id/radioButton"
        android:theme="@style/CheckBoxStyle"
        android:layout_width="@dimen/survey_votes_radio_button_width"
        android:layout_height="@dimen/survey_votes_radio_button_height"
        android:layout_marginStart="@dimen/survey_votes_radio_button_margin_start"
        app:layout_constraintStart_toEndOf="@id/linearLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/answer"/>

</androidx.constraintlayout.widget.ConstraintLayout>


text:
package ua.oit.selenium2.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;

import static com.codeborne.selenide.Selenide.$;

/**
 * Class {@code RozetkaHeaderLoginPopup} describes Login popup.
 * This class also in charge for interacting with web elements located on the page.
 * Use methods in this class for interact with this page or add new.
 *
 * @author Oleg Tatarchuk
 */
public class RozetkaHeaderLoginPopup extends RozetkaHeader implements Popup{
    public static By inputLogin     = By.name("login");
    public static By inputPassword  = By.name("password");
    public static By buttonLogin    = By.name("auth_submit");

    public RozetkaHeaderLoginPopup () {
        if (getSigninLinkText().equals("войдите в личный кабинет")) {
            super.clickSingninLink();
        } else {System.out.println("\n >> User is already logged in \n");}
    }

    public void fillLoginFormAndClickLogin(String email, String pwd) {
        $(inputLogin).setValue(email);
        $(inputPassword).setValue(pwd);
        $(buttonLogin).click();
    }
}


text:
set -ex
./scripts/godownloader-goreleaser.sh
go get -u github.com/alecthomas/gometalinter && gometalinter --install


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class Nails\Admin\Admin\Settings</title>

	<link rel="stylesheet" href="resources/bootstrap.min.css?08b23951ef4599ca9cbf1f902d0e8290c9653ddd">
	<link rel="stylesheet" href="resources/style.css?062e9e59e0b8c44fbaaded5b7ffc21f907b78669">

				Overview

							Namespace

Class

		<form id="search" class="form-search">
			<input type="hidden" name="cx" value="">
			<input type="hidden" name="ie" value="UTF-8">
			<input type="text" name="q" class="search-query" placeholder="Search">
		</form>

Namespaces

							Nails

							Admin

							Admin

							Auth

							Blog

							Cdn

							Cms

							Email

							Shop

							Testimonial

							None

Classes

Dashboard

Help

Logs

Notification

Settings

Utilities

Class Settings

This class is the base class of all Admin controllers, it defines some basic
methods which should exist.

			MX_Controller

			AdminController

Nails\Admin\Admin\Settings

		Namespace: Nails\Admin\Admin

		Package: Nails\module-admin

				Category:
				Controller

				Author:
				Nails Dev Team

				Link

			Located at module-admin/admin/controllers/settings.php

Methods summary

				 public static
				stdClass

			#
			announce( )

Announces this controller's navGroups

Announces this controller's navGroups

Returns

						stdClass

Overrides

AdminController::announce

				 public

			#
			admin( )

Manage Admin settings

Manage Admin settings

				 protected

			#
			_admin_update_branding( )

Set Admin branding settings

Set Admin branding settings

				 protected

			#
			_admin_update_whitelist( )

Set Admin IP whitelist settings

Set Admin IP whitelist settings

				 public

			#
			site( )

Manage Site settings

Manage Site settings

				 protected

			#
			_site_update_analytics( )

Set Site Analytics settings

Set Site Analytics settings

				 protected

			#
			_site_update_auth( )

Set Site Auth settings

Set Site Auth settings

				 protected

			#
			_site_update_maintenance( )

Set Site Maintenance settings

Set Site Maintenance settings

Methods inherited from AdminController

			__construct(),
			notifications(),
			permissions()

Methods inherited from MX_Controller

			__get()

Magic methods summary

Properties summary

Properties inherited from AdminController

			<var>$data</var>

Properties inherited from MX_Controller

			<var>$autoload</var>

		 API documentation generated by ApiGen


text:
package rsc.subscriber;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

public enum EmptySubscriber implements Subscriber<Object> {
    INSTANCE;

    @SuppressWarnings("unchecked")
    public static <T> Subscriber<T> instance() {
        return (Subscriber<T>) INSTANCE;
    }

    @Override
    public void onSubscribe(Subscription s) {
        // deliberately no op
    }

    @Override
    public void onNext(Object t) {
        // deliberately no op
    }

    @Override
    public void onError(Throwable t) {
        // deliberately no op
    }

    @Override
    public void onComplete() {
        // deliberately no op
    }

}


text:
/**
 * @module Health
 */
/// <reference path="healthPlugin.ts"/>
module Health {

    export var HealthController = _module.controller("Health.HealthController", ["$scope", "jolokia", "workspace", "$templateCache", ($scope, jolokia, workspace:Workspace, $templateCache) => {

      $scope.levelSorting = {
        'ERROR': 0,
        'WARNING': 1,
        'INFO': 2
      };

      $scope.colorMaps = {
        'ERROR': {
          'Health': '#ff0a47',
          'Remaining': '#e92614'
        },
        'WARNING': {
          'Health': '#33cc00',
          'Remaining': '#f7ee09'
        },
        'INFO': {
          'Health': '#33cc00',
          'Remaining': '#00cc33'
        }
      };

      $scope.results = [];
      $scope.responses = {};
      $scope.mbeans = [];
      $scope.mbeanStatus = {};
      $scope.displays = [];
      $scope.page = '';

      $scope.pageFilter = '';

      $scope.$watch('mbeans', (newValue, oldValue) => {
        Core.unregister(jolokia, $scope);
        if (!newValue) {
          return;
        }
        $scope.mbeanStatus = {};
        newValue.forEach((mbean) => {
          var unregFunc = Core.register(jolokia, $scope, {
            type: 'exec', mbean: mbean,
            operation: "healthList()"
          }, {
            success: $scope.render,
            error: (response) => {
              log.info("Failed to invoke healthList() on mbean: " + mbean + " due to: ", response.error);
              log.debug("Stack trace: ", response.stacktrace.split("\n"));
              unregFunc();
            }
          });

          var error = (response) => {
            if (!response.error.has("AttributeNotFoundException")) {
              log.info("Failed to read CurrentStatus on mbean: " + mbean + " due to: ", response.error);
              log.debug("Stack trace: ", response.stacktrace.split("\n"));
            }
          };

          //see if the mbean has a CurrentStatus attribute and keep an eye on it if so
          jolokia.request({
            type: 'read', mbean: mbean, attribute: 'CurrentStatus'
          }, {
            success: (response) => {
              $scope.mbeanStatus[response.request['mbean']] = response.value;
              Core.register(jolokia, $scope, {
                type: 'read', mbean: mbean, attribute: 'CurrentStatus'
              }, {
                success: (response) => {
                  /*
                  log.debug("response for CurrentStatus",
                      response.request['mbean'],
                      ": ",
                      response.value);
                      */
                  if (response.value === $scope.mbeanStatus[response.request['mbean']]) {
                    return;
                  }
                  $scope.mbeanStatus[response.request['mbean']] = response.value;
                  Core.$apply($scope);
                },
                error: error
              });
            },
            error: error
          });
        });
      }, true);

      $scope.getTitleClass = (display) => {
        if (!display) {
          return "warning";
        }
        if (!display.values || display.values.length === 0) {
          return "ok";
        }
        var answer = "ok";
        display.values.forEach((value) => {
          if (answer !== "warning" && value.level && value.level.toLowerCase() !== 'info') {
            answer = "warning";
          }
        });

        return answer;
      };

      $scope.getHumanName = (name) => {
        if (name.startsWith("org.apache.activemq")) {
          var answer = name;
          var nameParts = name.split(',');
          nameParts.forEach((part) => {
            if (part.startsWith('brokerName')) {
              var parts = part.split('=');
              if (parts[1]) {
                answer = "Broker: " + parts[1];
              }
            }
          });
          return answer;
        }
        if (name.startsWith("io.fabric8:service")) {
          return "Fabric8";
        }

        return name;

      };

      $scope.getMBeans = () => {
        var healthMap = getHealthMBeans(workspace);
        log.debug("HealthMap: ", healthMap);
        if (healthMap) {
          if (!angular.isArray(healthMap)) {
            return [healthMap.objectName];
          }
          var answer = healthMap.map((obj) => { return obj.objectName; });
          log.debug("Health mbeans: ", answer);
          return answer;
        } else {
          log.debug("No health mbeans found...");
          return [];
        }
      };

      $scope.$on('jmxTreeUpdated', () => {
        $scope.mbeans = $scope.getMBeans();
      });

      $scope.$on('$routeChangeSuccess', () => {
        $scope.mbeans = $scope.getMBeans();
      });

      $scope.mbeans = $scope.getMBeans();

      $scope.render = (response) => {
        /*
         log.debug("response for ",
            response.request['mbean'],
            ".",
            response.request['operation'],
            ": ",
            response.value);
        */
        var mbean = response.request['mbean'];
        var values = response.value;

        var responseJson = angular.toJson(values);

        if (mbean in $scope.responses) {
          if ($scope.responses[mbean] === responseJson) {
            return;
          }
        }

        $scope.responses[mbean] = responseJson;

        var display = $scope.displays.find((m) => { return m.mbean === mbean });

        values = defaultValues(values);

        values = values.sortBy((value) => {
          if (!value.level) {
            return 99;
          }
          return $scope.levelSorting[value.level];
        });

        values.forEach((value:any) => {

          var healthPercentCurrent = 0;
          var healthPercentRemaining = 1;

          if ('healthPercent' in value) {
            var healthPercent = <number>value['healthPercent'];
            healthPercentCurrent = healthPercent.round(3);
            healthPercentRemaining = 1 - healthPercentCurrent;
            healthPercentRemaining = healthPercentRemaining.round(3);
          }

          value.data = {
              total: 1,
              terms: [{
                term: 'Health',
                count: healthPercentCurrent
              }, {
                term: 'Remaining',
                count: healthPercentRemaining
              }]
            };
            value.colorMap = $scope.colorMaps[value.level];
        });

        if (!display) {
          $scope.displays.push({
            mbean: mbean,
            values: values
          });
        } else {
          display.values = values;
        }

        //log.debug("Display: ", $scope.displays);
        if ($scope.page === '') {
          $scope.page = $templateCache.get('pageTemplate');
        }

        Core.$apply($scope);
      };

      $scope.filterValues = (value) => {
        var json = angular.toJson(value);
        return json.has($scope.pageFilter);
      };

      $scope.sanitize = (value) => {
        var answer = {};
        Object.extended(value).keys().forEach((key) => {
          if ($scope.showKey(key) && value[key]) {
            answer[key] = value[key];
          }
        });
        return answer;
      };

      $scope.showKey = (key) => {
        if ( key === "colorMap" || key === "data") {
          return false;
        }
        return true;
      };

      $scope.getTitle = (value) => {
        if (value['healthId'].endsWith('profileHealth')) {
          return 'Profile: ' + value['profile'] + '';
        }
        return 'HealthID: ' + value['healthId'] + '';
      };

      $scope.isPercentage = (key) => {
        if( key !== undefined && key.toUpperCase().indexOf("PERCENT") > 0 ){
           return true;
        }
        return false;
      };

      /*
       * Default the values that are missing in the returned JSON
       */
      function defaultValues(values) {
        angular.forEach(values, (aData) => {
          var domain = aData["domain"];
          if (!domain) {
            var id = aData["healthId"];
            if (id) {
              var idx = id.lastIndexOf('.');
              if (idx > 0) {
                domain = id.substring(0, idx);
                var alias = Health.healthDomains[domain];
                if (alias) {
                  domain = alias;
                }
                var kind = aData["kind"];
                if (!kind) {
                  kind = Core.humanizeValue(id.substring(idx + 1));
                  aData["kind"] = kind;
                }
              }
            }
            aData["domain"] = domain;
          }
        });
        return values;
      }

      function createOKStatus(object) {
        return {
          healthId: object.domain + ".status",
          level: "INFO",
          message: object.title + " is OK"
        };
      }
    }]);
}


text:
package org.mockserver.client;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockserver.client.ClientException;
import org.mockserver.client.MockServerClient;
import org.mockserver.echo.http.EchoServer;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.mockserver.character.Character.NEW_LINE;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

/**
 * @author jamesdbloom
 */
public class MockServerClientServerValidationErrorsTest {

    @Rule
    public ExpectedException exception = ExpectedException.none();

    private EchoServer echoServer;
    private MockServerClient mockServerClient;

    @Before
    public void setupTestFixture() throws Exception {
        echoServer = new EchoServer(false);
        mockServerClient = new MockServerClient("localhost", echoServer.getPort());
    }

    @Test
    public void shouldHandleServerValidationFailure() {
        // given
        String responseBody = "2 errors:" + NEW_LINE +
                " - object instance has properties which are not allowed by the schema: [\"paths\"] for field \"/httpRequest\"" + NEW_LINE +
                " - for field \"/httpRequest/body\" a plain string, JSON object or one of the following example bodies must be specified " + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"BINARY\"," + NEW_LINE +
                "     \"base64Bytes\": \"\"," + NEW_LINE +
                "     \"contentType\": \"\"" + NEW_LINE +
                "   }, " + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"JSON\"," + NEW_LINE +
                "     \"json\": \"\"," + NEW_LINE +
                "     \"contentType\": \"\"," + NEW_LINE +
                "     \"matchType\": \"ONLY_MATCHING_FIELDS\"" + NEW_LINE +
                "   }," + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"JSON_SCHEMA\"," + NEW_LINE +
                "     \"jsonSchema\": \"\"" + NEW_LINE +
                "   }," + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"PARAMETERS\"," + NEW_LINE +
                "     \"parameters\": {\"name\": \"value\"}" + NEW_LINE +
                "   }," + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"REGEX\"," + NEW_LINE +
                "     \"regex\": \"\"" + NEW_LINE +
                "   }," + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"STRING\"," + NEW_LINE +
                "     \"string\": \"\"" + NEW_LINE +
                "   }," + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"XML\"," + NEW_LINE +
                "     \"xml\": \"\"," + NEW_LINE +
                "     \"contentType\": \"\"" + NEW_LINE +
                "   }," + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"XML_SCHEMA\"," + NEW_LINE +
                "     \"xmlSchema\": \"\"" + NEW_LINE +
                "   }," + NEW_LINE +
                "   {" + NEW_LINE +
                "     \"not\": false," + NEW_LINE +
                "     \"type\": \"XPATH\"," + NEW_LINE +
                "     \"xpath\": \"\"" + NEW_LINE +
                "   }";
        echoServer.withNextResponse(response()
                .withStatusCode(400)
                .withBody(responseBody)
        );

        // then
        exception.expect(IllegalArgumentException.class);
        exception.expectMessage(containsString(responseBody));

        // when
        mockServerClient.when(request()).respond(response());
    }

    @Test
    public void shouldHandleOtherClientError() {
        // given
        String responseBody = "some_random_response";
        echoServer.withNextResponse(response()
                .withStatusCode(401)
                .withBody(responseBody)
        );

        // then
        exception.expect(ClientException.class);
        exception.expectMessage(is("error:" + NEW_LINE +
            NEW_LINE +
            "\t" + responseBody + NEW_LINE +
            NEW_LINE +
            " while submitted expectation:" + NEW_LINE +
            NEW_LINE +
            "\t{" + NEW_LINE +
            "\t  \"httpRequest\" : { }," + NEW_LINE +
            "\t  \"times\" : {" + NEW_LINE +
            "\t    \"unlimited\" : true" + NEW_LINE +
            "\t  }," + NEW_LINE +
            "\t  \"timeToLive\" : {" + NEW_LINE +
            "\t    \"unlimited\" : true" + NEW_LINE +
            "\t  }," + NEW_LINE +
            "\t  \"httpResponse\" : { }" + NEW_LINE +
            "\t}" + NEW_LINE
        ));

        // when
        mockServerClient.when(request()).respond(response());
    }
}


text:
package engine;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.amazonaws.services.lambda.runtime.Context;

import environment.EnvConstants;

public class SqlConnector {

	private static final String jdbcUrl;

	private static String db_name;
	private static String username;
	private static String password;

	static {
		db_name = EnvConstants.env.getDatabase();
		username = EnvConstants.env.getUser();
		password = EnvConstants.env.getPassword();

		jdbcUrl = "jdbc:mysql://" + EnvConstants.env.getHost() + ":" + EnvConstants.env.getPort() + "/" + db_name;
	}

	private Connection connection;

	private static SqlConnector INSTANCE;

	public static synchronized SqlConnector getInstance(Context context) throws Exception {
		if (INSTANCE == null)
			INSTANCE = new SqlConnector(context);

		return INSTANCE;
	}

	public synchronized Connection getRestoreConnection() throws SQLException {
		if (connection.isClosed())
			connection = DriverManager.getConnection(jdbcUrl, username, password);

		return connection;
	}

	private SqlConnector(Context context) throws Exception {
		try {
			context.getLogger().log("connecting to db..");
			String driver = "com.mysql.jdbc.Driver";
			Class.forName(driver).newInstance();
			connection = DriverManager.getConnection(jdbcUrl, username, password);
			context.getLogger().log("successfully connected!");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("username: " + username + ". password: " + password + ". jdbcUrl: " + jdbcUrl + ". "
					+ e.getMessage());
		}
	}
}


text:
import {MARK_AS_READ, MARK_AS_UNREAD} from '../constants'

const items = [
  {
    id: 1,
    title: 'Item title 1',
    text: 'Item text 1',
    isRead: false
  },
  {
    id: 2,
    title: 'Item title 2',
    text: 'Item text 2',
    isRead: false
  }
];

function blogItem(state, action) {
  switch (action.type) {
    case MARK_AS_READ:
      if (state.id !== action.id) {
        return state
      }

      return {
        ...state,
        isRead: true
      };
      break;
    case MARK_AS_UNREAD:
      if (state.id !== action.id) {
        return state
      }

      return {
        ...state,
        isRead: false
      };
      break;

    default:
      return state;
  }
}

export default function (state = items, action) {
  switch (action.type) {
    case MARK_AS_READ:
    case MARK_AS_UNREAD:
      return state.map(item => blogItem(item, action));
      break;

    default:
      return state;
  }
}


text:
package com.scalaAsm.x86
package Instructions
package General

// Description: Add
// Category: general/arith/binary

trait ADD extends InstructionDefinition {
  val mnemonic = "ADD"
}

object ADD extends OneOperand[ADD] with TwoOperands[ADD] with ADDImpl

trait ADDLow extends ADD {
  implicit object _0 extends TwoOp[rm8, r8] {
    val opcode: OneOpcode = 0x00 /r
    val format = MemRegFormat
  }

  implicit object _1 extends TwoOp[rm16, r16] {
    val opcode: OneOpcode = 0x01 /r
    val format = MemRegFormat
  }

  implicit object _2 extends TwoOp[rm32, r32] {
    val opcode: OneOpcode = 0x01 /r
    val format = MemRegFormat
  }

  implicit object _3 extends TwoOp[rm64, r64] {
    val opcode: OneOpcode = 0x01 /r
    override def prefix = REX.W(true)
    val format = MemRegFormat
  }

  implicit object _4 extends TwoOp[r8, rm8] {
    val opcode: OneOpcode = 0x02 /r
    val format = RegRmFormat
  }

  implicit object _5 extends TwoOp[rm8, imm8] {
    val opcode: OneOpcode = 0x80 /+ 0
    val format = RmImmFormat
  }

  implicit object _6 extends TwoOp[rm16, imm16] {
    val opcode: OneOpcode = 0x81 /+ 0
    val format = RmImmFormat
  }

  implicit object _7 extends TwoOp[rm32, imm32] {
    val opcode: OneOpcode = 0x81 /+ 0
    val format = RmImmFormat
  }

  implicit object _8 extends TwoOp[rm64, imm32] {
    val opcode: OneOpcode = 0x81 /+ 0
    override def prefix = REX.W(true)
    val format = RmImmFormat
  }

  implicit object _9 extends TwoOp[rm16, imm8] {
    val opcode: OneOpcode = 0x83 /+ 0
    val format = RmImmFormat
  }

  implicit object _10 extends TwoOp[rm32, imm8] {
    val opcode: OneOpcode = 0x83 /+ 0
    val format = RmImmFormat
  }

  implicit object _11 extends TwoOp[rm64, imm8] {
    val opcode: OneOpcode = 0x83 /+ 0
    override def prefix = REX.W(true)
    val format = RmImmFormat
  }
}

trait ADDImpl extends ADDLow {
  implicit object _12 extends TwoOp[r16, rm16] {
    val opcode: OneOpcode = 0x03 /r
    val format = RegRmFormat
  }

  implicit object _13 extends TwoOp[r32, rm32] {
    val opcode: OneOpcode = 0x03 /r
    val format = RegRmFormat
  }

  implicit object _14 extends TwoOp[r64, rm64] {
    val opcode: OneOpcode = 0x03 /r
    override def prefix = REX.W(true)
    val format = RegRmFormat
  }

  implicit object _15 extends OneOp[imm8] {
    val opcode: OneOpcode = 0x04
    val format = ImmFormat
    override def hasImplicitOperand = true
  }

  implicit object _16 extends OneOp[imm16] {
    val opcode: OneOpcode = 0x05
    val format = ImmFormat
    override def hasImplicitOperand = true
  }

  implicit object _17 extends OneOp[imm32] {
    val opcode: OneOpcode = 0x05
    val format = ImmFormat
    override def hasImplicitOperand = true
  }
}