text:
''' A Simple Reminder Plugin '''
from hogar.Utils.StringUtils import ignore_case_replace
from recurrent import RecurringEvent
from dateutil.rrule import rrulestr
from hogar.Models.RemindOnce import RemindOnce
from hogar.Models.RemindRecurring import RemindRecurring
import os
import arrow
import datetime
import json
import ConfigParser
import logging

logger = logging.getLogger(__name__)

config = ConfigParser.ConfigParser()
config.read(
    os.path.join(os.path.dirname(__file__), '../../../settings.ini'))

def enabled ():
    '''
        Enabled

        Is this plugin enabled. Returning false here
        will cause this plugin to be ignored by the
        framework entirely.

        --
        @return bool
    '''

    return True

def applicable_types ():
    '''
        Applicable Types

        Returns the type of messages this plugin is for.
        See: hogar.static.values

        --
        @return list
    '''

    return ['text']

def commands ():
    '''
        Commands

        In the case of text plugins, returns the commands
        that this plugin should trigger for. For other
        message types, a empty list should be returned.

        If your plugin applies to any command (in the
        case of text messages), simply supply the a
        wildcard in the list ie. ['*']

        --
        @return list
    '''

    return ['reminder', 'remind']

def should_reply ():
    '''
        Should Reply

        Specifies wether a reply should be sent to the original
        sender of the message that triggered this plugin.

        --
        @return bool
    '''

    return True

def reply_type ():
    '''
        Reply Type

        Specifies the type of reply that should be sent to the
        sender. This is an optional function. See hogar.static.values
        for available types.

        --
        @return str
    '''

    return 'text'

def _extract_parts (text):
    '''
        Extract Parts

        Extract and parse the message, returning a dictionary
        describing the actions that should be taken

        --
        @param  text:string    The message sent by the user

        @return dict
    '''

    # Examples:
    # remind me once monday at 4pm, Help!
    # remind me once two weeks from now, Help!
    #
    # remind me every 5 minutes, Help!
    # remind me every 1 day, Help!
    #
    # remind show
    # remind stop #1

    # With the above examples, we can say that the
    # format should follow the following:
    #
    # [script init] [set / show /stop / help] [once/every] [time]: [message]

    parts = {

        'recipient': None,
        'action': 'set',
        'recurrence': 'once',
        'time': None,
        'parsed_time': None,
        'message': None,
        'error': False,
        'error_message': None
    }

    # Check the action_recipient
    action_recipient = text.split(' ')[0].strip()

    # Ensure that the action is something we understand
    if action_recipient not in ['set', 'show', 'stop', 'help']:
        parts['error'] = True
        parts['error_message'] = 'Unknown command: {c}'.format(
            c = action_recipient
        )

        return parts

    # We are happy with the action. show and stop
    # actions dont care about the rest
    if action_recipient in ['show', 'stop', 'help']:
        parts['action'] = action_recipient
        return parts

    # Set the recipient and remove it from the text
    text = text.replace(action_recipient, '', 1).strip()
    parts['recipient'] = action_recipient

    # Next part is to check the recurrence.
    recurrence = text.split(' ')[0].strip()

    # Check that the recurrence is valid
    if recurrence not in ['once', 'every']:
        parts['error'] = True
        parts['error_message'] = 'Unknown recurrence: {r}'.format(
            r = recurrence
        )

        return parts

    # Set the recurrence and remove it from the text
    # only of it is set to 'once'
    text = text.replace('once', '', 1).strip()
    parts['recurrence'] = recurrence

    # Next, we parse the time. For this we should be
    # able to split by ,
    if len(text.split(',', 1)) != 2:
        parts['error'] = True
        parts['error_message'] = 'Time and message should be seperated by a comma ( , ) character'

        return parts

    # Set the time and the message
    time = text.split(',', 1)[0].strip()
    message = text.split(',', 1)[1].strip()

    # Resolve the human time to something we can work
    # with
    r = RecurringEvent()
    parsed_time = r.parse(time)

    # If the time parsing failed, oh well.
    if parsed_time is None:
        parts['error'] = True
        parts['error_message'] = 'Unable to parse time: {t}'.format(
            t = time
        )

        return parts

    # Set the time and parsed time, as well as the message
    # that should be used
    parts['time'] = time
    parts['parsed_time'] = parsed_time
    parts['message'] = message

    return parts

def _set_once_reminder (r, orig_message):
    '''
        Set Once Reminder

        Record a reminder in the database to be sent.

        --
        @param  r:dict              The parsed message from the user
        @param  orig_message:str    The original message received

        @return str
    '''

    logger.debug('Storing reminder for {id}'.format(
        id = orig_message['chat']['id']
    ))

    RemindOnce.create(
        orig_message = json.dumps(orig_message),
        time = r['parsed_time'],
        message = r['message']
    )

    return

def _set_recurring_reminder (r, orig_message):
    '''
        Set Recurring Reminder

        Record a recurring reminder in the database to be sent.

        #TODO: Implement this

        --
        @param  r:dict              The parsed message from the user
        @param  orig_message:str    The original message received

        @return str
    '''

    logger.debug('Storing reminder for {id}'.format(
        id = orig_message['chat']['id']
    ))

    RemindRecurring.create(
        orig_message = json.dumps(orig_message),
        rrules = r['parsed_time'],
        next_run = rrulestr(r['parsed_time'],
                            dtstart = datetime.datetime.now()).after(datetime.datetime.now()),
        message = r['message']
    )

    return

def _show_all_reminders (message):
    '''
        Show All Reminders

        Returns all of the reminders for the appropriate
        chat ID that the message came from

        --
        @param  message:dict    The message sent by the user

        @return str
    '''

    response = '\n# One time reminders:\n\n'

    for reminder in RemindOnce.select().where(RemindOnce.sent == 0, \
                                              RemindOnce.time >= datetime.datetime.now()):

        orig_message = json.loads(reminder.orig_message)
        if orig_message['chat']['id'] == message['chat']['id']:
            response += '(#{id}) {human} @{time} | {message}\n'.format(
                id = reminder.id,
                human = arrow.get(reminder.time,
                                  config.get('reminder', 'timezone', 'UTC')).humanize(),
                time = str(reminder.time),
                message = reminder.message[:20] + '...' \
                    if len(reminder.message) > 20 else reminder.message)

    response += '\n# Recurring reminders:\n\n'

    for reminder in RemindRecurring.select().where(RemindRecurring.sent == 0, \
                                                   RemindRecurring.next_run >= datetime.datetime.now()):

        orig_message = json.loads(reminder.orig_message)
        if orig_message['chat']['id'] == message['chat']['id']:
            response += '(#{id}) {human} @{next_run} | {message}\n'.format(
                id = reminder.id,
                human = arrow.get(reminder.next_run,
                                  config.get('reminder', 'timezone', 'UTC')).humanize(),
                next_run = str(reminder.next_run),
                message = reminder.message[:20] + '...' \
                    if len(reminder.message) > 20 else reminder.message)

    return response

def _stop_reminder (message):
    '''
        Stop A Reminder

        Sets a reminder as sent so that it will not run
        again. This function also ensures that the
        reminder's chatID matches the chatID of
        the user requesting the stop

        --
        @param  message:dict    The message sent by the user

        @return str
    '''

    # Remove the command form the text
    text = message['text'].replace('remind stop', '').strip()

    # Split the remainder of the text into 2 parts.
    # We are expecting either 'once' or 'recurring'
    # as the type of reminder and a number
    parts_list = text.split(' ')

    # Check the length of the list and assume a typo
    # if its not 2
    if len(parts_list) != 2:
        return 'Could not understand what you wanted. Expecting:\n' + \
               'remind stop [once/recurring] [message number]'

    message_type = parts_list[0]
    message_number = parts_list[1]

    # Check that we got once or recurring
    if message_type not in ['once', 'recurring']:
        return 'Could not figure out which message type you are referring to. ' + \
               'Expected \'once\' / \'recurring\''

    # For once time messages, perform the chatID check
    # and mark the message as sent if its ok
    if message_type == 'once':

        try:
            m = RemindOnce.select().where(RemindOnce.id == message_number).get()

            if json.loads(m.orig_message)['chat']['id'] == message['chat']['id']:

                m.sent = 1
                m.save()

            else:

                logger.warning('User {id} tried to disable a reminder they dont own'.format(
                    id = message['chat']['id']))
                return 'That message number does not exist or you dont own it.'

        except RemindOnce.DoesNotExist:
            return 'That message number does not exist or you dont own it.'

        return 'Done stopping the one time reminder'

    # The same here for the recurring message.
    if message_type == 'recurring':

        try:
            m = RemindRecurring.select().where(RemindRecurring.id == message_number).get()

            if json.loads(m.orig_message)['chat']['id'] == message['chat']['id']:

                m.sent = 1
                m.save()

            else:

                logger.warning('User {id} tried to disable a reminder they dont own'.format(
                    id = message['chat']['id']))
                return 'That message number does not exist or you dont own it.'

        except RemindRecurring.DoesNotExist:
            return 'That message number does not exist or you dont own it.'

        return 'Done stopping the recurring reminder'

    # We will most probably never get here, but
    # just in case...
    return 'Nothing happend...'

def _show_help (message):
    '''
        Show Help

        Shows usage help

        --

        @return None
    '''

    h = '\n# Reminder Plugin Help:\n'
    h += 'Commands Sytax:\n'
    h += 'remind [ set / show / stop / help ] [once/every] [time], [message]\n\n'
    h += 'Descriptions:\n'
    h += ' - set    : set a reminder for the current chat\n'
    h += ' - show   : show all reminders\n'
    h += ' - stop   : stop a reminder\n'
    h += ' - help   : show this help\n'

    return h

def run (message):
    '''
        Run

        Run the custom plugin specific code. A returned
        string is the message that will be sent back
        to the user.

        --
        @param  message:dict    The message sent by the user

        @return str
    '''

    # Get the message contents
    text = message['text']

    # Remove a mention. This could be the case
    # if the bot was mentioned in a chat room
    if text.startswith('@'):
        text = text.split(' ', 1)[1].strip()

    # Some bots will accept commands that started
    # with a '/'
    if text.startswith('/'):
        text = text.replace('/', '', 1).strip()

    # Try and determine what was the trigger command
    # for this plugin.
    action = text.split(' ')[0].strip()

    # Hopefully we never get here, but just in case.
    if action not in commands():
        return 'Sorry, I don\'t know what to do with: {command}'.format(
            command = action
        )

    # Remove the trigger command
    for command in commands():
        text = ignore_case_replace(command, '', text).strip()

    # Now, parse the reminder line
    parts = _extract_parts(text)

    # If there was an error with the message, show it
    if parts['error']:
        error_message = 'Reminder not set. Error was: {e}.\n\n{help}'.format(
            e = parts['error_message'],
            help = _show_help(None)
        )

        return error_message

    # Handle a few control commands that should show
    # stop or display help for this plugin
    if parts['action'] in ['show', 'stop', 'help']:
        handle_action = {
            'show': _show_all_reminders,
            'stop': _stop_reminder,
            'help': _show_help,
        }

        # Handle and return the returned message
        return handle_action[parts['action']](message)

    # Fake a small case-like statement for the once or
    # every message types
    handle_recurrence_types = {
        'once': _set_once_reminder,
        'every': _set_recurring_reminder
    }

    # Run the appropriate set function
    handle_recurrence_types[parts['recurrence']](parts, message)

    # Respond with the fact that the reminder is set.
    response = 'Reminder set for: {t} with message: {m}'.format(
        t = parts['parsed_time'],
        m = parts['message']
    )

    return response


text:
package org.jibx.runtime;

import java.io.IOException;

/**
 * Extensible version of standard XML writer interface. This allows the creation
 * of child writer instances with added namespaces.
 *
 * @author Dennis M. Sosnoski
 */
public interface IExtensibleWriter extends IXMLWriter
{
    /**
     * Create a child writer instance to be used for a separate binding. The
     * child writer inherits the output handling from this writer, while using
     * the supplied namespace URIs.
     *
     * @param uris ordered array of URIs for namespaces used in document
     * @return child writer
     * @throws IOException
     */
    IXMLWriter createChildWriter(String[] uris) throws IOException;
}

redpajama_set_name: RedPajamaGithub


text:
using AdEvade.Config;
using AdEvade.Config.Controls;
using EloBuddy.SDK.Menu.Values;

namespace AdEvade.Helpers
{
    public static class MenuHelpers
    {
        public static ValueBase<T> Add<T>(this EloBuddy.SDK.Menu.Menu menu, IDynamicControl<T> item)
        {
            return menu.Add(item.GetConfigValue().Name(), item.GetControl());
        }
    }
}


text:
package com.google.common.css.compiler.ast;

import com.google.common.css.SourceCodeLocation;

import javax.annotation.Nullable;

/**
 * A node that represent a unicode range.
 *
 *
See  for details.
 */
public class CssUnicodeRangeNode extends CssValueNode {

  public CssUnicodeRangeNode(String value, @Nullable SourceCodeLocation sourceCodeLocation) {
    super(value, sourceCodeLocation);
  }

  public CssUnicodeRangeNode(String value) {
    this(value, null);
  }

  public CssUnicodeRangeNode(CssUnicodeRangeNode node) {
    super(node);
  }

  @Override
  public CssUnicodeRangeNode deepCopy() {
    return new CssUnicodeRangeNode(this);
  }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <barrelfish/barrelfish.h>

#include "ohci_device.h"

#include <usb/usb.h>
#include <usb/usb_descriptor.h>
#include <usb/usb_error.h>
#include <usb/usb_request.h>
#include <usb_device.h>
#include <usb_hub.h>
#include <usb_controller.h>
#include "usb_ohci.h"
#include "usb_ohci_root_hub.h"

static const struct usb_device_descriptor usb_ohci_root_hub_device_desc = {
        .bLength = sizeof(struct usb_device_descriptor),
        .bDescriptorType = USB_DESCRIPTOR_TYPE_DEVICE,
        .bcdUSB = 0x0100,
        .bDeviceClass = USB_HUB_CLASS_CODE,
        .bDeviceSubClass = USB_HUB_SUBCLASS_CODE,
        .bDeviceProtocol = USB_HUB_PROTOCOL_FSHUB,
        .bMaxPacketSize0 = 64,
        .idVendor = 0,
        .idProduct = 0,
        .bcdDevice = 0x0100,
        .iManufacturer = 1,
        .iProduct = 2,
        .iSerialNumber = 0,
        .bNumConfigurations = 1,
};

static const struct usb_ohci_config_desc usb_ohci_root_hub_config_desc = {
.config_desc = {
        .bLength = sizeof(struct usb_config_descriptor),
        .bDescriptorType = USB_DESCRIPTOR_TYPE_CONFIG,
        .wTotalLength = sizeof(usb_ohci_root_hub_config_desc),
        .bNumInterfaces = 1,
        .bConfigurationValue = 1,
        .iConfiguration = 0,
        .bmAttributes = USB_CONFIG_SELF_POWERED,
        .bMaxPower = 0,
}, .iface_desc = {
.bLength = sizeof(struct usb_interface_descriptor), .bDescriptorType =
        USB_DESCRIPTOR_TYPE_INTERFACE, .bNumEndpoints = 1, .bInterfaceClass =
        USB_HUB_IFACE_CLASS_CODE, .bInterfaceSubClass =
        USB_HUB_IFACE_SUBCLASS_CODE, .bInterfaceProtocol = 0,
}, .ep_desc = {
        .bLength = sizeof(struct usb_endpoint_descriptor),
        .bDescriptorType = USB_DESCRIPTOR_TYPE_ENDPOINT,
        .bEndpointAddress = {USB_ENDPOINT_DIRECTION_IN,0,1},
        .bmAttributes = {0,0,0,USB_ENDPOINT_TYPE_INTR},
        .wMaxPacketSize = 32,
        .bInterval = 255,
},
};

static const struct usb_hub_descriptor usb_ohci_root_hub_desc = {
        .bDescLength = 0,
        .bDescriptorType = USB_DESCRIPTOR_TYPE_HUB,
        .bNbrPorts = 0,
        .wHubCharacteristics = {0, 0, 0, 0, 0, 0},
        .bPwrOn2PwrGood = 0,
        .bHubContrCurrent = 0,
        .bDeviceRemovable =     {0}
};

/**
 * \brief   this function clears the old interrupt data and reads the
 *          status from the ports
 *
 * \param   hc  the host controller
 */
void usb_ohci_root_hub_interrupt(usb_ohci_hc_t *hc)
{
    /* clear old interrupt data */
    memset(hc->root_hub_intr_data, 0, sizeof(hc->root_hub_intr_data));

    /* get the root hub status */
    //ohci_rh_status_t hstatus = ohci_rh_status_rd(hc->ohci_base);

    /* get the number of ports */
    uint16_t num_ports = hc->root_hub_num_ports + 1;
    if (num_ports > (8 * sizeof(hc->root_hub_intr_data))) {
        num_ports = (8 * sizeof(hc->root_hub_intr_data));
    }

    //char buf[4048];
        //     ohci_rh_portstat_pr(buf, 4047, hc->ohci_base);
          //  printf(buf);
    ohci_rh_portstat_t ps;
    /* set the bits in the interrupt data field */
    for (uint16_t i = 0; i < num_ports; i++) {

        ps = ohci_rh_portstat_rd(hc->ohci_base, i);
        if (ps >> 16) {
            /* port i has changed */
            USB_DEBUG("port %u, has changed..\n", i);
            hc->root_hub_intr_data[i / 8] |= (1 << (i % 8));
        }
    }

    /* TODO: Handle the hub interrupts */
   // assert(!"NYI: Root hub interrupt handling");
    //uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata, sizeof(sc->sc_hub_idata));
}

/*
 * \brief   this function enables the status change interrupt
 *          of the root hub and updates the enabled_intrs field
 *          of the host controller.
 *
 * \param   hc  the host controller
 */
static void usb_ohci_root_hub_sc_intr_enable(usb_ohci_hc_t *hc)
{
    /* update the enabled interrupt field in our hc */
    ohci_interrupt_t ie = ohci_intenable_rd(hc->ohci_base);
    ohci_interrupt_rhsc_insert(ie, 1);
    hc->enabled_intrs = ie;

    /* enable the interrupt */
    ohci_intenable_rhsc_wrf(hc->ohci_base, 1);

    /* acknowledge any RHSC interrupts */
    ohci_intstatus_rhsc_wrf(hc->ohci_base, 1);

    usb_ohci_root_hub_interrupt(hc);
}

/**
 *  \brief  this function emulates the USB root hub device by software
 *
 *  \param  device      the USB device we want to issue the request for
 *  \param  req         the USB request to execute
 *  \param  ret_data    pointer to the returned data
 *  \param  ret_length  the returned length
 */
usb_error_t usb_ohci_roothub_exec(struct usb_device *device,
        struct usb_device_request *req, const void **ret_data,
        uint16_t *ret_length)
{
    usb_ohci_hc_t *hc = (usb_ohci_hc_t *) device->controller->hc_control;

    const void *data = (const void *) hc->root_hub_desc.temp;
    uint16_t length = 0;

    uint16_t req_value = req->wValue;
    uint16_t req_index = req->wIndex;

    const char *str_ptr;

    /*
     * execute the request for the USB root hub
     */
    switch (req->bRequest) {

        case USB_REQUEST_CLEAR_FEATURE:
            /*
             * ClearFeature() Request
             *
             * The only clear feature request is the clear port feature
             * for an existing port 1..num_ports
             */
            if (req->bType.recipient == USB_REQUEST_RECIPIENT_OTHER) {
                if ((req_index < 1) || (req_index > hc->root_hub_num_ports)) {
                    *ret_length = length;
                    *ret_data = data;
                    return USB_ERR_IOERROR;
                }
                // get the current value of the register
                ohci_rh_portstat_t ps = ohci_rh_portstat_rd(hc->ohci_base,
                        req_index);

                switch (req_value) {
                    case USB_HUB_FEATURE_PORT_ENABLE:
                        ohci_rh_portstat_ccs_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_PORT_SUSPEND:
                        ohci_rh_portstat_poci_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_PORT_POWER:
                        ohci_rh_portstat_lsda_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_C_PORT_CONNECTION:
                        ohci_rh_portstat_csc_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_C_PORT_ENABLE:
                        ohci_rh_portstat_pesc_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_C_PORT_SUSPEND:
                        ohci_rh_portstat_pssc_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_C_PORT_OVER_CURRENT:
                        ohci_rh_portstat_ocic_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_C_PORT_RESET:
                        ohci_rh_portstat_prsc_insert(ps, 1);
                        break;
                    default:
                        *ret_length = length;
                        *ret_data = data;
                        return USB_ERR_IOERROR;
                }
                // write the value to the register
                ohci_rh_portstat_rawwr(hc->ohci_base, req_index, ps);

                switch (req_value) {
                    case USB_HUB_FEATURE_C_PORT_CONNECTION:
                    case USB_HUB_FEATURE_C_PORT_ENABLE:
                    case USB_HUB_FEATURE_C_PORT_SUSPEND:
                    case USB_HUB_FEATURE_C_PORT_OVER_CURRENT:
                    case USB_HUB_FEATURE_C_PORT_RESET:
                        ps = ohci_rh_portstat_rd(hc->ohci_base, req_index);
                        if ((ps >> 16) == 0) {
                            usb_ohci_root_hub_sc_intr_enable(hc);
                        }
                        break;
                    default:
                        break;
                }
            }
            break;

        case USB_REQUEST_GET_CONFIG:
            /*
             * GetConfiguration() Request
             */
            if ((req->bType.recipient == USB_REQUEST_RECIPIENT_DEVICE)
                    && req->bType.direction == USB_REQUEST_READ) {
                length = 1;
                hc->root_hub_desc.temp[0] = hc->root_hub_config;
            }
            break;

        case USB_REQUEST_GET_DESCRIPTOR:
            /*
             * GetDescriptor() Request
             *
             * There are 3 different kind of standard descriptors we can
             * return: Device, Interface and String
             *
             * and also a class specific request
             */
            if ((req->bType.recipient == USB_REQUEST_RECIPIENT_DEVICE)
                    && req->bType.direction == USB_REQUEST_READ) {

                /* hub class specific request */
                if (req->bType.type == USB_REQUEST_TYPE_CLASS) {
                    if ((req_value & 0xFF) != 0) {
                        *ret_length = length;
                        *ret_data = data;
                        return USB_ERR_IOERROR;
                    }
                    ohci_rh_descra_t cda;
                    cda = ohci_rh_descra_rd(hc->ohci_base);

                    // get the standard hub descriptor to fill in data
                    hc->root_hub_desc.hub_descriptor = usb_ohci_root_hub_desc;

                    struct usb_hub_descriptor *hub = &(hc->root_hub_desc
                            .hub_descriptor);
                    hub->bNbrPorts = hc->root_hub_num_ports;

                    hub->wHubCharacteristics.power_mode =
                            ohci_rh_descra_nps_extract(cda);
                    hub->bPwrOn2PwrGood = ohci_rh_descra_potpgt_extract(cda);

                    /* update device removable stats */
                    ohci_rh_descra_t cdb;
                    cdb = ohci_rh_descrb_rd(hc->ohci_base);
                    for (uint16_t i = 0; i < hc->root_hub_num_ports; i++) {
                        if (cdb & 1) {
                            hub->bDeviceRemovable[i / 8] |= (1 << (i % 8));
                        }
                        i >>= 1;
                    }
                    hub->bDescLength = 8 + ((hc->root_hub_num_ports + 7 / 8));
                    length = hub->bDescLength;
                    break;
                }
                /* standard usb request */
                switch (req_value >> 8) {
                    case USB_DESCRIPTOR_TYPE_DEVICE:
                        if ((req_value & 0xFF) != 0) {
                            *ret_length = length;
                            *ret_data = data;
                            return USB_ERR_IOERROR;
                        }
                        length = sizeof(usb_ohci_root_hub_device_desc);
                        data = (const void *) &usb_ohci_root_hub_device_desc;
                        break;
                    case USB_DESCRIPTOR_TYPE_CONFIG:
                        if ((req_value & 0xFF) != 0) {
                            *ret_length = length;
                            *ret_data = data;
                            return USB_ERR_IOERROR;
                        }
                        length = sizeof(usb_ohci_root_hub_config_desc);
                        data = (const void *) &usb_ohci_root_hub_config_desc;
                        break;
                    case USB_DESCRIPTOR_TYPE_STRING:
                        switch (req_value & 0xFF) {
                            case 0:
                                str_ptr = "\001";
                                break;
                            case 1:
                                break;
                                str_ptr = hc->vendor;
                            case 2:
                                break;
                                str_ptr = "OHCI root HUB";
                            default:
                                str_ptr = "";
                                break;
                        }
                        /* TODO: Make string descriptor */
                        assert(!"NYI: Make string descriptor");
                        break;
                    default:
                        *ret_length = length;
                        *ret_data = data;
                        return USB_ERR_IOERROR;
                        break;
                }
            }
            break;

        case USB_REQUEST_GET_INTERFACE:
            /*
             * GetInterface() Request
             *
             * Root hub has just one interface and no alternative one
             */
            if ((req->bType.recipient == USB_REQUEST_RECIPIENT_DEVICE)
                    && req->bType.direction == USB_REQUEST_READ) {
                length = 1;
                hc->root_hub_desc.temp[0] = 0;
            }
            break;

        case USB_REQUEST_GET_STATUS:
            /*
             * GetStatus() Request
             */
            if (req->bType.direction == USB_REQUEST_WRITE) {
                *ret_data = data;
                *ret_length = length;
                return USB_ERR_IOERROR;
            }

            if (req->bType.type == USB_REQUEST_TYPE_CLASS) {
                if (req->bType.recipient == USB_REQUEST_RECIPIENT_DEVICE) {
                    length = 16;
                    memset(hc->root_hub_desc.temp, 0, 16);
                    break;
                } else if (req->bType.recipient == USB_REQUEST_RECIPIENT_OTHER) {
                    /* get port status */
                    if ((req_index < 1) || req_index > hc->root_hub_num_ports) {
                        // invalid port number;
                        *ret_length = length;
                        *ret_data = data;
                        return USB_ERR_IOERROR;
                    }
                    ohci_rh_portstat_t ps = ohci_rh_portstat_rawrd(
                            hc->ohci_base, req_index);
                    memcpy(&hc->root_hub_desc.port_status.wPortChange, &ps, 2);
                    ps <<= 16;
                    memcpy(&hc->root_hub_desc.port_status.wPortStatus, &ps, 2);
                    //hc->root_hub_desc.port_status.wPortChange = (ps >> 16);
                    //hc->root_hub_desc.port_status.wPortStatus = (ps & 0xFFFF);
                    length = sizeof(hc->root_hub_desc.port_status);
                    break;
                }
            }

            if ((req->bType.recipient == USB_REQUEST_RECIPIENT_DEVICE)) {
                length = 2;
                hc->root_hub_desc.status.wStatus = USB_STATUS_SELF_POWERED;
            } else {
                length = 2;
                hc->root_hub_desc.status.wStatus = 0;
            }

            break;

        case USB_REQUEST_SET_ADDRESS:
            /*
             * SetAddress() Request
             *
             * we can set the address of the root hub if it is
             * withint the maximum devices range
             */
            if (req_value > USB_OHCI_MAX_DEVICES) {
                *ret_length = length;
                *ret_data = data;
                return USB_ERR_IOERROR;
            }
            hc->root_hub_address = req_value;
            break;

        case USB_REQUEST_SET_CONFIG:
            /*
             * SetConfiguration() Request
             *
             * We have only two two options (0, 1) that we can set
             */
            if (req_value > 1) {
                *ret_length = length;
                *ret_data = data;
                return USB_ERR_IOERROR;
            }
            hc->root_hub_config = req_value;
            break;

        case USB_REQUEST_SET_DESCRIPTOR:
            /*
             * SetDescriptor() Request
             *
             * We do not allow to change the USB root hub descriptor
             * so this is a no-op for standard requests
             *
             * but is is an error for hub class requests
             */
            if (req->bType.type == USB_REQUEST_TYPE_CLASS) {
                *ret_length = length;
                *ret_data = data;
                return USB_ERR_IOERROR;
            }
            break;

        case USB_REQUEST_SET_FEATURE:
            /*
             * SetFeature() Request
             *
             * Setting a feature on the root hub is an error,
             * so we reply with USB_ERR_IOERROR
             */
            if (req->bType.type != USB_REQUEST_TYPE_CLASS) {
                *ret_length = length;
                *ret_data = data;
                return USB_ERR_IOERROR;
                break;
            }
            /* handling of hub cpass specific port request */

            if (req->bType.recipient == USB_REQUEST_RECIPIENT_OTHER) {
                if ((req_index < 1) || (req_index > hc->root_hub_num_ports)) {
                    *ret_length = length;
                    *ret_data = data;
                    return USB_ERR_IOERROR;
                    break;
                }
                ohci_rh_portstat_t ps = ohci_rh_portstat_rawrd(hc->ohci_base,
                        req_index);
                switch (req_value) {
                    case USB_HUB_FEATURE_PORT_ENABLE:
                        ohci_rh_portstat_pes_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_PORT_SUSPEND:
                        ohci_rh_portstat_pss_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_PORT_RESET:
                        ohci_rh_portstat_prs_insert(ps, 1);
                        break;
                    case USB_HUB_FEATURE_PORT_POWER:
                        ohci_rh_portstat_pps_insert(ps, 1);
                        break;
                    default:
                        *ret_length = length;
                        *ret_data = data;
                        return USB_ERR_IOERROR;
                        break;
                }
                ohci_rh_portstat_rawwr(hc->ohci_base, req_index, ps);
                /*
                 * handle the reset of the port
                 */
                if (req_value == USB_HUB_FEATURE_PORT_RESET) {
                    for (uint32_t i = 0;; i++) {
                        if (ohci_rh_portstat_prs_rdf(hc->ohci_base,
                                req_index)) {
                            /*
                             * bit has not been cleared, that means the
                             * reset is not completed yet
                             */
                            /* TODO: WAIT SOME TIME */
                            if (i > 12) {
                                *ret_data = data;
                                *ret_length = length;
                                return USB_ERR_TIMEOUT;
                            }
                        } else {
                            // reset complete
                            break;
                        }
                    }
                }
            }
            break;

        case USB_REQUEST_SET_INTERFACE:
            /*
             * SetInterface() Request
             *
             * we have just one interface, so this is a no-op
             */
            break;

        case USB_REQUEST_SYNCH_FRAME:
            /*
             * SetSynchFrame() Request
             *
             * No-op
             */
            break;
        default:
            *ret_length = length;
            *ret_data = data;
            return USB_ERR_IOERROR;
            break;
    }
    *ret_length = length;
    *ret_data = data;
    return USB_ERR_OK;
}


text:
This file holds style specific markup and coding things.

## Code things

#### Variables

Trying to keep things modular, all variables follow this simple scheme. If it is used in multiple files, it goes in the `variables.styl` file with a general object name like 'size' or 'colors'. If it is only used in one place, the it goes in the respective file under 'local variables' section with the object name of that file (`$type = {}`).

#### Types

To keep things all organized, we have split different files into different folders depending on there role. Here is the breakdown:

##### base/
Used for all site wide things that would be odd in another category. Will not be used for much besides the global reset and global css.

##### component/
Used for objects that change layout like a grid or group of elements. These objects don't have an interface on there own.

##### element/
Used for native html elements like `img` or `input`.

##### page/
Used for page specific styling. These pages will compile in an unique file.

##### widget/
used for objects that are not native html but offer a gui. Examples include an `avatar` style


text:
module Plugins.StdinReader where

import Prelude
import System.Posix.Process
import System.Exit
import System.IO
import Control.Exception (SomeException(..), handle)
import Plugins
import Actions (stripActions)

data StdinReader = StdinReader deriving (Read, Show)

instance Exec StdinReader where
  start StdinReader cb = do
    s <- handle (\(SomeException e) -> do hPrint stderr e; return "")
                (hGetLineSafe stdin)
    cb (stripActions s)
    eof <- hIsEOF stdin
    if eof
      then exitImmediately ExitSuccess
      else start StdinReader cb


text:
Graphite for Monitoring
===============

[German / Deutsch](LIESMICH.md)

This project creates a VM with the application in a Docker container
and a separate Docker container for Graphite. Graphite can be used as
a monitoring tool for the application.

To run:

- Install Vagrant as discussed at
  http://docs.vagrantup.com/v2/installation/index.html
- Install Virtual Box from https://www.virtualbox.org/wiki/Downloads
- Go to parent directory and run `mvn install` there
- Change to the directoriy containing this README.MD and run `vagrant
   up`

The result should be:

- A new VirtualBox VM is fired up by Vagrant
- Docker is installed in the VM
- You can access the application at http://localhost:8083/
- You can access Graphite  at http://localhost:8082/
- Graphite's port to add data to the monitoring is also exposed at 2003


text:
package com.wrq.rearranger.util;

import java.awt.*;

/**
 * Utility class for performing common operations on GridBagConstraints.
 */
public class Constraints
        extends GridBagConstraints
{
    boolean newRow;

    /**
     * Constructs a new Constraints object and initializes a new row.

      * Side effects are:
     *

     *    gridy = 0
     *    gridx = 0
     *    gridheight = 1
     *    gridwidth = 1
     *    weightx = 0
     *    weighty = 0
     *    fill = NONE
     *    anchor = WEST
     *

     */
    public Constraints()
    {
        fill = GridBagConstraints.NONE;
        gridwidth = 1;
        gridheight = 1;
        anchor = GridBagConstraints.WEST;
        weightx = 0.0d;
        weighty = 0.0d;
        gridx = gridy = 0;
        newRow = true;
        newRow();
    }

   /**
     * Constructs a new Constraints object and initializes a new row.

      * Side effects are:
     *

     *    gridy = 0
     *    gridx = 0
     *    gridheight = 1
     *    gridwidth = 1
     *    weightx = 0
     *    weighty = 0
     *    fill = NONE
     *    anchor = specified parameter
     *

     */     public Constraints(int anchor)
    {
        this();
        this.anchor = anchor;
    }

    /**
     * Prepares for adding components to a new row.

     * Side effects are:
     *

     *    gridy++ (if not already at the beginning of a new row)
     *    gridx = 0
     *    gridheight = 1
     *    weighty = 0
     *

     */
    public void newRow()
    {
        if (!newRow)
            gridy++;
        gridx = 0;
        gridheight = 1;
        weighty = 0;
        newRow = true;
    }

    /**
     * Prepares for adding components to a new row, which is weighted.

     * Side effects are:
     *

     *    gridy++ (if not the first row)
     *    gridx = 0
     *    gridheight = 1
     *    weighty = supplied parameter
     *

     */
    public void weightedNewRow(double weight)
    {
        newRow();
        weighty = weight;
    }

    /**
     * Prepares for adding components to a new row, which is weighted.

     * Side effects are:
     *

     *    gridy++ (if not the first row)
     *    gridx = 0
     *    gridheight = 1
     *    weighty = 1
     *

     */
    public void weightedNewRow()
    {
        weightedNewRow(1);
    }

    /**
     * Prepares for adding components to a new row which will be the last row.

     * Side effects are:
     *

     *    gridy++ (if not the first row)
     *    gridx = 0
     *    gridheight = REMAINDER
     *    weighty = 0
     *

     */
    public void lastRow()
    {
        newRow();
        gridheight = REMAINDER;
    }

     /**
     * Prepares for adding components to a new weightd row which will be the last row.

     * Side effects are:
     *

     *    gridy++ (if not the first row)
     *    gridx = 0
     *    gridheight = REMAINDER
     *    weighty = supplied parameter
     *

     */
    public void weightedLastRow(double weight)
    {
        lastRow();
        weighty = weight;
    }

    /**
     * Prepares for adding components to a new weightd row which will be the last row.

     * Side effects are:
     *

     *    gridy++ (if not the first row)
     *    gridx = 0
     *    gridheight = REMAINDER
     *    weighty = 1
     *

     */
    public void weightedLastRow()
    {
        weightedLastRow(1);
    }

    /**
     * Automatically starts a new row if not explicitly done already or if columns have been added since the last
     * newRow() call.

     * Side effects are:
     *

     *    gridx = 0
     *    newRow = false
     *    gridwidth = 1
     *    weightx = 0
     *

     * @return this Constraints object
     */
    public Constraints firstCol()
    {
        if (!newRow)
        {
            newRow();
        }
        gridx = 0;
        newRow = false;
        gridwidth = 1;
        weightx = 0;
        return this;
    }

    /**
     * Automatically starts a new weighted row if not explicitly done already or if columns have been added since the last
     * newRow() call.

     * Side effects are:
     *

     *    gridx = 0
     *    newRow = false
     *    gridwidth = 1
     *    weightx = 1
     *

     * @return this Constraints object
     */
    public Constraints weightedFirstCol()
    {
        firstCol();
        weightx = 1;
        return this;
    }

    /**
     * Prepares to add a component to the next column.  If this is the first column in the row,
     * gridx will be zero (not one).

     * Side effects are:
     *

     *    gridx = gridx + 1 (or zero, if this is the beginning of a new row)
     *    newRow = false
     *    gridwidth = 1
     *    weightx = 0
     *

     * @return this Constraints object
     */
    public Constraints nextCol()
    {
        gridx = newRow ? 0 : gridx + 1;
        newRow = false;
        gridwidth = 1;
        weightx = 0;
        return this;
    }

    /**
     * Prepares to add a weighted component to the next column.

     * Side effects are:
     *

     *    gridx = gridx + 1 (or zero, if this is the beginning of a new row)
     *    newRow = false
     *    gridwidth = 1
     *    weightx = supplied parameter
     *

     * @return this Constraints object
     */
    public Constraints weightedNextCol(double weight)
    {
        nextCol();
        weightx = weight;
        return this;
    }

    /**
     * Prepares to add a weighted component to the next column.

     * Side effects are:
     *

     *    gridx = gridx + 1 (or zero, if this is the beginning of a new row)
     *    newRow = false
     *    gridwidth = 1
     *    weightx = 1
     *

     * @return this Constraints object
     */
    public Constraints weightedNextCol()
    {
        return weightedNextCol(1);
    }

    /**
     * Prepares to add a component to the last column.

     * Side effects are:
     *

     *    gridx = gridx + 1 (or zero, if this is the beginning of a new row)
     *    newRow = false
     *    gridwidth = REMAINDER
     *    weightx = 0
     *

     * @return this Constraints object
     */
    public Constraints lastCol()
    {
        nextCol();
        gridwidth = REMAINDER;
        return this;
    }

    /**
     * Prepares to add a weighted component to the last column.

     * Side effects are:
     *

     *    gridx = gridx + 1 (or zero, if this is the beginning of a new row)
     *    newRow = false
     *    gridwidth = REMAINDER
     *    weightx = supplied parameter
     *

     * @return this Constraints object
     */
    public Constraints weightedLastCol(double weight)
    {
        weightedNextCol(weight);
        gridwidth = REMAINDER;
        return this;
    }

    /**
     * Prepares to add a weighted component to the last column.

     * Side effects are:
     *

     *    gridx = gridx + 1 (or zero, if this is the beginning of a new row)
     *    newRow = false
     *    gridwidth = REMAINDER
     *    weightx = 1
     *

     * @return this Constraints object
     */
    public Constraints weightedLastCol()
    {
        weightedLastCol(1);
        gridwidth = REMAINDER;
        return this;
    }
}


text:
function Tile(args) {
	args = args ? args : {};
	this.value = args.value || 0
}

Tile.prototype.randomizeTile = function(){
	var random = _.sample([2, 4])
	this.value = random
}

function Game(args) {
	args = args ? args : {};
	this.tiles = args.tiles || [
		[new Tile, new Tile, new Tile, new Tile],
		[new Tile, new Tile, new Tile, new Tile],
		[new Tile, new Tile, new Tile, new Tile],
		[new Tile, new Tile, new Tile, new Tile]
	]
	this.score = 0
}

Game.prototype.reset = function(){
	this.tiles = [
		[new Tile, new Tile, new Tile, new Tile],
		[new Tile, new Tile, new Tile, new Tile],
		[new Tile, new Tile, new Tile, new Tile],
		[new Tile, new Tile, new Tile, new Tile]
	]
	this.score = 0;
}

Game.prototype.start = function(){
	this.reset();
	var indices = [0,1,2,3];

	var rowIndex1 = _.sample(indices);
	var rowIndex2 = _.sample(indices);
	var tileIndex1 = _.sample(indices);
	var	tileIndex2 = _.sample(indices);
	while(tileIndex2 === tileIndex1 && rowIndex1 === rowIndex2){
		rowIndex2 = _.sample(indices);
		tileIndex2 = _.sample(indices);
	}

	this.tiles[rowIndex1][tileIndex1].randomizeTile();
	this.tiles[rowIndex2][tileIndex2].randomizeTile();
}

Game.prototype.toString = function(){
	_.each(this.tiles, function(row){
		console.log(row[0].value + '|' + row[1].value + '|' + row[2].value + '|' + row[3].value);
	})
	console.log('---------------')
}

Game.prototype.zipRight = function(){
	_.each(this.tiles, function(row){
		_.each(row, function(tile, i){
			if(tile.value === 0){
				row.splice(i, 1);
				while(row.length < 4){
					row.unshift(new Tile);
				}
			}
		})
	})
}

Game.prototype.addRight = function(){
	var game = this
	_.each(this.tiles, function(row){
		for(var i = row.length - 1; i >= 0; i --){
			if(i > 0 && row[i].value != 0 && row[i].value === row[i - 1].value){
				var combined = row[i].value + row[i - 1].value;
				game.score += combined;
				row[i].value = combined;
				row[i - 1].value = 0;
				game.zipRight();
			}
		}
	})
}

function zipCloneRight(clone) {
	_.each(clone, function(row){
		_.each(row, function(tile, i){
			if(tile.value === 0){
				row.splice(i, 1);
				while(row.length < 4){
					row.unshift(new Tile);
				}
			}
		})
	})
	_.each(clone, function(row){
		for(var i = row.length - 1; i >= 0; i --){
			if(i > 0 && row[i].value != 0 && row[i].value === row[i - 1].value){
				var combined = row[i].value + row[i - 1].value;
				row[i].value = combined;
				row[i - 1].value = 0;
				_.each(clone, function(row){
					_.each(row, function(tile, i){
						if(tile.value === 0){
							row.splice(i, 1);
							while(row.length < 4){
							row.unshift(new Tile);
							}
						}
					})
				})
			}
		}
	})
	return clone;
}

Game.prototype.canZipRight = function(){
	var tileJson = JSON.stringify(this.tiles)
	var clone = JSON.parse(JSON.stringify(this.tiles));
	zipCloneRight(clone)
	return !(tileJson == JSON.stringify(clone));
}

Game.prototype.canZipLeft = function(){
	var tileJson = JSON.stringify(this.tiles)
	var clone = JSON.parse(JSON.stringify(this.tiles));
	_.each(clone, function(row){
		row.reverse();
	});
	zipCloneRight(clone);
	_.each(clone, function(row){
		row.reverse();
	});
	return !(tileJson == JSON.stringify(clone));
}

Game.prototype.canZipUp = function(){
	var tileJson = JSON.stringify(this.tiles)
	var clone = JSON.parse(JSON.stringify(this.tiles));
	clone = _.zip.apply(_, clone);
	_.each(clone, function(row){
		row.reverse();
	});
	zipCloneRight(clone);
	_.each(clone, function(row){
		row.reverse();
	});
	clone = _.zip.apply(_, clone);
	return !(tileJson == JSON.stringify(clone));
}

Game.prototype.canZipDown = function(){
	var tileJson = JSON.stringify(this.tiles)
	var clone = JSON.parse(JSON.stringify(this.tiles));
	clone = _.zip.apply(_, clone);
	zipCloneRight(clone);
	clone = _.zip.apply(_, clone);
	return !(tileJson == JSON.stringify(clone));
}

Game.prototype.canMove = function(){
	if(this.canZipRight() === true || this.canZipLeft() === true || this.canZipUp() === true || this.canZipDown() === true){
		return true;
	} else {
		return false;
	}
}

Game.prototype.insertRandom = function(){
	var Indices = [0,1,2,3];

	var rowIndex = _.sample(Indices);
	var tileIndex = _.sample(Indices);

	while(this.tiles[rowIndex][tileIndex].value != 0){
		rowIndex = _.sample(Indices);
		tileIndex = _.sample(Indices);
	}
		this.tiles[rowIndex][tileIndex].randomizeTile();
}

Game.prototype.moveRight = function(){
	if(this.canZipRight() === true){
			this.zipRight();
			this.addRight();
			this.insertRandom();
		};
}

Game.prototype.move = function(direction){
	if(direction === 'right'){
		this.moveRight();
		this.toString();
	}
	if(direction === 'left'){
		_.each(this.tiles, function(row){
			row.reverse();
		});
		this.moveRight();
		_.each(this.tiles, function(row){
			row.reverse();
		})
		this.toString();
	}
	if(direction === 'up'){
		this.tiles = _.zip.apply(_, this.tiles)
		_.each(this.tiles, function(row){
			row.reverse();
		});
		this.moveRight();
		_.each(this.tiles, function(row){
			row.reverse();
		});
		this.tiles = _.zip.apply(_, this.tiles)
		this.toString();
	}
	if(direction === 'down'){
		this.tiles = _.zip.apply(_, this.tiles)
		this.moveRight();
		this.tiles = _.zip.apply(_, this.tiles)
		this.toString();
	}
}

Game.prototype.bindDir = function(keys, dir){
	Mousetrap.bind(keys, function(e){
		this.move(dir)
	}.bind(this))
}

Game.prototype.bindAll = function(){
	this.bindDir(['right'], 'right');
	this.bindDir(['left'], 'left');
	this.bindDir(['up'], 'up');
	this.bindDir(['down'], 'down');
}


text:
<html>
<head>
<title></title>
<script>
  var assert = xwalk.app.test.assert;
  var getManifestTest = function(resolve) {
    xwalk.app.runtime.getManifest(function(manifest) {
      assert(manifest);
      assert(manifest.name === "xwalk.app API Test");
      assert(manifest.version === "1.0");
      assert(manifest.manifest_version === 1);
      resolve();
    });
  };

  var tests = [
    getManifestTest,
  ];

  function onLoad() {
    xwalk.app.test.runTests(tests, 10000);
  }

</script>
</head>
<body onload = "onLoad()">
</body>
</html>


text:
name              "config-driven-helper"
maintainer        "Inviqa"
maintainer_email  "athompson@inviqa.com"
issues_url        "https://github.com/inviqa/chef-config-driven-helper/issues"
source_url        "https://github.com/inviqa/chef-config-driven-helper"
license           "Apache 2.0"
description       "enable driving cookbooks that are not normally config driven to be so"
version           "3.2.0"

depends "apache2", ">= 1.8"
depends 'iptables-ng', '>= 2.2'
depends "mysql", "~> 4.0"
depends 'nginx', '< 2.4.4'
depends "database", "~> 2.0.0"
depends "build-essential", "~> 1.4"

%w{ debian ubuntu centos redhat fedora scientific amazon windows }.each do |os|
  supports os
end

recipe "apache-sites", "Propagates sites from node config to web_app"
recipe "nginx-sites", "Propagates sites from node config to nginx site"
recipe "mysql-users", "Creates mysql users using the database cookbook"
recipe "mysql-ruby", "Installs MySQL ruby gem in chef ruby"
recipe "mysql-databases", "Creates mysql databases using the database cookbook"
recipe "packages-additional", "Installs packages"
recipe "services", "Enables service actions"


text:
layout: post
title: SDDM 0.13.0
author: plfiorini
permalink: /news/2015/11/04/sddm-0.13.0/
---

We are proud to announce the immediate availability of [SDDM](https://github.com/sddm/sddm) 0.13.0.

<!-- more -->

Change log:

* Greeter inherits path environment variables from parent so that themes installed in non-standard paths will work.
* Add ENABLE_PAM option to toggle PAM support at build time.
* Allow overriding textColor in ComboBox.
* Don't cast QByteArray to (char *).
* Disable greeters from loading KDE's debug hander (fix CVE-2015-0856).
* Fix multi-screen support for some setups.
* Added Serbian translation.
* Added Traditional Chinese translation.
* Improved German translation.
* Remove failsafe session entry.
* Close the pipe fd passed to X server.
* A few micro-optimizations.

More information can be found [here](https://github.com/sddm/sddm/wiki/0.13.0-Release-Announcement).

Sources and SHA1 hashes follow:

 * [sddm-0.13.0.tar.xz](https://github.com/sddm/sddm/releases/download/v0.13.0/sddm-0.13.0.tar.xz) (SHA1: 0e022f8eed64307a2ca8536c71204954c2858106)
 * [sddm-0.13.0.tar.gz](https://github.com/sddm/sddm/releases/download/v0.13.0/sddm-0.13.0.tar.gz) (SHA1: dcb5328b222cbf34f70956415a4da2017620b0c9)


text:
package com.example.android.waitlist;

import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.android.waitlist.data.WaitlistContract;

public class GuestListAdapter extends RecyclerView.Adapter<GuestListAdapter.GuestViewHolder> {

    // Holds on to the cursor to display the waitlist
    private Cursor mCursor;
    private Context mContext;

    /**
     * Constructor using the context and the db cursor
     * @param context the calling context/activity
     * @param cursor the db cursor with waitlist data to display
     */
    public GuestListAdapter(Context context, Cursor cursor) {
        this.mContext = context;
        this.mCursor = cursor;
    }

    @Override
    public GuestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Get the RecyclerView item layout
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.guest_list_item, parent, false);
        return new GuestViewHolder(view);
    }

    @Override
    public void onBindViewHolder(GuestViewHolder holder, int position) {
        // Move the mCursor to the position of the item to be displayed
        if (!mCursor.moveToPosition(position))
            return; // bail if returned null

        // Update the view holder with the information needed to display
        String name = mCursor.getString(mCursor.getColumnIndex(WaitlistContract.WaitlistEntry.COLUMN_GUEST_NAME));
        int partySize = mCursor.getInt(mCursor.getColumnIndex(WaitlistContract.WaitlistEntry.COLUMN_PARTY_SIZE));
        // TODO (6) Retrieve the id from the cursor and
        long id = mCursor.getLong(mCursor.getColumnIndex(WaitlistContract.WaitlistEntry._ID));

        // Display the guest name
        holder.nameTextView.setText(name);
        // Display the party count
        holder.partySizeTextView.setText(String.valueOf(partySize));
        // TODO (7) Set the tag of the itemview in the holder to the id
        holder.itemView.setTag(id);
    }

    @Override
    public int getItemCount() {
        return mCursor.getCount();
    }

    /**
     * Swaps the Cursor currently held in the adapter with a new one
     * and triggers a UI refresh
     *
     * @param newCursor the new cursor that will replace the existing one
     */
    public void swapCursor(Cursor newCursor) {
        // Always close the previous mCursor first
        if (mCursor != null) mCursor.close();
        mCursor = newCursor;
        if (newCursor != null) {
            // Force the RecyclerView to refresh
            this.notifyDataSetChanged();
        }
    }

    /**
     * Inner class to hold the views needed to display a single item in the recycler-view
     */
    class GuestViewHolder extends RecyclerView.ViewHolder {

        // Will display the guest name
        TextView nameTextView;
        // Will display the party size number
        TextView partySizeTextView;

        /**
         * Constructor for our ViewHolder. Within this constructor, we get a reference to our
         * TextViews
         *
         * @param itemView The View that you inflated in
         *                 {@link GuestListAdapter#onCreateViewHolder(ViewGroup, int)}
         */
        public GuestViewHolder(View itemView) {
            super(itemView);
            nameTextView = (TextView) itemView.findViewById(R.id.name_text_view);
            partySizeTextView = (TextView) itemView.findViewById(R.id.party_size_text_view);
        }

    }
}


text:
#ifndef BLACK

#define BLACK       1
#define RED         2
#define YELLOW      3
#define GREEN       4
#define CYAN        5
#define BLUE        6
#define MAGENTA     7
#define WHITE       0
/* and a set of 8 more intermediate colors; names from the
    /usr/lib/X11/rgb.txt database */
#define AQUAMARINE  8
#define FORESTGREEN 9
#define ORANGE     10
#define VIOLET     11
#define BROWN      12
#define PINK       13
#define CORAL      14
#define GRAY       15

/* Had a "ifndef lint around this, but that is wrong for using gcc with
   string checking and -Dlint to remove the "vcid" not used */
static char *(colornames[]) = { "white", "black", "red", "yellow", "green",
			      "cyan", "blue", "magenta", "aquamarine",
			      "forestgreen", "orange", "marroon", "brown",
			      "pink", "coral", "gray" };

/*I "xtools/baseclr.h" I*/

/*
      XBPixFromInteger - Looks up an entry in the win->cmapping

    Input Parameters:
     color - an integer color as listed in xtools/baseclr.h

    Synopsis:
    PixVal XBPixFromInteger(win,color)
    XBWindow *win;
    int      color;
 */
#define XBPixFromInteger(win,color) (win)->cmapping[color]

/* Prototypes */
Colormap XBCreateColormap ( Display *, int, Visual * );
int XBHlsToRgb ( int, int, int,
			  unsigned char *, unsigned char *, unsigned char * );

#endif


text:
#ifndef __XX_DICTIONARY_H__
#define __XX_DICTIONARY_H__

#include <string>
#include <map>

/**
Class for dictionaries with string key and pointer value.
\tparam T Specifies the non-pointer value type.
*/
template <typename T> class Dictionary final
{

    public:

        //! Registers the specified pointer entry with the unique identifier 'ident'.
        void Register(const std::string& ident, T* entry)
        {
            map_[ident] = entry;
        }

        //! Unregisters a pointer entry with the specified identifier 'ident'.
        T* Unregister(const std::string& ident)
        {
            auto it = map_.find(ident);
            if (it != map_.end())
            {
                auto entry = it->second;
                map_.erase(it);
                return entry;
            }
            return nullptr;
        }

        //! Clears the entire dictionary map.
        void Clear()
        {
            map_.clear();
        }

        //! Returns true if the specified pointer entry is contained in this dictionary.
        bool Has(T* entry) const
        {
            return map_.find(entry) != map_.end();
        }

        /**
        Returns a pointer to the entry with the specified registered identifier 'ident',
        or null if there is no such entry.
        */
        T* Find(const std::string& ident) const
        {
            auto it = map_.find(ident);
            return it != map_.end() ? it->second : nullptr;
        }

    private:

        std::map<std::string, T*> map_;

};

#endif

// ================================================================================


text:
stresstest.sh
#!/bin/bash
#Simple stress test for system. If it survives this, it's probably stable.
#Free software, GPL2+

echo "Testing overclock stability..."

#Max out the CPU in the background (one core). Heats it up, loads the power-supply.
nice yes >/dev/null &

#Read the entire SD card, 2x. Tests RAM and I/O
for i in {1..2}; do echo reading: $i; sudo dd if=/dev/mmcblk0 of=/dev/null bs=4M; done

#Writes 512 MB test file,  5x.
for i in {1..5}; do echo writing: $i; dd if=/dev/zero of=deleteme.dat bs=1M count=512; sync; done

#Clean up
killall yes
rm deleteme.dat

#Print summary. Anything nasty will appear in dmesg.
echo -n "CPU freq: " ; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
echo -n "CPU temp: " ; cat /sys/class/thermal/thermal_zone0/temp
dmesg | tail

echo "Not crashed yet, probably stable."


text:
package org.purview.qtui.meta

import com.trolltech.qt.QSignalEmitter
import org.purview.core.analysis.Analyser
import org.purview.core.analysis.Metadata
import org.purview.core.data.ImageMatrix
import org.purview.core.report.ReportEntry
import org.purview.core.session.AnalysisSession
import org.purview.core.session.AnalysisStats
import scala.actors.Actor

case class Analysis(matrix: ImageMatrix, name: String, analysers: Seq[Analyser[ImageMatrix]]) extends QSignalEmitter {

  def analyser: String = stats.oldAnalyser
  val analyserChanged = new Signal1[String]

  def status: String = stats.oldStatus
  val statusChanged = new Signal1[String]

  def progress: Float = stats.oldProgress
  val progressChanged = new Signal1[Float]

  def subProgress: Float = stats.oldSubProgress
  val subProgressChanged = new Signal1[Float]

  val error = new Signal1[String]

  def hasFinished = _done
  val finished = new Signal0

  @volatile private var _done = false
  @volatile private var _results: Option[Map[Metadata, Seq[ReportEntry]]] = None
  def results = _results

  private val stats = new AnalysisStats {
    var oldProgress = 0f
    var oldSubProgress = 0f
    var oldStatus = ""
    var oldAnalyser = ""

    override def reportProgress(progress: Float) =
      if((oldProgress * 100).toInt != (progress * 100).toInt) {
        oldProgress = progress
        progressChanged.emit(progress)
      }

    override def reportSubProgress(progress: Float) =
      if((oldSubProgress * 100).toInt != (progress * 100).toInt) {
        oldSubProgress = progress
        subProgressChanged.emit(progress)
      }

    override def reportStatus(status: String) =
      if(oldStatus != status) {
        oldStatus = status
        statusChanged.emit(status)
      }

    override def reportAnalyser(analyser: String) =
      if(oldAnalyser != analyser) {
        oldAnalyser = analyser
        analyserChanged.emit(analyser)
      }
  }

  def analyse(): Unit = Actor.actor {
    val report = try
      new AnalysisSession(analysers, matrix).run(stats)
    catch {
      case err =>
        val str = err.getMessage + "\n" + err.getStackTraceString
        error.emit(str)
        println(str)
        throw new Throwable("Error in analyser", err)
    }
    val sortedReport = for {
      (analyser, entries) <- report
      sortedEntries = entries.toSeq.sortBy(_.level.name)
    } yield (analyser, sortedEntries)
    stats.reportStatus("Done")
    stats.reportAnalyser("None")
    _results = Some(sortedReport)
    _done = true
    finished.emit()
  }

  var reportEntryChanged: List[Option[ReportEntry] => Any] = Nil

  def changeReportEntry(reportEntry: Option[ReportEntry]) =
    reportEntryChanged.foreach(_(reportEntry))
}


text:
package im.mange.flyby

import com.zink.scala.fly.ScalaFly
import im.mange.driveby.DriveByConfig

class FlySpace(hostname: String) {
  private var fly = ScalaFly.makeFly(host = hostname) match {
    case Left(t) => throw new RuntimeException("Unable to start fly", t)
    case Right(f) => f
  }

  def read(entry: AnyRef, waitTime: Long = DriveByConfig.flySpaceDefaultTimeoutMillis) = fly.read(entry, waitTime)
  def write(entry: AnyRef, leaseTime: Long = DriveByConfig.flySpaceDefaultTimeoutMillis) = fly.write(entry, leaseTime)
  def take[T <: AnyRef](template: T, waitTime: Long = DriveByConfig.flySpaceDefaultTimeoutMillis) = fly.take(template, waitTime)
  def readMany(entry: AnyRef, matchLimit: Long = DriveByConfig.flySpaceDefaultMatchLimit) = fly.readMany(entry, matchLimit)
  def writeMany(entries: Iterable[AnyRef], leaseTime: Long = DriveByConfig.flySpaceDefaultTimeoutMillis) = fly.writeMany(entries, leaseTime)
  def takeMany[T <: AnyRef](template: T, matchLimit: Long = DriveByConfig.flySpaceDefaultMatchLimit) = fly.takeMany(template, matchLimit)
}


text:
<?php
namespace Tests\Functional\BehatContext;

use Behat\Behat\Context\Context;
use Behat\Behat\Tester\Exception\PendingException;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessBuilder;

/**
 * Defines application features from the specific context.
 */
class FeatureContext implements Context
{

    /** @var Process|null */
    private $process = null;
    /** @var string|null */
    private $configurationName = null;
    /** @var string[] */
    private $groupNameList = [];
    /** @var bool */
    private $withCoverage = false;

    /**
     * @Given I use :configurationName phpunit configuration
     */
    public function iUsePhpunitConfiguration($configurationName)
    {
        $this->configurationName = $configurationName;
    }

    /**
     * @Given I use :groupName group
     */
    public function iUseGroup($groupName)
    {
        $this->groupNameList[] = $groupName;
    }

    /**
     * @Given I enable coverage
     */
    public function iEnableCoverage()
    {
        $this->withCoverage = true;
    }

    /**
     * @Given I run phpunit
     */
    public function iRunPhpunitTestSuite()
    {
        $baseArgList = [
            sprintf('%s/%s/vendor/bin/phpunit', __DIR__, '../..')
        ];
        $argList = array_merge($baseArgList, $this->getCustomConfig());
        $processBuilder = new ProcessBuilder($argList);

        $this->process = $processBuilder->getProcess();

        $this->process->run();
    }

    /**
     * @Then /^I should have (?P<expectedFailureCount>\d+) failure(s)?$/
     */
    public function iShouldHaveXFailures($expectedFailureCount)
    {
        $output = $this->process->getOutput();

        $failureCount = preg_match_all(sprintf('#There was %s failure#', $expectedFailureCount), $output);
        if ($failureCount != $expectedFailureCount) {
            throw new \Exception(sprintf('Found %d failure, but %d expected', $failureCount, $expectedFailureCount));
        }
    }

    /**
     * @Then I should have the following regexp :regexp
     */
    public function iShouldHaveAFailureContainingFollowingMessage($regexp)
    {
        $output = $this->process->getOutput();

        if (!preg_match($regexp, $output)) {
            throw new \Exception(sprintf('"%s" not found in : %s', $regexp, $output));
        }
    }

    /**
     * @Then :className should not be covered
     */
    public function shouldNotBeCovered($className)
    {
        throw new PendingException();
    }

    /**
     * @return array
     */
    protected function getCustomConfig()
    {
        $config = [];

        if (null !== $this->configurationName) {
            $config[] = '-c';
            $config[] = sprintf('features/demo_app/phpunitConfig/%s.phpunit.xml', $this->configurationName);
        }

        foreach ($this->groupNameList as $groupName) {
            $config[] = '--group';
            $config[] = $groupName;
        }

        if (true === $this->withCoverage) {
            $config[] = '--coverage-text';
        }

        return $config;
    }
}


text:
Copyright [A Beautiful Site, LLC.](http://abeautifulsite.net/)

Licensed under the MIT license: http://opensource.org/licenses/MIT

## Demo & Documentation ##

http://labs.abeautifulsite.net/jquery-dropdown/


text:
import dbus

def main():
    try:
        session_bus = dbus.SessionBus()
        spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify",
                                             "/org/mpris/MediaPlayer2")
        spotify_properties = dbus.Interface(spotify_bus,
                                            "org.freedesktop.DBus.Properties")
        metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player",
                                          "Metadata")

        print("{} - {}".format(
            metadata["xesam:artist"][0],
            metadata["xesam:title"]))
    except:
        print("")

if __name__ == "__main__":
    main()


text:
from migen import *

from litex.gen import LiteXModule

from litex_boards.platforms import mnt_rkx7

from litex.soc.cores.clock import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.soc import SoCRegion
from litex.soc.integration.builder import *
from litex.soc.interconnect.csr import *
from litex.soc.interconnect.axi import *
from litex.soc.interconnect.wishbone import *
from litex.soc.cores.bitbang import I2CMaster
from litex.soc.cores.gpio import GPIOOut
from litex.soc.cores.video import VideoDVIPHY
from litex.soc.cores.usb_ohci import USBOHCI
from migen.fhdl.specials import Tristate

from litedram.modules import IS43TR16512B
from litedram.phy import s7ddrphy

from liteeth.phy.s7rgmii import LiteEthPHYRGMII

# CRG ----------------------------------------------------------------------------------------------

class _CRG(LiteXModule):
    def __init__(self, platform, sys_clk_freq):
        self.rst       = Signal()
        self.cd_sys    = ClockDomain()
        self.cd_sys4x  = ClockDomain()
        self.cd_idelay = ClockDomain()
        self.cd_dvi    = ClockDomain(reset_less=True)
        self.cd_usb    = ClockDomain()

        clkin = platform.request("clk100")

        self.pll = pll = S7MMCM(speedgrade=-2)
        self.comb += pll.reset.eq(self.rst)
        # Main clock input (100MHz)
        pll.register_clkin(clkin, 100e6)
        pll.create_clkout(self.cd_sys,    sys_clk_freq)
        pll.create_clkout(self.cd_sys4x,  4*sys_clk_freq)
        pll.create_clkout(self.cd_idelay, 200e6)
        # Ignore sys_clk to pll.clkin path created by SoC's rst.
        platform.add_false_path_constraints(self.cd_sys.clk, pll.clkin)

        # USB clock
        pll.create_clkout(self.cd_usb, 48e6)

        self.pll2 = pll2 = S7MMCM(speedgrade=-2)
        self.comb += pll2.reset.eq(self.rst)
        pll2.register_clkin(clkin, 100e6)
        # DVI/HDMI pixel clock
        pll2.create_clkout(self.cd_dvi, 80e6) # display wants 162e6, but we can underclock
        platform.add_false_path_constraints(self.cd_sys.clk, pll2.clkin)

        self.idelayctrl = S7IDELAYCTRL(self.cd_idelay)

# BaseSoC ------------------------------------------------------------------------------------------

class BaseSoC(SoCCore):
    mem_map = {**SoCCore.mem_map, **{
        # FIXME: ends up as 0x7f000000 in linux
        "video_framebuffer": 0x3f000000,
        "usb_ohci"         : 0xc0000000,
    }}

    def __init__(self, sys_clk_freq=100e6,
        with_ethernet  = True,
        with_etherbone = False,
        with_spi_flash = True,
        with_usb_host  = False,
        **kwargs):
        platform = mnt_rkx7.Platform()

        # CRG --------------------------------------------------------------------------------------
        self.crg = _CRG(platform, sys_clk_freq)

        # SoCCore ----------------------------------------------------------------------------------
        SoCCore.__init__(self, platform, sys_clk_freq, ident="LiteX SoC on MNT-RKX7", **kwargs)

        # DDR3 SDRAM -------------------------------------------------------------------------------
        if not self.integrated_main_ram_size:
            self.ddrphy = s7ddrphy.K7DDRPHY(platform.request("ddram"),
                memtype      = "DDR3",
                nphases      = 4,
                sys_clk_freq = sys_clk_freq)
            self.add_sdram("sdram",
                phy           = self.ddrphy,
                module        = IS43TR16512B(sys_clk_freq, "1:4"),
                size          = 0x40000000,
                l2_cache_size = kwargs.get("l2_size", 8192), # TBD: is L2 really necessary?
            )

        # SPI Flash --------------------------------------------------------------------------------
        if with_spi_flash:
            from litespi.modules import W25Q128JV
            from litespi.opcodes import SpiNorFlashOpCodes as Codes
            self.add_spi_flash(mode="4x", module=W25Q128JV(Codes.READ_1_1_4), rate="1:1", with_master=True)

        # Ethernet / Etherbone ---------------------------------------------------------------------
        if with_ethernet or with_etherbone:
            self.ethphy = LiteEthPHYRGMII(
                clock_pads = self.platform.request("eth_clocks"),
                pads       = self.platform.request("eth"))
            platform.add_platform_command("set_property CLOCK_DEDICATED_ROUTE FALSE [get_nets {{main_ethphy_eth_rx_clk_ibuf}}]")
            platform.add_platform_command("set_property CLOCK_DEDICATED_ROUTE FALSE [get_nets {{soclinux_ethphy_eth_rx_clk_ibuf}}]")
            if with_ethernet:
                self.add_ethernet(phy=self.ethphy, dynamic_ip=True, software_debug=False)
            if with_etherbone:
                self.add_etherbone(phy=self.ethphy)

        # GPIO -------------------------------------------------------------------------------------
        # Controllable as faux "leds"
        # These are reset pins of various chips
        # We toggle them in LiteX BIOS
        reset_signals = platform.request("resets")
        self.comb += reset_signals.eq(Signal(6, reset=0b111111))

        gpio_signals = platform.request("gpio")
        self.leds = GPIOOut(gpio_signals)

        # Additional I2C Ports ---------------------------------------------------------------------
        self.i2c0 = I2CMaster(platform.request("i2c", 0))
        self.i2c1 = I2CMaster(platform.request("i2c", 1))
        self.i2c2 = I2CMaster(platform.request("i2c", 2))

        # JTAG -------------------------------------------------------------------------------------
        #self.add_jtagbone()

        # Backlight --------------------------------------------------------------------------------
        # Motherboard display connector backlight, currently unused (the new backlight signals
        # are on the 50pin RGB->eDP connector)
        backlight = platform.request("backlight")
        self.comb += backlight.en.eq(Signal(reset=1))
        self.comb += backlight.pwm.eq(Signal(reset=1))

        # eDP --------------------------------------------------------------------------------------
        video_timings = ("1920x1080@rkx7", {
            "pix_clk"       : 162e6,
            "h_active"      : 1920,
            "h_blanking"    : 159, # off by one in vtg
            "h_sync_offset" : 40,
            "h_sync_width"  : 40,
            "v_active"      : 1080,
            "v_blanking"    : 32,
            "v_sync_offset" : 4,
            "v_sync_width"  : 4,
        })
        self.videophy = VideoDVIPHY(platform.request("edp"), clock_domain="dvi")
        self.add_video_framebuffer(phy=self.videophy, timings=video_timings, clock_domain="dvi")

        # HDMI -------------------------------------------------------------------------------------
        # Untested: 2x VideoDVIPHYs and framebuffers in parallel
        #self.videophy = VideoDVIPHY(platform.request("hdmi"), clock_domain="dvi")

        # USB Host ---------------------------------------------------------------------------------
        if with_usb_host:
            self.usb_ohci = USBOHCI(platform, platform.request("usb"))
            self.bus.add_slave("usb_ohci_ctrl", self.usb_ohci.wb_ctrl, region=SoCRegion(origin=self.mem_map["usb_ohci"], size=0x100000, cached=False))
            self.dma_bus.add_master("usb_ohci_dma", master=self.usb_ohci.wb_dma)
            self.comb += self.cpu.interrupt[16].eq(self.usb_ohci.interrupt)

        # LiteScope UART
        self.add_uartbone(name="litescope_serial")
        # LiteScope Analyzer (optional)
        # analyzer_signals = [
        #     ulpi_data.din,
        #     utmi.linestate,
        #     utmi.txvalid,
        #     utmi.rxerror,
        #     utmi.rxvalid,
        #     usb_ulpi.dir,
        #     usb_ulpi.stp,
        #     usb_ulpi.nxt,
        #     usbh_dbg_state,
        #     ulpi_dbg_state,
        #     usb_host_intr,
        #     usb_host_dbg_intr,
        #     ]
        # from litescope import LiteScopeAnalyzer
        # self.analyzer = LiteScopeAnalyzer(analyzer_signals,
        #                                              depth        = 256,
        #                                              clock_domain = "ulpi",
        #                                              csr_csv      = "analyzer.csv")

# Build --------------------------------------------------------------------------------------------

def main():
    from litex.build.parser import LiteXArgumentParser
    parser = LiteXArgumentParser(platform=mnt_rkx7.Platform, description="LiteX SoC on MNT-RKX7.")
    parser.add_target_argument("--sys-clk-freq",    default=100e6,  type=float,         help="System clock frequency.")
    parser.add_target_argument("--with-spi-flash",  action="store_true", default=True,  help="Enable SPI Flash (MMAPed).")
    parser.add_target_argument("--with-usb-host",   action="store_true", default=False, help="Enable USB host support.")
    sdopts = parser.target_group.add_mutually_exclusive_group()
    sdopts.add_argument("--with-spi-sdcard",     action="store_true",               help="Enable SPI-mode SDCard support.")
    sdopts.add_argument("--with-sdcard",         action="store_true", default=True, help="Enable SDCard support.")
    ethopts = parser.target_group.add_mutually_exclusive_group()
    ethopts.add_argument("--with-ethernet",  action="store_true", default=True, help="Enable Ethernet support.")
    ethopts.add_argument("--with-etherbone", action="store_true",               help="Enable Etherbone support.")
    args = parser.parse_args()

    soc = BaseSoC(
        sys_clk_freq   = args.sys_clk_freq,
        with_ethernet  = args.with_ethernet,
        with_etherbone = args.with_etherbone,
        with_spi_flash = args.with_spi_flash,
        with_usb_host  = args.with_usb_host,
        **parser.soc_argdict
    )
    if args.with_spi_sdcard:
        soc.add_spi_sdcard()
    if args.with_sdcard:
        soc.add_sdcard()

    args.csr_csv="csr.csv"

    builder = Builder(soc, **parser.builder_argdict)
    if args.build:
        builder.build(**parser.toolchain_argdict)

    if args.load:
        prog = soc.platform.create_programmer()
        prog.load_bitstream(builder.get_bitstream_filename(mode="sram"))

if __name__ == "__main__":
    main()


text:
using Newtonsoft.Json;

namespace MiningCore.Blockchain.Monero.DaemonResponses
{
    public class GetInfoResponse
    {
        /// <summary>
        /// Current target for next proof of work.
        /// </summary>
        public uint Target { get; set; }

        /// <summary>
        /// The height of the next block in the chain.
        /// </summary>
        [JsonProperty("target_height")]
        public uint TargetHeight { get; set; }

        /// <summary>
        /// States if the node is on the testnet(true) or mainnet(false).
        /// </summary>
        [JsonProperty("testnet")]
        public bool IsTestnet { get; set; }

        /// <summary>
        /// Hash of the highest block in the chain.
        /// </summary>
        [JsonProperty("top_block_hash")]
        public string TopBlockHash { get; set; }

        /// <summary>
        /// Total number of non-coinbase transaction in the chain.
        /// </summary>
        [JsonProperty("tx_count")]
        public uint TransactionCount { get; set; }

        /// <summary>
        /// Number of transactions that have been broadcast but not included in a block.
        /// </summary>
        [JsonProperty("tx_pool_size")]
        public uint TransactionPoolSize { get; set; }

        /// <summary>
        /// Network difficulty(analogous to the strength of the network)
        /// </summary>
        public ulong Difficulty { get; set; }

        /// <summary>
        /// Current length of longest chain known to daemon.
        /// </summary>
        public uint Height { get; set; }

        /// <summary>
        /// General RPC error code. "OK" means everything looks good.
        /// </summary>
        public string Status { get; set; }

        /// <summary>
        /// Number of alternative blocks to main chain.
        /// </summary>
        [JsonProperty("alt_blocks_count")]
        public int AltBlocksCount { get; set; }

        /// <summary>
        /// Grey Peerlist Size
        /// </summary>
        [JsonProperty("grey_peerlist_size")]
        public int GreyPeerlistSize { get; set; }

        /// <summary>
        /// White Peerlist Size
        /// </summary>
        [JsonProperty("white_peerlist_size")]
        public uint WhitePeerlistSize { get; set; }

        /// <summary>
        /// Number of peers connected to and pulling from your node.
        /// </summary>
        [JsonProperty("incoming_connections_count")]
        public int IncomingConnectionsCount { get; set; }

        /// <summary>
        /// Number of peers that you are connected to and getting information from.
        /// </summary>
        [JsonProperty("outgoing_connections_count")]
        public int OutgoingConnectionsCount { get; set; }
    }
}