text:
package za.redbridge.experiment.NEATM.training;

import org.encog.engine.network.activation.ActivationFunction;
import org.encog.neural.neat.NEATNeuronType;
import org.encog.neural.neat.training.NEATNeuronGene;

import za.redbridge.experiment.NEATM.sensor.SensorConfiguration;

/**
 * Created by jamie on 2014/09/08.
 */
public class NEATMNeuronGene extends NEATNeuronGene {

    private static final long serialVersionUID = 1583781843029771944L;

    private SensorConfiguration sensorConfiguration;

    public NEATMNeuronGene(NEATNeuronType type, ActivationFunction theActivationFunction, long id,
            long innovationID) {
        setNeuronType(type);
        setInnovationId(innovationID);
        setId(id);
        setActivationFunction(theActivationFunction);
    }

    /**
     * Construct this gene by comping another.
     * @param other The other gene to copy.
     */
    public NEATMNeuronGene(NEATMNeuronGene other) {
        copy(other);
    }

    /**
     * Copy another gene to this one.
     *
     * @param other
     *            The other gene.
     */
    public void copy(NEATMNeuronGene other) {
        setId(other.getId());
        setNeuronType(other.getNeuronType());
        setActivationFunction(other.getActivationFunction());
        setInnovationId(other.getInnovationId());

        if (getNeuronType() == NEATNeuronType.Input) {
            setSensorConfiguration(other.getSensorConfiguration().clone());
        }
    }

    public SensorConfiguration getSensorConfiguration() {
        return sensorConfiguration;
    }

    public void setSensorConfiguration(SensorConfiguration sensorConfiguration) {
        this.sensorConfiguration = sensorConfiguration;
    }

    private void checkInputNeuron() {
        if (getNeuronType() != NEATNeuronType.Input) {
            throw new UnsupportedOperationException("Not an input neuron");
        }
    }
}


text:
"""Test message sending before handshake completion.

A node should never send anything other than VERSION/VERACK/REJECT until it's
received a VERACK.

This test connects to a node and sends it a few messages, trying to entice it
into sending us something it shouldn't."""

import time

from test_framework.messages import msg_getaddr, msg_ping, msg_verack
from test_framework.mininode import mininode_lock, P2PInterface
from test_framework.test_framework import SyscoinTestFramework
from test_framework.util import wait_until

banscore = 10

class CLazyNode(P2PInterface):
    def __init__(self):
        super().__init__()
        self.unexpected_msg = False
        self.ever_connected = False

    def bad_message(self, message):
        self.unexpected_msg = True
        self.log.info("should not have received message: %s" % message.command)

    def on_open(self):
        self.ever_connected = True

    def on_version(self, message): self.bad_message(message)
    def on_verack(self, message): self.bad_message(message)
    def on_reject(self, message): self.bad_message(message)
    def on_inv(self, message): self.bad_message(message)
    def on_addr(self, message): self.bad_message(message)
    def on_getdata(self, message): self.bad_message(message)
    def on_getblocks(self, message): self.bad_message(message)
    def on_tx(self, message): self.bad_message(message)
    def on_block(self, message): self.bad_message(message)
    def on_getaddr(self, message): self.bad_message(message)
    def on_headers(self, message): self.bad_message(message)
    def on_getheaders(self, message): self.bad_message(message)
    def on_ping(self, message): self.bad_message(message)
    def on_mempool(self, message): self.bad_message(message)
    def on_pong(self, message): self.bad_message(message)
    def on_feefilter(self, message): self.bad_message(message)
    def on_sendheaders(self, message): self.bad_message(message)
    def on_sendcmpct(self, message): self.bad_message(message)
    def on_cmpctblock(self, message): self.bad_message(message)
    def on_getblocktxn(self, message): self.bad_message(message)
    def on_blocktxn(self, message): self.bad_message(message)

# Node that never sends a version. We'll use this to send a bunch of messages
# anyway, and eventually get disconnected.
class CNodeNoVersionBan(CLazyNode):
    # send a bunch of veracks without sending a message. This should get us disconnected.
    # NOTE: implementation-specific check here. Remove if syscoind ban behavior changes
    def on_open(self):
        super().on_open()
        for i in range(banscore):
            self.send_message(msg_verack())

    def on_reject(self, message): pass

# Node that never sends a version. This one just sits idle and hopes to receive
# any message (it shouldn't!)
class CNodeNoVersionIdle(CLazyNode):
    def __init__(self):
        super().__init__()

# Node that sends a version but not a verack.
class CNodeNoVerackIdle(CLazyNode):
    def __init__(self):
        self.version_received = False
        super().__init__()

    def on_reject(self, message): pass
    def on_verack(self, message): pass
    # When version is received, don't reply with a verack. Instead, see if the
    # node will give us a message that it shouldn't. This is not an exhaustive
    # list!
    def on_version(self, message):
        self.version_received = True
        self.send_message(msg_ping())
        self.send_message(msg_getaddr())

class P2PLeakTest(SyscoinTestFramework):
    def set_test_params(self):
        self.num_nodes = 1
        self.extra_args = [['-banscore=' + str(banscore)]]

    def run_test(self):
        no_version_bannode = self.nodes[0].add_p2p_connection(CNodeNoVersionBan(), send_version=False, wait_for_verack=False)
        no_version_idlenode = self.nodes[0].add_p2p_connection(CNodeNoVersionIdle(), send_version=False, wait_for_verack=False)
        no_verack_idlenode = self.nodes[0].add_p2p_connection(CNodeNoVerackIdle())

        wait_until(lambda: no_version_bannode.ever_connected, timeout=10, lock=mininode_lock)
        wait_until(lambda: no_version_idlenode.ever_connected, timeout=10, lock=mininode_lock)
        wait_until(lambda: no_verack_idlenode.version_received, timeout=10, lock=mininode_lock)

        # Mine a block and make sure that it's not sent to the connected nodes
        self.nodes[0].generatetoaddress(1, self.nodes[0].get_deterministic_priv_key().address)

        #Give the node enough time to possibly leak out a message
        time.sleep(5)

        #This node should have been banned
        assert not no_version_bannode.is_connected

        self.nodes[0].disconnect_p2ps()

        # Wait until all connections are closed
        wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 0)

        # Make sure no unexpected messages came in
        assert no_version_bannode.unexpected_msg == False
        assert no_version_idlenode.unexpected_msg == False
        assert no_verack_idlenode.unexpected_msg == False

if __name__ == '__main__':
    P2PLeakTest().main()

redpajama_set_name: RedPajamaGithub


text:
// Qt includes
#include <QCoreApplication>
#include <QDir>

// ctkDICOMCore includes
#include "ctkDICOMDatabase.h"

// STD includes
#include <iostream>
#include <cstdlib>

int ctkDICOMDatabaseTest7( int argc, char * argv [] )
{
  QCoreApplication app(argc, argv);

  ctkDICOMDatabase database;
  QDir databaseDirectory = QDir::temp();
  databaseDirectory.remove("ctkDICOMDatabase.sql");
  databaseDirectory.remove("ctkDICOMTagCache.sql");

  QFileInfo databaseFile(databaseDirectory, QString("database.test"));
  database.openDatabase(databaseFile.absoluteFilePath());

  bool res = database.initializeDatabase();

  if (!res)
    {
    std::cerr << "ctkDICOMDatabase::initializeDatabase() failed." << std::endl;
    return EXIT_FAILURE;
    }
  std::cerr << "Database is in " << databaseDirectory.path().toStdString() << std::endl;

  // try to call fileValue with bogus data - should not trigger and exception
  // (see https://github.com/commontk/CTK/issues/706)

  database.fileValue("/tmp/file-that-does-not-exist", "00ff,eeee");

  //
  // Close and clean up
  //
  database.closeDatabase();

  return EXIT_SUCCESS;
}


text:
#include <aws/glacier/model/InitiateJobResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Glacier::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

InitiateJobResult::InitiateJobResult()
{
}

InitiateJobResult::InitiateJobResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

InitiateJobResult& InitiateJobResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  const auto& headers = result.GetHeaderValueCollection();
  const auto& locationIter = headers.find("location");
  if(locationIter != headers.end())
  {
    m_location = locationIter->second;
  }

  const auto& jobIdIter = headers.find("x-amz-job-id");
  if(jobIdIter != headers.end())
  {
    m_jobId = jobIdIter->second;
  }

  return *this;
}


text:
        <select id="form-select" >

        </select>

Please fill out all of the red fields


text:
'use strict';

/**
 * @ngdoc function
 * @name itemCatalogApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the itemCatalogApp
 */
angular.module('itemCatalogApp')
  .controller('MainCtrl', function ($scope, $state, $window, Common, Item) {
    $scope.items = [];

    var loadItems = function () {
      Item.recent(function (response) {
        $scope.items = response;
      }, function (response) {
        Common.alert.setErrorMessage(response.data.message);
      });
    };

    $scope.selectItem = function (item) {
      $state.go('item', { 'categoryId': item.categoryId, 'itemId': item.id }, { notify: true });
    };

    $scope.selectCategory = function (item) {
      $state.go('category', { 'categoryId': item.categoryId }, { notify: true });
    };

    (function init() {
      Common.setTag('home');
      loadItems();
    })();
  });


text:
/*
TaskCollection.js
Function: holds global Task collection
*/

Tasks = new Mongo.Collection('tasks', {
  // transform all MongoDB elements to 'Task' objects
  transform: function transformToTask(doc) {
    var taskBson = doc.task;
    return new Task(taskBson);
  },
});


text:
TOP = ../../..
include $(TOP)/mak/config.mak

MODULE=1

SHARED_LIBRARY = cimplefan

GENCLASS_SOURCES = \
    Fan.cpp \
    repository.cpp

GENCLASS_HEADERS = $(GENCLASS_SOURCES:.cpp=.h)

CLEAN += $(GENCLASS_SOURCES) $(GENCLASS_HEADERS)

SOURCES = \
    $(GENCLASS_SOURCES) \
    Fan_Provider.cpp \
    module.cpp

## Allow building providers for either CMPI or Pegasus C++ provider interface
## Changing Provider interfaces requires reregistering the provider. Default Pegasus
##
ifndef CIMPLE_PROVIDER_TYPE
   CIMPLE_PEGASUS_MODULE = 1
endif

export CIMPLE_MOF_PATH=$(TOP)/schema/cim214

## Expand CIMPLE_***_MODULE definitions and CIMPLE_PROVIDER_TYPE
include ../common.mak

include $(TOP)/mak/rules.mak

genclass $(GENCLASS_SOURCES): repository.mof
	$(BINDIR)/genclass -r Fan

regmod:
	$(BINDIR)/regmod -c $(TARGET)

genprov:
	$(BINDIR)/genprov Fan

genmod:
	$(BINDIR)/genmod Fan Fan

genproj:
	$(BINDIR)/genproj Fan Fan

##============================================================================
##
##  Live Tests - These are tests automatically conducted during regression
##                  Pegasus cimcli used for these live tests.
##                  Does not test results.
##
##============================================================================
live:
	$(CIMCLI) gc fan
	$(CIMCLI) ei fan
	$(CIMCLI) ni fan
	$(CIMCLI) ei fan --sum -count 3
	$(CIMCLI) ni fan --sum -count 3

	$(CIMCLI) gi Fan.DeviceID=\"FAN03\"
	$(CIMCLI) gi Fan.DeviceID=\"FAN02\"
	$(CIMCLI) gi Fan.DeviceID=\"FAN01\"

## The following tests the enumerate, get, and delete functions
## Since it deletes instances, it can be run only once before
## reinitializing the provider which reinstalls the deleted instances.
## This can be done either by waiting for the provider to timeout and
## drop out of memory or by restarting the server. Therefore
## we targeted it as livetests so it will not run as part of
## the automated test Therefore
## we targeted it as livetests so it will not run as part of
## the automated test

##=======================================================================
##
## Live manual tests using Pegasus cimcli
## These tests are a demonstration that the provider works.  They
## do not test the results today, simply assure that there is no exception
## on response
##===========================================================================
manual-test:
	cimcli ns -l localhost
	cimcli gc $(TEST_CLASS) -l localhost -n $(TEST_NAMESPACE)
	cimcli ni $(TEST_CLASS) -l localhost -n $(TEST_NAMESPACE)
	cimcli ei $(TEST_CLASS) -l localhost -n $(TEST_NAMESPACE)

ei:
	cimcli ei $(TEST_CLASS) -l localhost -n $(TEST_NAMESPACE)

	$(CIMCLI) gi Fan.DeviceID=\"FAN03\"
	$(CIMCLI) gi Fan.DeviceID=\"FAN02\"
	$(CIMCLI) gi Fan.DeviceID=\"FAN01\"

	$(CIMCLI) di Fan.DeviceID=\"FAN03\"
	$(CIMCLI) ni fan --sum -count 2
	$(CIMCLI) di Fan.DeviceID=\"FAN02\"
	$(CIMCLI) ni fan --sum -count 1
	$(CIMCLI) di Fan.DeviceID=\"FAN01\"
	$(CIMCLI) ni fan --sum -count 0


text:
import React, { PureComponent } from "react";
import PropTypes from 'prop-types';
import { Range } from 'immutable';

import { SQUARE_SIZE, GUTTER_SIZE } from '../../constants';

import Day from '../../containers/Day';

class Week extends PureComponent {
  render() {
    const { weekIndex, initialValues } = this.props;

    return (
      <g
        key={`week-${weekIndex}`}
        transform={`translate(${weekIndex * (SQUARE_SIZE + GUTTER_SIZE)}, 0)`}
      >
        {Range(6, -1, -1).map(dayIndex => {
          return (
            <Day
              key={`day-${dayIndex}`}
              dayIndex={dayIndex}
              weekIndex={weekIndex}
              initialDays={initialValues}
            />
          );
        })}
      </g>
    );
  }
}

Week.propTypes = {
  weekIndex: PropTypes.number
};

Week.defaultProps = {
  weekIndex: 0
};

export default Week;


text:
/**
 * Detect which browsers the user has installed.
 *
 * Inspired heavily by: https://github.com/celer/element34
 */

'use strict';

var EventEmitter    = require( 'events' ).EventEmitter,
    util            = require( 'util' ),
    path            = require( 'path' ),
    fs              = require( 'fs' ),
    os              = require( 'os' ),
    spawn           = require( 'child_process' ).spawn,
    which           = require( 'which' ),
    Q               = require( 'Q' ),
    _browserData    = [
        {
            'paths': [
                '/usr/bin/google-chrome',
                '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome',
                '%HOMEPATH%i\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe',
                'C:\\Users\\%USERNAME%\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'
            ],
            'label':       'Chrome',
            'slug':        'chrome',
            'isAvailable': false
        },
        {
            'paths': [
                '/Applications/Firefox.app/Contents/MacOS/firefox-bin',
                '%PROGRAMFILES%\\Mozilla Firefox\\firefox.exe'
            ],
            'label':       'Firefox',
            'slug':        'firefox',
            'isAvailable': false
        },
        {
            'label':       'Safari',
            'slug':        'safari',
            'isAvailable': false
        },
        {
            'label':       'PhantomJS',
            'slug':        'phantomjs',
            'isAvailable': false
        }
    ];

var BrowserDetect = function BrowserDetect () {

    var self = this;

    // cache browser data
    this.browsers = _browserData;

    // cache browser helper methods
    this.browserHelpers = [];

    var _getHelper = function _getHelper( methodName ) {
        console.log( methodName , this );
        return self[ methodName ];
    };

    // private method with helper internal private methods
    var _initialize = function _initialize () {
        var helpers = {
            '_checkAvailableChrome': function _checkAvailableChrome ( options ) {
                var opts       = options || {},
                    browserObj = opts.browserObj || {},
                    deffered   = Q.defer(),
                    paths      = browserObj.paths;

                for( var i in paths ) {
                    if( fs.existsSync( paths[ i ] ) ) {
                        deffered.resolve({
                            'data': browserObj,
                            'result': true
                        });
                    }
                }

                if( os.platform() === 'linux' ) {
                    which( 'google-chrome' , function( err , res ){
                        deffered.resolve({
                            'data': browserObj,
                            'result': res !== null
                        });
                    });
                }

                return deffered.promise;
            },
            '_checkAvailableFirefox': function _checkAvailableFirefox ( options ) {
                var opts       = options || {},
                    browserObj = opts.browserObj || {},
                    deffered   = Q.defer(),
                    paths      = browserObj.paths;

                if( os.platform() === 'linux' ) {
                    which( 'firefox' , function( err , res ){
                        deffered.resolve({
                            'data': browserObj,
                            'result': res !== null
                        });
                    });
                }
                else {
                    for( var i in paths ) {
                        if( fs.existsSync( paths[ i ] ) ) {
                            deffered.resolve({
                                'data': browserObj,
                                'result': true
                            });
                        }
                    }
                }

                return deffered.promise;
            },
            '_checkAvailableSafari': function _checkAvailableSafari ( options ) {
                var opts       = options || {},
                    browserObj = opts.browserObj || {},
                    deffered   = Q.defer();

                deffered.resolve({
                    'data': browserObj,
                    'result': os.platform() === 'darwin'
                });

                return deffered.promise;
            },
            '_checkAvailablePhantomJS': function _checkAvailablePhantomJS ( options ) {
                var opts       = options || {},
                    browserObj = opts.browserObj || {},
                    deffered    = Q.defer(),
                    phantomCall = spawn ( 'phantomjs' , [ '--version' ] );

                // grep for version on data of call to phantomJS
                phantomCall
                    .stdout.on( 'data' , function ( data ) {
                        var regEx = new RegExp( /(\d*).(\d*).(\d)(.*)/g );
                        deffered.resolve({
                            'data': browserObj,
                            'result': regEx.test( data )
                        });
                    });

                // handle error of phantomJS call / reject promise
                phantomCall
                    .stderr.on( 'data' , function ( data ) {
                        console.log( 'phantomCall stderr: ' + data );
                        deffered.resolve({
                            'data': browserObj,
                            'result': false
                        });
                    });

                // handle end of child processes / reject if errors
                phantomCall
                    .on( 'close' , function ( code ) {
                        if ( code !== 0 ) {
                            console.log( 'phantomCall process exited with code ' + code );
                            deffered.resolve({
                                'data': browserObj,
                                'result': false
                            });
                        }
                    });

                return deffered.promise;
            }
        };

        // check for browser availability
        Q.all( self.browserHelpers )
            .spread( function () {
                var args = arguments,
                    envelope, browser;

                for( var key in args ) {
                    envelope = args[ key ];

                    if( envelope.result ){
                        browser = self.getBrowserData( envelope.data.slug );
                        browser.isAvailable = envelope.result;
                    }
                }
            })
            .done( function () {
                self.emit( self.events.success , self.getBrowsers() );
            });

        self.browsers.forEach( function ( browser ) {
            var fnName = '_checkAvailable' + browser.label,
                data   = {
                    'browserObj': browser
                };

            self.browserHelpers
                .push( helpers[ fnName ]( data ) );

        } , self );
    };

    // initialize the promise queue
    _initialize();

    return this;
};

util.inherits( BrowserDetect , EventEmitter );

BrowserDetect.prototype.events = {
    'success': 'onBrowserDetectSuccess',
    'fail':    'onBrowserDetectFail'
};

BrowserDetect.prototype.getBrowserData = function getBrowserData ( slug ) {
    return this.browsers
        .map( function ( val , index , arr ) {
            if( val.slug === slug ) {
                return val;
            }
        })
        .filter( function ( val ) {
            return typeof val !== 'undefined';
        })
        [ 0 ];
};

BrowserDetect.prototype.getBrowsers = function getBrowsers () {
    return this.browsers
        .map( function ( val , index , arr ) {
            // console.log( index , val );
            if ( val.isAvailable) {
                return val;
            }
        })
        .filter( function ( val ) {
            return typeof val !== 'undefined';
        });
};

exports = module.exports = BrowserDetect;


text:
Options
=======

All options that take a "Date" can handle a ``Date`` object; a String formatted according to the given ``format``; or a timedelta relative to today, eg "-1d", "+6m +1y", etc, where valid units are "d" (day), "w" (week), "m" (month), and "y" (year). Use "0" as today.
There are also aliases for the relative timedelta's: "yesterday" equals "-1d", "today" is equal to "+0d" and "tomorrow" is equal to "+1d".

Most options can be provided via data-attributes.  An option can be converted to a data-attribute by taking its name, replacing each uppercase letter with its lowercase equivalent preceded by a dash, and prepending "data-date-" to the result.  For example, ``startDate`` would be ``data-date-start-date``, ``format`` would be ``data-date-format``, and ``daysOfWeekDisabled`` would be ``data-date-days-of-week-disabled``.

autoclose
---------

Boolean.  Default: false

Whether or not to close the datepicker immediately when a date is selected.

beforeShowDay
-------------

Function(Date).  Default: $.noop

A function that takes a date as a parameter and returns one of the following values:

 * undefined to have no effect
 * A Boolean, indicating whether or not this date is selectable
 * A String representing additional CSS classes to apply to the date's cell
 * An object with the following properties:

   * ``enabled``: same as the Boolean value above
   * ``classes``: same as the String value above
   * ``tooltip``: a tooltip to apply to this date, via the ``title`` HTML attribute

beforeShowMonth
---------------

Function(Date).  Default: $.noop

A function that takes a date as a parameter and returns a boolean indicating whether or not this month is selectable

beforeShowYear
--------------

Function(Date).  Default: $.noop

A function that takes a date as a parameter and returns one of the following values:

 * undefined to have no effect
 * A Boolean, indicating whether or not this year is selectable
 * A String representing additional CSS classes to apply to the year's cell
 * An object with the following properties:

   * ``enabled``: same as the Boolean value above
   * ``classes``: same as the String value above
   * ``tooltip``: a tooltip to apply to this year, via the ``title`` HTML attribute

beforeShowDecade
----------------

Function(Date).  Default: $.noop

A function that takes a date as a parameter and returns one of the following values:

 * undefined to have no effect
 * A Boolean, indicating whether or not this year is selectable
 * A String representing additional CSS classes to apply to the year's cell
 * An object with the following properties:

   * ``enabled``: same as the Boolean value above
   * ``classes``: same as the String value above
   * ``tooltip``: a tooltip to apply to this year, via the ``title`` HTML attribute

beforeShowCentury
-----------------

Function(Date).  Default: $.noop

A function that takes a date as a parameter and returns one of the following values:

 * undefined to have no effect
 * A Boolean, indicating whether or not this year is selectable
 * A String representing additional CSS classes to apply to the year's cell
 * An object with the following properties:

   * ``enabled``: same as the Boolean value above
   * ``classes``: same as the String value above
   * ``tooltip``: a tooltip to apply to this year, via the ``title`` HTML attribute

calendarWeeks
-------------

Boolean. Default: false

Whether or not to show week numbers to the left of week rows.

.. figure:: _static/screenshots/option_calendarweeks.png
    :align: center

clearBtn
--------

Boolean.  Default: false

If true, displays a "Clear" button at the bottom of the datepicker to clear the input value. If "autoclose" is also set to true, this button will also close the datepicker.

.. figure:: _static/screenshots/option_clearbtn.png
    :align: center

container
---------

String.  Default: "body"

Appends the date picker popup to a specific element; eg: container: '#picker-container' (will default to "body")

.. _daysofweekdisabled:

datesDisabled
-------------

String, Array.  Default: []

Array of date strings or a single date string formatted in the given date format

.. _defaultviewdate:

daysOfWeekDisabled
------------------

String, Array.  Default: []

Days of the week that should be disabled. Values are 0 (Sunday) to 6 (Saturday). Multiple values should be comma-separated. Example: disable weekends: ``'06'`` or ``'0,6'`` or ``[0,6]``.

.. figure:: _static/screenshots/option_daysofweekdisabled.png
    :align: center

.. _daysofweekhighlighted:

daysOfWeekHighlighted
---------------------

String, Array.  Default: []

Days of the week that should be highlighted. Values are 0 (Sunday) to 6 (Saturday). Multiple values should be comma-separated. Example: highlight weekends: ``'06'`` or ``'0,6'`` or ``[0,6]``.

.. _datesdisabled:

defaultViewDate
---------------

Object with keys ``year``, ``month``, and ``day``. Default: today

Date to view when initially opening the calendar. The internal value of the date remains today as default, but when the datepicker is first opened the calendar will open to ``defaultViewDate`` rather than today. If this option is not used, "today" remains the default view date. If the given object is missing any of the required keys, their defaults are:

 * ``year``: the current year
 * ``month``: 0
 * ``day``: 1

.. _enddate:

disableTouchKeyboard
--------------------

Boolean.  Default: false

If true, no keyboard will show on mobile devices

enableOnReadonly
----------------

Boolean. Default: true

If false the datepicker will not show on a readonly datepicker field.

endDate
-------

Date.  Default: End of time

The latest date that may be selected; all later dates will be disabled.

.. figure:: _static/screenshots/option_enddate.png
    :align: center

.. code-block:: html

    <input type="text" data-provide="datepicker" data-date-end-date="0d">

Will disable all dates after today.

forceParse
----------

Boolean.  Default: true

Whether or not to force parsing of the input value when the picker is closed.  That is, when an invalid date is left in the input field by the user, the picker will forcibly parse that value, and set the input's value to the new, valid date, conforming to the given `format`.

assumeNearbyYear
----------------

Boolean or Integer.  Default: false

If true, manually-entered dates with two-digit years, such as "5/1/15", will be parsed as "2015", not "15". If the year is less than 10 years in advance, the picker will use the current century, otherwise, it will use the previous one. For example "5/1/15" would parse to May 1st, 2015, but "5/1/97" would be May 1st, 1997.

To configure the number of years in advance that the picker will still use the current century, use an Integer instead of the Boolean true. E.g. "assumeNearbyYear: 20"

format
------

String.  Default: "mm/dd/yyyy"

The date format, combination of d, dd, D, DD, m, mm, M, MM, yy, yyyy.

* d, dd: Numeric date, no leading zero and leading zero, respectively.  Eg, 5, 05.
* D, DD: Abbreviated and full weekday names, respectively.  Eg, Mon, Monday.
* m, mm: Numeric month, no leading zero and leading zero, respectively.  Eg, 7, 07.
* M, MM: Abbreviated and full month names, respectively.  Eg, Jan, January
* yy, yyyy: 2- and 4-digit years, respectively.  Eg, 12, 2012.

Object.

Custom formatting options

* toDisplay: function (date, format, language) to convert date object to string, that will be stored in input field
* toValue: function (date, format, language) to convert string object to date, that will be used in date selection

::

    $('.datepicker').datepicker({
        format: {
            /*
             * Say our UI should display a week ahead,
             * but textbox should store the actual date.
             * This is useful if we need UI to select local dates,
             * but store in UTC
             */
            toDisplay: function (date, format, language) {
                var d = new Date(date);
                d.setDate(d.getDate() - 7);
                return d.toISOString();
            },
            toValue: function (date, format, language) {
                var d = new Date(date);
                d.setDate(d.getDate() + 7);
                return new Date(d);
            }
        },
        autoclose: true
    });

immediateUpdates
----------------

Boolean. Default: false

If true, selecting a year or month in the datepicker will update the input value immediately. Otherwise, only selecting a day of the month will update the input value immediately.

inputs
------

Array, jQuery. Default: None

A list of inputs to be used in a range picker, which will be attached to the selected element.  Allows for explicitly creating a range picker on a non-standard element.

.. code-block:: html

        <input type="text" class="actual_range">
        <input type="text" class="actual_range">

::

    $('#event_period').datepicker({
        inputs: $('.actual_range')
    });

keyboardNavigation
------------------

Boolean.  Default: true

Whether or not to allow date navigation by arrow keys.

language
--------

String.  Default: "en"

The IETF code (eg  "en" for English, "pt-BR" for Brazilian Portuguese) of the language to use for month and day names.  These will also be used as the input's value (and subsequently sent to the server in the case of form submissions).  If a full code (eg "de-DE") is supplied the picker will first check for an "de-DE" language and if not found will fallback and check for a "de" language.  If an unknown language code is given, English will be used.  See :doc:`i18n`.

.. figure:: _static/screenshots/option_language.png
    :align: center

maxViewMode
-----------

Number, String.  Default: 4, "centuries"

Set a maximum limit for the view mode.  Accepts: "days" or 0, "months" or 1, "years" or 2, "decades" or 3, and "centuries" or 4.
Gives the ability to pick only a day, a month, a year or a decade.  The day is set to the 1st for "months", the month is set to January for "years", the year is set to the first year from the decade for "decades", and the year is set to the first from the millennium for "centuries".

minViewMode
-----------

Number, String.  Default: 0, "days"

Set a minimum limit for the view mode.  Accepts: "days" or 0, "months" or 1, "years" or 2, "decades" or 3, and "centuries" or 4.
Gives the ability to pick only a month, a year or a decade.  The day is set to the 1st for "months", and the month is set to January for "years", the year is set to the first year from the decade for "decades", and the year is set to the first from the millennium for "centuries".

multidate
---------

Boolean, Number.  Default: false

Enable multidate picking.  Each date in month view acts as a toggle button, keeping track of which dates the user has selected in order.  If a number is given, the picker will limit how many dates can be selected to that number, dropping the oldest dates from the list when the number is exceeded.  ``true`` equates to no limit.  The input's value (if present) is set to a string generated by joining the dates, formatted, with ``multidateSeparator``.

For selecting 2 dates as a range please see :ref:`daterange`

.. figure:: _static/screenshots/option_multidate.png
    :align: center

multidateSeparator
------------------

String.  Default: ","

The string that will appear between dates when generating the input's value.  When parsing the input's value for a multidate picker, this will also be used to split the incoming string to separate multiple formatted dates; as such, it is highly recommended that you not use a string that could be a substring of a formatted date (eg, using '-' to separate dates when your format is 'yyyy-mm-dd').

orientation
-----------

String.  Default: "auto"

A space-separated string consisting of one or two of "left" or "right", "top" or "bottom", and "auto" (may be omitted); for example, "top left", "bottom" (horizontal orientation will default to "auto"), "right" (vertical orientation will default to "auto"), "auto top".  Allows for fixed placement of the picker popup.

"orientation" refers to the location of the picker popup's "anchor"; you can also think of it as the location of the trigger element (input, component, etc) relative to the picker.

"auto" triggers "smart orientation" of the picker.  Horizontal orientation will default to "left" and left offset will be tweaked to keep the picker inside the browser viewport; vertical orientation will simply choose "top" or "bottom", whichever will show more of the picker in the viewport.

.. _startdate:

showOnFocus
-----------

Boolean.  Default: true

If false, the datepicker will be prevented from showing when the input field associated with it receives focus.

startDate
---------

Date.  Default: Beginning of time

The earliest date that may be selected; all earlier dates will be disabled.

.. figure:: _static/screenshots/option_startdate.png
    :align: center

startView
---------

Number, String.  Default: 0, "month"

The view that the datepicker should show when it is opened.  Accepts values of 0 or "month" for month view (the default), 1 or "year" for the 12-month overview, 2 or "decade" for the 10-year overview, 3 or "century" for the 10-decade overview, and 4 or "millennium" for the 10-century overview.  Useful for date-of-birth datepickers.

templates
---------

Object. Default:

::

    {
        leftArrow: '«',
        rightArrow: '»'
    }

The templates used to generate some parts of the picker. Each property must be a string with only text, or valid html.
You can use this property to use custom icons libs. for example:

::

    {
        leftArrow: '',
        rightArrow: ''
    }

title
-----

String. Default: ""

The string that will appear on top of the datepicker. If empty the title will be hidden.

todayBtn
--------

Boolean, "linked".  Default: false

If true or "linked", displays a "Today" button at the bottom of the datepicker to select the current date.  If true, the "Today" button will only move the current date into view; if "linked", the current date will also be selected.

.. figure:: _static/screenshots/option_todaybtn.png
    :align: center

todayHighlight
--------------

Boolean.  Default: false

If true, highlights the current date.

.. figure:: _static/screenshots/option_todayhighlight.png
    :align: center

toggleActive
------------

Boolean. Default: false

If true, selecting the currently active date in the datepicker will unset the respective date. This option is always true when the multidate option is being used.

weekStart
---------

Integer.  Default: 0

Day of the week start. 0 (Sunday) to 6 (Saturday)

.. figure:: _static/screenshots/option_weekstart.png
    :align: center

zIndexOffset
------------

Integer.  Default: 10

The CSS z-index of the open datepicker is the maximum z-index of the input and all of its DOM ancestors *plus* the ``zIndexOffset``.


text:
package it.unitn.bd.bfs;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import it.unitn.bd.bfs.graph.Color;
import it.unitn.bd.bfs.graph.Vertex;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

/**
 * Useful utils for Graph representation conversion
 *
 * @see Vertex
 * @see Color
 */
public abstract class GraphFileUtil {

    private static final Splitter SPACE = Splitter.on(" ");
    private static final Joiner NEW_LINE = Joiner.on("\n");

    /**
     * Defines the starting point for BFS algorithm
     */
    private final static int SOURCE_VERTEX = 0;

    /**
     * Converts a file from the "Algorithm" book from undirected graph
     * into appropriate bi-directed file structure for MapReduce process
     *

     * Creates new file in format "problemFile_0" where "_0" is the initial state
     * that will be incremented during the intermediate results
     *

     * First vertex with the lowest key will be colored GRAY with 0 distance,
     * thus indicating the starting point of single-source path
     *

     * Other vertices will be colored WHITE with positive infinity distance
     *
     * @param problemFile of the Robert Sedgewick
     * @throws IOException if cannot write to file system
     */
    public static void convert(String problemFile) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(problemFile))));

        int vertexCount = Integer.parseInt(reader.readLine());
        Map<Integer, Vertex> vertices = new HashMap<>(vertexCount);
        LinkedList<Integer> path = new LinkedList<Integer>() {{
            add(SOURCE_VERTEX);
        }};
        vertices.put(SOURCE_VERTEX, new Vertex(SOURCE_VERTEX, new HashSet<Integer>(), path, 0, Color.GRAY));
        for (int i = 1; i < vertexCount; i++) {
            vertices.put(i, new Vertex(i, new HashSet<Integer>(), path, Integer.MAX_VALUE, Color.WHITE));
        }

        @SuppressWarnings("UnusedAssignment")
        String line = reader.readLine(); // number of edges [unused]
        while ((line = reader.readLine()) != null) {
            List<String> pair = SPACE.splitToList(line);
            int vertex1 = Integer.parseInt(pair.get(0));
            int vertex2 = Integer.parseInt(pair.get(1));
            vertices.get(vertex1).addNeighbour(vertex2);
            vertices.get(vertex2).addNeighbour(vertex1);
        }

        Files.write(Paths.get(problemFile + "_0"), NEW_LINE.join(vertices.values()).getBytes(), StandardOpenOption.CREATE);
    }
}


text:
UFW Rules setup
##############

Ansible playbook rule for setting up UFW. With support for IPv4/IPv6 forwarding.

Requirements
---------

Testing on Ubuntu 16.04

Variables
---------
- default.yml
Explanation:
```yaml

ufw_kernel_modules:  	       #Set iptables kernel modules
ufw_policy:  		       #Set default policy to deny/allow

ufw_forwarding: []             #IPv4 forwarding rules
  - comment:                   #Comment                  ; Not yet used.
    incomming_dev:             #Incomming interface
    incomming_network:         #Incomming network/subnet
    outgoing_dev:              #Outgoing interface
    outgoing_network:          #Outgoing network/subnet
    masquerading:              #Enable masquerading (boolean)
    conntrack_state:           #Incomming traffic ctstat setting
    reroute: []                #Reroute outgoing IP of host (Useful for internal subnets)
      - comment:               #Comment                  ; Not yet used.
        routed_ip:             #Reroute IP
        source_ip:             #Source is internal ip where is routed out
    forwards: []               #Port forwarding
      - comment:               #Comment                  ; Not yet used.
        protocols: []          #Protocol. TCP/UDP as array
        allowed_sources: []    #Allowed IPs   (TODO)
        incomming_ip:          #Orignal destiantion ip
        incomming_port:        #Orignal destiantion port
        destination_ip:        #Outgoing IP addresss
        destination_port:      #Outgoing Port addresss

ufw.forwarding6: []            #IPv4 forwarding rules
  - comment:                   #Comment                  ; Not yet used.
    incomming_dev:             #Incomming interface
    incomming_network:         #Incomming network/subnet
    outgoing_dev:              #Outgoing interface
    outgoing_network:          #Outgoing network/subnet
    conntrack_state:           #Incomming traffic ctstat setting
    masquerading:              #Enable masquerading (boolean)
    forwards: []               #Port forwarding
      - comment:               #Comment                  ; Not yet used.
        incomming_ip:          #Orignal destiantion ip   ; Only used when masquerading is enabled
        incomming_port:        #Orignal destiantion port ; Only used when masquerading is enabled
        protocols: []          #Protocol
        destination_ip:        #Outgoing IP addresss
        destination_port:      #Outgoing Port addresss

```

Custom rules
------------

If you want to add custom rules to you machine(s) just use UFW module of ansible:
http://docs.ansible.com/ansible/ufw_module.html

Example playbook
----------------

Simple example with custom ufw rules
```yaml
- name: Setup UFW
  hosts: all
  roles:
    - ufw

- name: Custom UFW rules
  hosts: all
  tasks:
    - name: Allow OpenSSH on port 22
      ufw: rule=allow name=OpenSSH
    - name: Allow HTTP
      ufw: rule=allow port=80 proto=tcp
    - name: Allow HTTPS
      ufw: rule=allow port=https proto=tcp
    - name: Allow port 8443 from 1 host
      ufw: rule=allow interface="{{ item.incomming_dev }}" direction=in proto=tcp src="2001:db8:1337:beef:cafe::1" to_port=8443
      with_items:
        - "{{ ufw.forwarding6 }}"

```

Licence
-------

MIT

Author
-------

Egbert Verhage <egbert@eggiecode.org>


text:
.class public Landroid/support/v4/os/EnvironmentCompat;
.super Ljava/lang/Object;
.source "EnvironmentCompat.java"

# static fields
.field public static final MEDIA_UNKNOWN:Ljava/lang/String; = "unknown"

.field private static final TAG:Ljava/lang/String; = "EnvironmentCompat"

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 30
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static getStorageState(Ljava/io/File;)Ljava/lang/String;
    .locals 7
    .param p0, "path"    # Ljava/io/File;

    .prologue
    .line 56
    sget v3, Landroid/os/Build$VERSION;->SDK_INT:I

    .line 57
    .local v3, "version":I
    const/16 v4, 0x13

    if-lt v3, v4, :cond_0

    .line 58
    invoke-static {p0}, Landroid/support/v4/os/EnvironmentCompatKitKat;->getStorageState(Ljava/io/File;)Ljava/lang/String;

    move-result-object v4

    .line 73
    :goto_0
    return-object v4

    .line 62
    :cond_0
    :try_start_0
    invoke-virtual {p0}, Ljava/io/File;->getCanonicalPath()Ljava/lang/String;

    move-result-object v1

    .line 63
    .local v1, "canonicalPath":Ljava/lang/String;
    invoke-static {}, Landroid/os/Environment;->getExternalStorageDirectory()Ljava/io/File;

    move-result-object v4

    invoke-virtual {v4}, Ljava/io/File;->getCanonicalPath()Ljava/lang/String;

    move-result-object v0

    .line 66
    .local v0, "canonicalExternal":Ljava/lang/String;
    invoke-virtual {v1, v0}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z

    move-result v4

    if-eqz v4, :cond_1

    .line 67
    invoke-static {}, Landroid/os/Environment;->getExternalStorageState()Ljava/lang/String;
    :try_end_0
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v4

    goto :goto_0

    .line 69
    .end local v0    # "canonicalExternal":Ljava/lang/String;
    .end local v1    # "canonicalPath":Ljava/lang/String;
    :catch_0
    move-exception v2

    .line 70
    .local v2, "e":Ljava/io/IOException;
    const-string v4, "EnvironmentCompat"

    new-instance v5, Ljava/lang/StringBuilder;

    invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V

    const-string v6, "Failed to resolve canonical path: "

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-virtual {v5, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v5

    invoke-static {v4, v5}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I

    .line 73
    .end local v2    # "e":Ljava/io/IOException;
    :cond_1
    const-string v4, "unknown"

    goto :goto_0
.end method


text:
<?php

/**
 * This class defines the structure of the 'sf_review' table.
 *
 *
 * This class was autogenerated by Propel 1.4.1 on:
 *
 * Fri Apr 29 23:44:19 2011
 *
 *
 * This map class is used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    plugins.sfReviewPlugin.lib.model.map
 */
class SfReviewTableMap extends TableMap {

	/**
	 * The (dot-path) name of this class
	 */
	const CLASS_NAME = 'plugins.sfReviewPlugin.lib.model.map.SfReviewTableMap';

	/**
	 * Initialize the table attributes, columns and validators
	 * Relations are not initialized by this method since they are lazy loaded
	 *
	 * @return     void
	 * @throws     PropelException
	 */
	public function initialize()
	{
	  // attributes
		$this->setName('sf_review');
		$this->setPhpName('SfReview');
		$this->setClassname('SfReview');
		$this->setPackage('plugins.sfReviewPlugin.lib.model');
		$this->setUseIdGenerator(true);
		// columns
		$this->addPrimaryKey('ID', 'Id', 'INTEGER', true, 11, null);
		$this->addColumn('ENTITY_ID', 'EntityId', 'INTEGER', false, 11, null);
		$this->addColumn('VALUE', 'Value', 'INTEGER', true, 11, 0);
		$this->addForeignKey('SF_GUARD_USER_ID', 'SfGuardUserId', 'INTEGER', 'sf_guard_user', 'ID', true, 11, null);
		$this->addForeignKey('SF_REVIEW_TYPE_ID', 'SfReviewTypeId', 'INTEGER', 'sf_review_type', 'ID', false, 11, null);
		$this->addForeignKey('SF_REVIEW_STATUS_ID', 'SfReviewStatusId', 'INTEGER', 'sf_review_status', 'ID', true, 11, null);
		$this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null);
		$this->addColumn('COOKIE', 'Cookie', 'VARCHAR', false, 45, null);
		$this->addColumn('IP_ADDRESS', 'IpAddress', 'VARCHAR', false, 45, null);
		$this->addColumn('TEXT', 'Text', 'VARCHAR', false, 420, null);
		$this->addColumn('MODIFIED_AT', 'ModifiedAt', 'TIMESTAMP', false, null, null);
		$this->addColumn('CULTURE', 'Culture', 'VARCHAR', false, 5, null);
		$this->addForeignKey('SF_REVIEW_ID', 'SfReviewId', 'INTEGER', 'sf_review', 'ID', false, 11, null);
		$this->addColumn('BALANCE', 'Balance', 'INTEGER', false, 11, 0);
		$this->addColumn('IS_ACTIVE', 'IsActive', 'BOOLEAN', true, null, true);
		$this->addColumn('TO_FB', 'ToFb', 'BOOLEAN', true, null, false);
		$this->addColumn('SOURCE', 'Source', 'VARCHAR', false, 64, null);
		$this->addColumn('ANONYMOUS', 'Anonymous', 'BOOLEAN', true, null, false);
		$this->addColumn('TO_TW', 'ToTw', 'BOOLEAN', true, null, false);
		// validators
	} // initialize()

	/**
	 * Build the RelationMap objects for this table relationships
	 */
	public function buildRelations()
	{
    $this->addRelation('sfGuardUser', 'sfGuardUser', RelationMap::MANY_TO_ONE, array('sf_guard_user_id' => 'id', ), 'RESTRICT', 'RESTRICT');
    $this->addRelation('SfReviewType', 'SfReviewType', RelationMap::MANY_TO_ONE, array('sf_review_type_id' => 'id', ), 'RESTRICT', 'RESTRICT');
    $this->addRelation('SfReviewStatus', 'SfReviewStatus', RelationMap::MANY_TO_ONE, array('sf_review_status_id' => 'id', ), 'RESTRICT', 'RESTRICT');
    $this->addRelation('SfReviewRelatedBySfReviewId', 'SfReview', RelationMap::MANY_TO_ONE, array('sf_review_id' => 'id', ), 'RESTRICT', 'RESTRICT');
    $this->addRelation('SfReviewRelatedBySfReviewId', 'SfReview', RelationMap::ONE_TO_MANY, array('id' => 'sf_review_id', ), 'RESTRICT', 'RESTRICT');
    $this->addRelation('SfReviewAttach', 'SfReviewAttach', RelationMap::ONE_TO_MANY, array('id' => 'sf_review_id', ), 'RESTRICT', 'RESTRICT');
    $this->addRelation('SfReviewModeration', 'SfReviewModeration', RelationMap::ONE_TO_MANY, array('id' => 'sf_review_id', ), 'RESTRICT', 'RESTRICT');
	} // buildRelations()

	/**
	 *
	 * Gets the list of behaviors registered for this table
	 *
	 * @return array Associative array (name => parameters) of behaviors
	 */
	public function getBehaviors()
	{
		return array(
			'symfony' => array('form' => 'true', 'filter' => 'true', ),
			'symfony_behaviors' => array(),
			'symfony_timestampable' => array('create_column' => 'created_at', ),
		);
	} // getBehaviors()

} // SfReviewTableMap


text:
class ScheduledChore < ApplicationRecord
  belongs_to :chore
  belongs_to :site

  after_initialize :populate_due
  validates_presence_of :due

  def populate_due
    return unless due.blank?

    self.due = chore&.next_due_date
  end
end

# == Schema Information
#
# Table name: scheduled_chores
#
#  id         :bigint(8)        not null, primary key
#  due        :datetime
#  chore_id   :bigint(8)
#  site_id    :bigint(8)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
# Indexes
#
#  index_scheduled_chores_on_chore_id  (chore_id)
#  index_scheduled_chores_on_site_id   (site_id)
#
# Foreign Keys
#
#  fk_rails_...  (chore_id => chores.id)
#  fk_rails_...  (site_id => sites.id)
#


text:
namespace reporting {

MetricReportingController::MetricReportingController(
    ReportingSettings* reporting_settings,
    const std::string& setting_path,
    bool setting_enabled_default_value,
    base::RepeatingClosure on_setting_enabled,
    base::RepeatingClosure on_setting_disabled)
    : reporting_settings_(reporting_settings),
      setting_path_(setting_path),
      setting_enabled_default_value_(setting_enabled_default_value),
      on_setting_enabled_(std::move(on_setting_enabled)),
      on_setting_disabled_(std::move(on_setting_disabled)) {
  UpdateSetting();

  subscription_ = reporting_settings_->AddSettingsObserver(
      setting_path_,
      base::BindRepeating(&MetricReportingController::UpdateSetting,
                          base::Unretained(this)));
}

MetricReportingController::~MetricReportingController() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

void MetricReportingController::UpdateSetting() {
  CHECK(base::SequencedTaskRunnerHandle::IsSet());
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  base::OnceClosure update_setting_cb = base::BindOnce(
      &MetricReportingController::UpdateSetting, weak_factory_.GetWeakPtr());
  bool trusted = reporting_settings_->PrepareTrustedValues(base::BindPostTask(
      base::SequencedTaskRunnerHandle::Get(), std::move(update_setting_cb)));
  if (!trusted) {
    return;
  }

  bool new_setting_enabled = setting_enabled_default_value_;
  reporting_settings_->GetBoolean(setting_path_, &new_setting_enabled);

  if (setting_enabled_ != new_setting_enabled) {
    setting_enabled_ = new_setting_enabled;
    if (setting_enabled_) {
      on_setting_enabled_.Run();
    } else {
      on_setting_disabled_.Run();
    }
  }
}
}  // namespace reporting


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<title>Glyr is a search engine for music related metadata</title>
Glyr is a search engine for music related metadata

The finest search you can buy for no money TM

It comes both in a command-line interface tool and as a C library, both with an easy to use interface.

The sort of metadata glyr is searching (and downloading) is usually the data you see in your musicplayer.

And indeed, originally it was written to serve as internally library for a musicplayer, but has been extended to

work as a standalone program which is able to download:

Getter	Description

cover	Coverart (front images supported only)

lyrics	Songtext

artistphotos	Photos of a certain band (press or live)

artistbio	Artist biography from various sites

review	album reviews from various sites

albumlist	A list of albums from a specific artist.

tags	Tags, either related to artist, album or title

relations	links to wikipedia, myspace, musicbrainz ...

similarartists	similar artists

similarsongs	similar songs

tracklist	tracklists of an album

guitartabs	guitartabs in textual form

backdrops	 Large artist photos, suitable for backgrounds

Terminology:

To prevent disambiguation the following terms are used below:

* glyrc is the command-line interface to libglyr.

* libglyr is the library behind, which may be used by your program.

* a getter is a type of metadata to download, e.g. cover, sometimes also called fetcher

* a provider is a source libglyr queries in order to find the data.

* glyros is the ruby wrapper for this lib. Currently it is not maintained.

FEATURES

Many built-in providers (46 at time of writing, ~30 distinct sites), high success-rate (the longer the search, the higher the risk :))

Portable: Windows and Linux are supported (Developement on Linux) see 1 for Mac OSX,

Fuzzy matching: Search providers with Levenshtein algorithm to eliminate typos and enhance search results.

Decent Unicode support: All sort of valid UTF8 is taken, and UTf8 output can be forced.

Fast Download: libcurl is used internally, and sources are searched in parallel, unneeded data is not downloaded if possible.

Lightweight dependencies: libcurl, glib and sqlite (for caching) - typical linux systems have those installed.

Download of a user defined amount of items, glyrc cover -a Foo -b Bar -n 30 tries to load 30 covers of album 'Bar' by artist 'Foo'.

Grouped download: Query providers by descending Accuray / Speed; controllable by the user over the qsratio

Optional download of images, URL is returned otherwise - so it can act a bit like a search-engine.

Free Software licensed under the terms of the GPLv3

libglyr is portable, easy, threadsafe and lowlevel enough for everyone.

...lots of other options like min/max size for images.

A built-in cache to store the metadata (using SQLite)

GETTING STARTED

Compiling

See the compile page.

libglyr:

See the examples in src/examples for a quickstart.

There's also a more gentle (and brief) introduction.

Also see the API Reference

Please note: Since version 1.0.0 the API will be stable, and will only be open for extensions.

glyrc:

Please refer to glyrc -h which gives you a brief introduction to the arguments you can pass,

See the wiki for more detailed information about the options.

FAQ

Anyone using it already?

GMPC

Pragha

Freya

lyvi

Glyr.. such a silly name! Why?

Indeed. Should have named it 'Glyros' (too late, damnit).

Is it hard to write something with it?

Some knowledge of C might be required, but the code is straight forward most of the time.

Bash scripts are pretty straight-forward:

glyrc cover --artist Equilibrium --album Sagas --write '/tmp/:artist:_:album:.:format:' --callback 'sxiv ":path:"'

Additionally there are bindings to Python and Ruby:

plyr by me (complete API).

ruby-glyr by meh (complete API).

How..how am I supposed to use it?

Well, as normal user you could use glyrc to retrieve some metadata in a batchlike fashion.

As developers you have lots of option, you could write glyr-plugins for musicplayers (gmpc!), set up a webserver with this,

hack up little scripts showing covers on the desktop.. everything related to musicmetadat is possible here.

You could also extend libglyr itself but that's a little harder.

Isn't there musicbrainz already?

The kind of metadata downloaded by glyr differs heavily from musicbrainz.

i.e. glyr finds metadata for musicplayers while musicbrainz finds data for CD Rippers and taggers.

Musicbrainz runs remotely on some server and uses a large database which is searched through lucene.

Glyr is a client program which hops over several sites and does not cache anything, unless you do it yourself.

You could of course let glyr run on a (remote) server, and cache all results to do something similiar.

There is coverarchive.org , but it does not seem to fully work yet. But it will be accessible once it does.

AUTHOR

See the AUTHORS file that comes in glyr's distribution.

See also COPYING to know about your rights.

I CAN HAZ HELP?

BUGS

If you found one: Meh. Sorry for that.

If you file a bugreport: Hey, thank you!

Use the Issue Tracker to share your find.

Alternatively you may drop me a mail at <sahib@online.de>

PATCHES

If you hacked one: Excellent! Send it to me via mail or see below.

If you want to add new providers you should look at the existing provider plugins to get an idea how to write one.

Starting with lib/cover/lastfm.c isn't a bad idea either, because it is one of the very simple ones.

Take the usual Git(Hub) approach:

# Fork this project

# Make your changes

# Make a Pull request

If you're not familiar with git, or just don't like it,

you can also send me the patch via mail: <sahib@online.de>

Thanks for any help in advance!

WRITE SOFTWARE THAT USES GLYR

May sound strange, but you're giving me a reason to maintain it, write new providers etc.

Also bugreports (well, there are no bugs, just in case) are appreciated, or just questions.

Those help to make the documentation more clear.

DONATE

You also might consider a small (CS-Students are already motivated by 1 Cent ) donation if you use feel like it:

(For now only possible via Flattr or Paypal , you gonna need an account there - Sorry)

DISCLAIMER

As usual, no warranty is granted that this software works like expected.

Refer to the GPLv3 copy you got with libglyr. It is here.

Glyr is just a way to find the data, it does not own any rights on the data it found.

All retrieved items are copyrighted by their respective copyright owners.

Refer to the provider's terms of use. Every item you get from libglyr contains the name and a url to the provider, so lookup there terms of use there.

[1] Glyr has not been tested on Mac OSX yet. If you own a Mac, any help with 'porting' glyr is highly appreciated. My guess would be that no to almost no changes need to be done though.


text:
package jb5n.api;

public interface MyMessageResource {

	@Message(defaultMessage = "OK")
	String ok();

	String cancel();

	String youHaveNREtries(int numberOfRetries);

	@Message(key = "no.default.key")
	String noDefaultKey();

	String missingResource();

	String myMessageResource();
}


text:
from itertools import combinations_with_replacement
from utils import divisors

abundant = filter(lambda n: sum(divisors(n)) > n, range(2, 29000))

u = set(range(1, 29000))
for i in combinations_with_replacement(abundant, 2):
    u.discard(sum(i))

print sum(u)


text:
package codecs

import (
	"github.com/driskell/log-courier/src/lc-lib/core"
	"testing"
)

var filter_lines []string

func createFilterCodec(unused map[string]interface{}, callback core.CodecCallbackFunc, t *testing.T) core.Codec {
	config := core.NewConfig()

	factory, err := NewFilterCodecFactory(config, "", unused, "filter")
	if err != nil {
		t.Logf("Failed to create filter codec: %s", err)
		t.FailNow()
	}

	return factory.NewCodec(callback, 0)
}

func checkFilter(start_offset int64, end_offset int64, text string) {
	filter_lines = append(filter_lines, text)
}

func TestFilter(t *testing.T) {
	filter_lines = make([]string, 0, 1)

	codec := createFilterCodec(map[string]interface{}{
		"patterns": []string{"^NEXT line$"},
		"negate":   false,
	}, checkFilter, t)

	// Send some data
	codec.Event(0, 1, "DEBUG First line")
	codec.Event(2, 3, "NEXT line")
	codec.Event(4, 5, "ANOTHER line")
	codec.Event(6, 7, "DEBUG Next line")

	if len(filter_lines) != 1 {
		t.Error("Wrong line count received")
	} else if filter_lines[0] != "NEXT line" {
		t.Error("Wrong line[0] received: %s", filter_lines[0])
	}

	offset := codec.Teardown()
	if offset != 7 {
		t.Error("Teardown returned incorrect offset: ", offset)
	}
}

func TestFilterNegate(t *testing.T) {
	filter_lines = make([]string, 0, 1)

	codec := createFilterCodec(map[string]interface{}{
		"patterns": []string{"^NEXT line$"},
		"negate":   true,
	}, checkFilter, t)

	// Send some data
	codec.Event(0, 1, "DEBUG First line")
	codec.Event(2, 3, "NEXT line")
	codec.Event(4, 5, "ANOTHER line")
	codec.Event(6, 7, "DEBUG Next line")

	if len(filter_lines) != 3 {
		t.Error("Wrong line count received")
	} else if filter_lines[0] != "DEBUG First line" {
		t.Error("Wrong line[0] received: %s", filter_lines[0])
	} else if filter_lines[1] != "ANOTHER line" {
		t.Error("Wrong line[1] received: %s", filter_lines[1])
	} else if filter_lines[2] != "DEBUG Next line" {
		t.Error("Wrong line[2] received: %s", filter_lines[2])
	}

	offset := codec.Teardown()
	if offset != 7 {
		t.Error("Teardown returned incorrect offset: ", offset)
	}
}

func TestFilterMultiple(t *testing.T) {
	filter_lines = make([]string, 0, 1)

	codec := createFilterCodec(map[string]interface{}{
		"patterns": []string{"^NEXT line$", "^DEBUG First line$"},
		"negate":   false,
	}, checkFilter, t)

	// Send some data
	codec.Event(0, 1, "DEBUG First line")
	codec.Event(2, 3, "NEXT line")
	codec.Event(4, 5, "ANOTHER line")
	codec.Event(6, 7, "DEBUG Next line")

	if len(filter_lines) != 2 {
		t.Error("Wrong line count received")
	} else if filter_lines[0] != "DEBUG First line" {
		t.Error("Wrong line[0] received: %s", filter_lines[0])
	} else if filter_lines[1] != "NEXT line" {
		t.Error("Wrong line[1] received: %s", filter_lines[1])
	}

	offset := codec.Teardown()
	if offset != 7 {
		t.Error("Teardown returned incorrect offset: ", offset)
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/SNSRequest.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/SNSRequest</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>SNSRequest.h</DeclaredIn>

			<NodeRef refid="1235"/>
		</Token>

	</File>
</Tokens>


text:
/* 2013-01-06 Camilla Löwy <elmindreda@glfw.org>
 *
 * Added casts from time_t to DWORD to avoid warnings on VC++.
 * Fixed time retrieval on POSIX systems.
 */

#include "tinycthread.h"
#include <stdlib.h>

/* Platform specific includes */
#if defined(_TTHREAD_POSIX_)
#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <sys/time.h>
#include <unistd.h>
#elif defined(_TTHREAD_WIN32_)
#include <process.h>
#include <sys/timeb.h>
#endif

/* Standard, good-to-have defines */
#ifndef NULL
#define NULL (void *)0
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

int mtx_init(mtx_t *mtx, int type) {
#if defined(_TTHREAD_WIN32_)
  mtx->mAlreadyLocked = FALSE;
  mtx->mRecursive = type & mtx_recursive;
  InitializeCriticalSection(&mtx->mHandle);
  return thrd_success;
#else
  int ret;
  pthread_mutexattr_t attr;
  pthread_mutexattr_init(&attr);
  if (type & mtx_recursive) {
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  }
  ret = pthread_mutex_init(mtx, &attr);
  pthread_mutexattr_destroy(&attr);
  return ret == 0 ? thrd_success : thrd_error;
#endif
}

void mtx_destroy(mtx_t *mtx) {
#if defined(_TTHREAD_WIN32_)
  DeleteCriticalSection(&mtx->mHandle);
#else
  pthread_mutex_destroy(mtx);
#endif
}

int mtx_lock(mtx_t *mtx) {
#if defined(_TTHREAD_WIN32_)
  EnterCriticalSection(&mtx->mHandle);
  if (!mtx->mRecursive) {
    while (mtx->mAlreadyLocked) Sleep(1000); /* Simulate deadlock... */
    mtx->mAlreadyLocked = TRUE;
  }
  return thrd_success;
#else
  return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error;
#endif
}

int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) {
  /* FIXME! */
  (void)mtx;
  (void)ts;
  return thrd_error;
}

int mtx_trylock(mtx_t *mtx) {
#if defined(_TTHREAD_WIN32_)
  int ret = TryEnterCriticalSection(&mtx->mHandle) ? thrd_success : thrd_busy;
  if ((!mtx->mRecursive) && (ret == thrd_success) && mtx->mAlreadyLocked) {
    LeaveCriticalSection(&mtx->mHandle);
    ret = thrd_busy;
  }
  return ret;
#else
  return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy;
#endif
}

int mtx_unlock(mtx_t *mtx) {
#if defined(_TTHREAD_WIN32_)
  mtx->mAlreadyLocked = FALSE;
  LeaveCriticalSection(&mtx->mHandle);
  return thrd_success;
#else
  return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;
  ;
#endif
}

#if defined(_TTHREAD_WIN32_)
#define _CONDITION_EVENT_ONE 0
#define _CONDITION_EVENT_ALL 1
#endif

int cnd_init(cnd_t *cond) {
#if defined(_TTHREAD_WIN32_)
  cond->mWaitersCount = 0;

  /* Init critical section */
  InitializeCriticalSection(&cond->mWaitersCountLock);

  /* Init events */
  cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL);
  if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL) {
    cond->mEvents[_CONDITION_EVENT_ALL] = NULL;
    return thrd_error;
  }
  cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL) {
    CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]);
    cond->mEvents[_CONDITION_EVENT_ONE] = NULL;
    return thrd_error;
  }

  return thrd_success;
#else
  return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error;
#endif
}

void cnd_destroy(cnd_t *cond) {
#if defined(_TTHREAD_WIN32_)
  if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL) {
    CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]);
  }
  if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL) {
    CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]);
  }
  DeleteCriticalSection(&cond->mWaitersCountLock);
#else
  pthread_cond_destroy(cond);
#endif
}

int cnd_signal(cnd_t *cond) {
#if defined(_TTHREAD_WIN32_)
  int haveWaiters;

  /* Are there any waiters? */
  EnterCriticalSection(&cond->mWaitersCountLock);
  haveWaiters = (cond->mWaitersCount > 0);
  LeaveCriticalSection(&cond->mWaitersCountLock);

  /* If we have any waiting threads, send them a signal */
  if (haveWaiters) {
    if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0) {
      return thrd_error;
    }
  }

  return thrd_success;
#else
  return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error;
#endif
}

int cnd_broadcast(cnd_t *cond) {
#if defined(_TTHREAD_WIN32_)
  int haveWaiters;

  /* Are there any waiters? */
  EnterCriticalSection(&cond->mWaitersCountLock);
  haveWaiters = (cond->mWaitersCount > 0);
  LeaveCriticalSection(&cond->mWaitersCountLock);

  /* If we have any waiting threads, send them a signal */
  if (haveWaiters) {
    if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) {
      return thrd_error;
    }
  }

  return thrd_success;
#else
  return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error;
#endif
}

#if defined(_TTHREAD_WIN32_)
static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout) {
  int result, lastWaiter;

  /* Increment number of waiters */
  EnterCriticalSection(&cond->mWaitersCountLock);
  ++cond->mWaitersCount;
  LeaveCriticalSection(&cond->mWaitersCountLock);

  /* Release the mutex while waiting for the condition (will decrease
     the number of waiters when done)... */
  mtx_unlock(mtx);

  /* Wait for either event to become signaled due to cnd_signal() or
     cnd_broadcast() being called */
  result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout);
  if (result == WAIT_TIMEOUT) {
    return thrd_timeout;
  } else if (result == (int)WAIT_FAILED) {
    return thrd_error;
  }

  /* Check if we are the last waiter */
  EnterCriticalSection(&cond->mWaitersCountLock);
  --cond->mWaitersCount;
  lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) &&
               (cond->mWaitersCount == 0);
  LeaveCriticalSection(&cond->mWaitersCountLock);

  /* If we are the last waiter to be notified to stop waiting, reset the event
   */
  if (lastWaiter) {
    if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) {
      return thrd_error;
    }
  }

  /* Re-acquire the mutex */
  mtx_lock(mtx);

  return thrd_success;
}
#endif

int cnd_wait(cnd_t *cond, mtx_t *mtx) {
#if defined(_TTHREAD_WIN32_)
  return _cnd_timedwait_win32(cond, mtx, INFINITE);
#else
  return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error;
#endif
}

int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) {
#if defined(_TTHREAD_WIN32_)
  struct timespec now;
  if (clock_gettime(CLOCK_REALTIME, &now) == 0) {
    DWORD delta = (DWORD)((ts->tv_sec - now.tv_sec) * 1000 +
                          (ts->tv_nsec - now.tv_nsec + 500000) / 1000000);
    return _cnd_timedwait_win32(cond, mtx, delta);
  } else
    return thrd_error;
#else
  int ret;
  ret = pthread_cond_timedwait(cond, mtx, ts);
  if (ret == ETIMEDOUT) {
    return thrd_timeout;
  }
  return ret == 0 ? thrd_success : thrd_error;
#endif
}

/** Information to pass to the new thread (what to run). */
typedef struct {
  thrd_start_t mFunction; /**< Pointer to the function to be executed. */
  void *mArg;             /**< Function argument for the thread function. */
} _thread_start_info;

/* Thread wrapper function. */
#if defined(_TTHREAD_WIN32_)
static unsigned WINAPI _thrd_wrapper_function(void *aArg)
#elif defined(_TTHREAD_POSIX_)
static void *_thrd_wrapper_function(void *aArg)
#endif
{
  thrd_start_t fun;
  void *arg;
  int res;
#if defined(_TTHREAD_POSIX_)
  void *pres;
#endif

  /* Get thread startup information */
  _thread_start_info *ti = (_thread_start_info *)aArg;
  fun = ti->mFunction;
  arg = ti->mArg;

  /* The thread is responsible for freeing the startup information */
  free((void *)ti);

  /* Call the actual client thread function */
  res = fun(arg);

#if defined(_TTHREAD_WIN32_)
  return res;
#else
  pres = malloc(sizeof(int));
  if (pres != NULL) {
    *(int *)pres = res;
  }
  return pres;
#endif
}

int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) {
  /* Fill out the thread startup information (passed to the thread wrapper,
     which will eventually free it) */
  _thread_start_info *ti =
      (_thread_start_info *)malloc(sizeof(_thread_start_info));
  if (ti == NULL) {
    return thrd_nomem;
  }
  ti->mFunction = func;
  ti->mArg = arg;

  /* Create the thread */
#if defined(_TTHREAD_WIN32_)
  *thr = (HANDLE)_beginthreadex(NULL, 0, _thrd_wrapper_function, (void *)ti, 0,
                                NULL);
#elif defined(_TTHREAD_POSIX_)
  if (pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0) {
    *thr = 0;
  }
#endif

  /* Did we fail to create the thread? */
  if (!*thr) {
    free(ti);
    return thrd_error;
  }

  return thrd_success;
}

thrd_t thrd_current(void) {
#if defined(_TTHREAD_WIN32_)
  return GetCurrentThread();
#else
  return pthread_self();
#endif
}

int thrd_detach(thrd_t thr) {
  /* FIXME! */
  (void)thr;
  return thrd_error;
}

int thrd_equal(thrd_t thr0, thrd_t thr1) {
#if defined(_TTHREAD_WIN32_)
  return thr0 == thr1;
#else
  return pthread_equal(thr0, thr1);
#endif
}

void thrd_exit(int res) {
#if defined(_TTHREAD_WIN32_)
  ExitThread(res);
#else
  void *pres = malloc(sizeof(int));
  if (pres != NULL) {
    *(int *)pres = res;
  }
  pthread_exit(pres);
#endif
}

int thrd_join(thrd_t thr, int *res) {
#if defined(_TTHREAD_WIN32_)
  if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED) {
    return thrd_error;
  }
  if (res != NULL) {
    DWORD dwRes;
    GetExitCodeThread(thr, &dwRes);
    *res = dwRes;
  }
#elif defined(_TTHREAD_POSIX_)
  void *pres;
  int ires = 0;
  if (pthread_join(thr, &pres) != 0) {
    return thrd_error;
  }
  if (pres != NULL) {
    ires = *(int *)pres;
    free(pres);
  }
  if (res != NULL) {
    *res = ires;
  }
#endif
  return thrd_success;
}

int thrd_sleep(const struct timespec *time_point, struct timespec *remaining) {
  struct timespec now;
#if defined(_TTHREAD_WIN32_)
  DWORD delta;
#else
  long delta;
#endif

  /* Get the current time */
  if (clock_gettime(CLOCK_REALTIME, &now) != 0)
    return -2;  // FIXME: Some specific error code?

#if defined(_TTHREAD_WIN32_)
  /* Delta in milliseconds */
  delta = (DWORD)((time_point->tv_sec - now.tv_sec) * 1000 +
                  (time_point->tv_nsec - now.tv_nsec + 500000) / 1000000);
  if (delta > 0) {
    Sleep(delta);
  }
#else
  /* Delta in microseconds */
  delta = (time_point->tv_sec - now.tv_sec) * 1000000L +
          (time_point->tv_nsec - now.tv_nsec + 500L) / 1000L;

  /* On some systems, the usleep argument must be < 1000000 */
  while (delta > 999999L) {
    usleep(999999);
    delta -= 999999L;
  }
  if (delta > 0L) {
    usleep((useconds_t)delta);
  }
#endif

  /* We don't support waking up prematurely (yet) */
  if (remaining) {
    remaining->tv_sec = 0;
    remaining->tv_nsec = 0;
  }
  return 0;
}

void thrd_yield(void) {
#if defined(_TTHREAD_WIN32_)
  Sleep(0);
#else
  sched_yield();
#endif
}

int tss_create(tss_t *key, tss_dtor_t dtor) {
#if defined(_TTHREAD_WIN32_)
  /* FIXME: The destructor function is not supported yet... */
  if (dtor != NULL) {
    return thrd_error;
  }
  *key = TlsAlloc();
  if (*key == TLS_OUT_OF_INDEXES) {
    return thrd_error;
  }
#else
  if (pthread_key_create(key, dtor) != 0) {
    return thrd_error;
  }
#endif
  return thrd_success;
}

void tss_delete(tss_t key) {
#if defined(_TTHREAD_WIN32_)
  TlsFree(key);
#else
  pthread_key_delete(key);
#endif
}

void *tss_get(tss_t key) {
#if defined(_TTHREAD_WIN32_)
  return TlsGetValue(key);
#else
  return pthread_getspecific(key);
#endif
}

int tss_set(tss_t key, void *val) {
#if defined(_TTHREAD_WIN32_)
  if (TlsSetValue(key, val) == 0) {
    return thrd_error;
  }
#else
  if (pthread_setspecific(key, val) != 0) {
    return thrd_error;
  }
#endif
  return thrd_success;
}

#if defined(_TTHREAD_EMULATE_CLOCK_GETTIME_)
int _tthread_clock_gettime(clockid_t clk_id, struct timespec *ts) {
#if defined(_TTHREAD_WIN32_)
  struct _timeb tb;
  _ftime(&tb);
  ts->tv_sec = (time_t)tb.time;
  ts->tv_nsec = 1000000L * (long)tb.millitm;
#else
  struct timeval tv;
  gettimeofday(&tv, NULL);
  ts->tv_sec = (time_t)tv.tv_sec;
  ts->tv_nsec = 1000L * (long)tv.tv_usec;
#endif
  return 0;
}
#endif  // _TTHREAD_EMULATE_CLOCK_GETTIME_


text:
package hudson.plugins.graph.series;

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

import javax.xml.namespace.QName;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import hudson.FilePath;
import hudson.model.AbstractBuild;

import org.kohsuke.stapler.DataBoundConstructor;

import org.xml.sax.InputSource;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import static javax.xml.xpath.XPathConstants.*;

/**
 * Represents a plot data series configuration from an XML file.
 *
 * @author Allen Reese
 *
 */
public class XMLSeries extends Series
{
    private String xpath;

    private String label;

    private String nodeType;

    @DataBoundConstructor
    public XMLSeries(String id, String file, String xpath, String nodeType, String label)
    {
        super(id, file);

        this.xpath = xpath;
        this.label = label;
        this.nodeType = nodeType;
    }

    public String getType()
    {
        return SeriesType.XML.toString();
    }

    @SuppressWarnings("unused")
    public String getXpath()
    {
        return xpath;
    }

    @SuppressWarnings("unused")
    public String getLabel()
    {
        return label;
    }

    @SuppressWarnings("unused")
    public String getNodeType()
    {
        return nodeType;
    }

    private QName getNodeQName()
    {
        return new QName("http://www.w3.org/1999/XSL/Transform", nodeType);
    }

    private String nodeToString(Object node)
    {
        if (BOOLEAN.equals(getNodeQName()))
        {
            return (Boolean) node ? "1" : "0";
        }

        return node.toString().trim();
    }

    private SeriesValue createPlotPoint(String value, String label, AbstractBuild build)
    {
        return new SeriesValue(value, label, build);
    }

    @Override
    protected List<SeriesValue> loadSeries(AbstractBuild build) throws IOException
    {
        List<SeriesValue> values = new ArrayList<SeriesValue>();

        FilePath seriesFile = new FilePath(build.getWorkspace(), getFile());

        try
        {
            if (!seriesFile.exists())
            {
                return values;
            }

            XPathExpression expression = XPathFactory.newInstance().newXPath().compile(xpath);

            InputSource source = null;

            try
            {
                source = new InputSource(seriesFile.read());

                Object xml = expression.evaluate(source, getNodeQName());

                if (NODESET.equals(getNodeQName()))
                {
                    NodeList list = (NodeList) xml;

                    for (int nodeIndex = 0; nodeIndex < list.getLength(); nodeIndex++)
                    {
                        Node node = list.item(nodeIndex);

                        String localLabel = node.getLocalName(), value = node.getTextContent();

                        if (localLabel != null && value != null)
                        {
                            values.add(createPlotPoint(value.trim(), localLabel, build));
                        }
                    }
                }
                else
                {
                    values.add(createPlotPoint(nodeToString(xml), label, build));
                }
            }
            finally
            {
                if (source != null)
                {
                    source.getByteStream().close();
                }
            }

            return values;
        }
        catch (XPathExpressionException e)
        {
            throw new RuntimeException(e);
        }
        catch (InterruptedException e)
        {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder("XMLSeries{");

        sb.append("file=").append(file).append(", ");
        sb.append("xpath=").append(xpath).append(", ");
        sb.append("label=").append(label).append(", ");
        sb.append("nodeType=").append(nodeType);

        return sb.append("}").toString();
    }
}


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

    <string name="app_name">rups</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_main2">MainActivity</string>
    <string name="title_activity_main_activity3">MainActivity3</string>

</resources>


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

namespace TileEngine
{
    ///
    /// Interface between users and QueueInternal, which is the actual value structure
    ///
    /// <typeparam name="T">Type of value stored</typeparam>
    /// <author>Colden Cullen</author>
    public class Queue<T>
    {
        #region Fields
        ///
        /// QueueInternal object that acts as actual queue
        ///
        QueueInternal<T> qi;

        ///
        /// Returns the total number of elements in the queue
        ///
        public int Count
        {
            get { return qi.Count; }
        }
        #endregion

        #region Indexer, Enumerator
        ///
        /// Indexer for List
        /// <param name="index">
        /// Index of List item to get or set</param>
        /// <returns>
        /// get: Data at index set: nothing</returns>
        public T this[ int index ]
        {
            get { return qi[ index ]; }
            set { qi[ index ] = value; }
        }

        ///
        /// Enumerator for for loops
        /// <returns></returns>
        public IEnumerator<T> GetEnumerator()
        {
            return qi.GetEnumerator();
        }
        #endregion

        #region Constructor
        ///
        /// Queue constructor
        ///
        public Queue()
        {
            qi = new QueueInternal<T>();
        }
        #endregion

        #region Enqueue
        ///
        /// Adds an element to the back of the queue
        ///
        /// <param name="value">
        /// The element to be added</param>
        public void Enqueue( T data )
        {
            qi.Enqueue( data );
        }
        #endregion

        #region Dequeue
        ///
        /// Removes the front element from the queue
        ///
        /// <returns>The front element</returns>
        public virtual T Dequeue()
        {
            return qi.Dequeue();
        }
        #endregion
    }
}


text:
package org.apache.logging.log4j.core.appender.db.jdbc;

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

/**
 * Tests the JDBC appender with the HyperSQL database (a.k.a. HSQLDB) in memory.
 */
public class JdbcHyperSqlAppenderTest extends AbstractJdbcAppenderTest {
    private static final String USER_ID = "sa";
    private static final String PASSWORD = "";

    public JdbcHyperSqlAppenderTest() {
        super("hsqldb");
    }

    /**
     * Referred from log4j2-hsqldb-factory-method.xml.
     */
    @SuppressWarnings("unused")
    public static Connection getConfigConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:hsqldb:mem:Log4j;ifexists=true", USER_ID, PASSWORD);
    }

    @Override
    protected Connection newConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:hsqldb:mem:Log4j", USER_ID, PASSWORD);
    }

    @Override
    protected String toCreateTableSqlString(final String tableName) {
        return "CREATE TABLE " + tableName + " ( " +
                    "id INTEGER IDENTITY, eventDate DATETIME, literalColumn VARCHAR(255), level VARCHAR(10), " +
                    "logger VARCHAR(255), message VARCHAR(1024), exception CLOB" +
                " )";
    }
}


text: @import url(http://fonts.googleapis.com/css?family=Lato:300,400,700,900);


text:
/* EEPROM module for Chrome EC */

#include "clock.h"
#include "console.h"
#include "eeprom.h"
#include "registers.h"
#include "timer.h"
#include "util.h"
#include "watchdog.h"

/* Size of EEPROM block in bytes */
#define EEPROM_BLOCK_SIZE 64

/* Count of EEPROM blocks */
static int block_count;

/*
 * Wait for the current EEPROM operation to finish; all operations but write
 * should normally finish in 4 system clocks, but worst case is up to
 * 1800ms if the EEPROM needs to do an internal page erase/copy.  We must
 * spin-wait for this delay, because EEPROM operations will fail if the chip
 * drops to sleep mode.
 */
static int wait_for_done(void)
{
	int j;

	for (j = 0; j < 20; j++) {  /* 20 * 100 ms = 2000 ms */
		uint64_t tstop = get_time().val + 100 * MSEC;
		while (get_time().val < tstop) {
			if (!(LM4_EEPROM_EEDONE & 0x01))
				return EC_SUCCESS;
		}
		watchdog_reload();
	}

	return EC_ERROR_UNKNOWN;
}

int eeprom_get_block_count(void)
{
	return block_count;
}

int eeprom_get_block_size(void)
{
	return EEPROM_BLOCK_SIZE;
}

int eeprom_read(int block, int offset, int size, char *data)
{
	uint32_t *d = (uint32_t *)data;
	int rv;

	if (block < 0 || block >= block_count ||
	    offset < 0 || offset > EEPROM_BLOCK_SIZE || offset & 3 ||
	    size < 0 || offset + size > EEPROM_BLOCK_SIZE || size & 3)
		return EC_ERROR_UNKNOWN;

	rv = wait_for_done();
	if (rv)
		return rv;

	LM4_EEPROM_EEBLOCK = block;
	if (LM4_EEPROM_EEBLOCK != block)
		return EC_ERROR_UNKNOWN;  /* Error setting block */

	LM4_EEPROM_EEOFFSET = offset >> 2;

	for (; size; size -= sizeof(uint32_t))
		*(d++) = LM4_EEPROM_EERDWRINC;

	return EC_SUCCESS;
}

int eeprom_write(int block, int offset, int size, const char *data)
{
	uint32_t *d = (uint32_t *)data;
	int rv;

	if (block < 0 || block >= block_count ||
	    offset < 0 || offset > EEPROM_BLOCK_SIZE || offset & 3 ||
	    size < 0 || offset + size > EEPROM_BLOCK_SIZE || size & 3)
		return EC_ERROR_UNKNOWN;

	rv = wait_for_done();
	if (rv)
		return rv;

	LM4_EEPROM_EEBLOCK = block;
	if (LM4_EEPROM_EEBLOCK != block)
		return EC_ERROR_UNKNOWN;  /* Error setting block */

	LM4_EEPROM_EEOFFSET = offset >> 2;

	/* Write 32 bits at a time; wait for each write to complete */
	for (; size; size -= sizeof(uint32_t)) {
		LM4_EEPROM_EERDWRINC = *(d++);

		rv = wait_for_done();
		if (rv)
			return rv;

		if (LM4_EEPROM_EEDONE & 0x10) {
			/* Failed due to write protect */
			return EC_ERROR_ACCESS_DENIED;
		} else if (LM4_EEPROM_EEDONE & 0x100) {
			/* Failed due to program voltage level */
			return EC_ERROR_UNKNOWN;
		}
	}

	return EC_SUCCESS;
}

int eeprom_hide(int block)
{
	/* Block 0 can't be hidden */
	if (block <= 0 || block >= block_count)
		return EC_ERROR_UNKNOWN;

	LM4_EEPROM_EEHIDE |= 1 << block;
	return EC_SUCCESS;
}

/*****************************************************************************/
/* Console commands */

static int command_eeprom_info(int argc, char **argv)
{
	ccprintf("%d blocks @ %d bytes, hide=0x%08x\n",
		 eeprom_get_block_count(), eeprom_get_block_size(),
		 LM4_EEPROM_EEHIDE);
	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(eeinfo, command_eeprom_info,
			NULL,
			"Print EEPROM info",
			NULL);

static int command_eeprom_read(int argc, char **argv)
{
	int block = 0;
	int offset = 0;
	char *e;
	int rv;
	uint32_t d;

	if (argc < 2)
		return EC_ERROR_PARAM_COUNT;

	block = strtoi(argv[1], &e, 0);
	if (*e)
		return EC_ERROR_PARAM1;

	if (argc > 2) {
		offset = strtoi(argv[2], &e, 0);
		if (*e)
			return EC_ERROR_PARAM2;
	}

	rv = eeprom_read(block, offset, sizeof(d), (char *)&d);
	if (rv == EC_SUCCESS)
		ccprintf("%d:%d = 0x%08x\n", block, offset, d);
	return rv;
}
DECLARE_CONSOLE_COMMAND(eeread, command_eeprom_read,
			"block [offset]",
			"Read a word of EEPROM",
			NULL);

static int command_eeprom_write(int argc, char **argv)
{
	int block = 0;
	int offset = 0;
	char *e;
	uint32_t d;

	if (argc < 4)
		return EC_ERROR_PARAM_COUNT;

	block = strtoi(argv[1], &e, 0);
	if (*e)
		return EC_ERROR_PARAM1;
	offset = strtoi(argv[2], &e, 0);
	if (*e)
		return EC_ERROR_PARAM2;
	d = strtoi(argv[3], &e, 0);
	if (*e)
		return EC_ERROR_PARAM3;

	ccprintf("Writing 0x%08x to %d:%d...\n", d, block, offset);
	return eeprom_write(block, offset, sizeof(d), (char *)&d);
}
DECLARE_CONSOLE_COMMAND(eewrite, command_eeprom_write,
			"block offset value",
			"Write a word of EEPROM",
			NULL);

#ifdef CONSOLE_COMMAND_EEHIDE
static int command_eeprom_hide(int argc, char **argv)
{
	int block = 0;
	char *e;

	if (argc < 2)
		return EC_ERROR_PARAM_COUNT;

	block = strtoi(argv[1], &e, 0);
	if (*e)
		return EC_ERROR_PARAM1;

	ccprintf("Hiding block %d\n", block);
	return eeprom_hide(block);
}
DECLARE_CONSOLE_COMMAND(eehide, command_eeprom_hide,
			"block",
			"Hide a block of EEPROM",
			NULL);
#endif

/*****************************************************************************/
/* Initialization */

int eeprom_init(void)
{
	/* Enable the EEPROM module in run and sleep modes. */
	clock_enable_peripheral(CGC_OFFSET_EEPROM, 0x1,
			CGC_MODE_RUN | CGC_MODE_SLEEP);

	/* Wait for internal EEPROM init to finish */
	wait_for_done();

	/* Store block count */
	block_count = LM4_EEPROM_EESIZE >> 16;

	/*
	 * Handle resetting the EEPROM module to clear state from a previous
	 * error condition.
	 */
	if (LM4_EEPROM_EESUPP & 0xc0) {
		LM4_SYSTEM_SREEPROM = 1;
		clock_wait_cycles(200);
		LM4_SYSTEM_SREEPROM = 0;

		/* Wait again for internal init to finish */
		clock_wait_cycles(6);
		wait_for_done();

		/* Fail if error condition didn't clear */
		if (LM4_EEPROM_EESUPP & 0xc0)
			return EC_ERROR_UNKNOWN;
	}

	return EC_SUCCESS;
}


text:
@interface REDTopRatedCall ()

@property (setter=injected_topRated:) id<REDDictionary2ModelFactoryProtocol> parser;
@property (setter=injected:) id<REDServiceResponseProtocol> response;

@end

@implementation REDTopRatedCall

-(void)startWithRequest:(id<REDRequestProtocol>)request2 withCompletion:(void (^)(BOOL success))completion {
    self.request = request2;
//    [self call:^(id responseObject, NSError *error) {
//        if (error) {
//            [self.response setSuccess:NO];
//            [self.response setError:error];
//            [self error:self.response];
//        } else {
//            [self.parser setInput:responseObject];
//            [self.response setData:[self.parser outputForMany]];
//            [self.response setSuccess:YES];
//            [self success:self.response];
//        }
//    }];

    NSDictionary *headers = @{ @"cache-control": @"no-cache",
                               @"postman-token": @"e26faa94-01e3-1078-e415-c38dd3554252" };

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",REDServiceFind(REDServerMetadata_V1, @"book/top")]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    [request setHTTPMethod:@"GET"];
    [request setAllHTTPHeaderFields:headers];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    dispatch_async(dispatch_get_main_queue(), ^{
                                                        if (error) {
                                                            self.response.success = NO;
                                                            self.response.error = error;
                                                            [self error:self.response];
                                                            //                                                        callback(nil, error);
                                                        } else {
                                                            NSError* error;
                                                            id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
                                                            if ([json isKindOfClass:[NSDictionary class]]) {
                                                                if ([[json objectForKey:@"error"] isEqual:[NSNull null]] == NO ) {
                                                                    self.response.success = NO;
                                                                    self.response.error = [NSError errorWithDomain:REDErrorDomain code:101 userInfo:@{NSLocalizedDescriptionKey : [json objectForKey:@"error"]}];
                                                                    [self error:self.response];
                                                            }
                                                            } else {
                                                                self.response.success = YES;
                                                                [self.parser setInput:json];
                                                                self.response.data = [self.parser outputForMany];
                                                                [self success:self.response];
                                                            }
                                                        }

                                                    });
                                                }];
    [dataTask resume];
}
-(BOOL)canCacheResult {
    return NO;
}

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<base href="<?php echo base_url();?>"/>
    <title>Welcome to Mirpur Polytechnic Institute</title>
	<link rel="shortcut icon" href="assets/images/mpilogo.png">

    <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="assets/js/dropdown-menu/dropdown-menu.css" rel="stylesheet" type="text/css">
    <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="assets/bootstrap/css/dataTables.bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="assets/js/fancybox/jquery.fancybox.css" rel="stylesheet" type="text/css">
    <link href="assets/js/audioplayer/audioplayer.css" rel="stylesheet" type="text/css">
    <link href="assets/style.css" rel="stylesheet" type="text/css">

মিরপুর পলিটেকনিক ইনস্টিটিউট

                        Mirpur Polytechnic Institute( MPI )

                        Private Polytechnic Institute

মুক্ত বাংলা শপিং কমপ্লেক্স, মিরপুর-০১, ঢাকা

    <?php $this->load->view('menubar');?>


text:
from django.conf.urls import patterns, include, url
from django.contrib import admin

from source.app.views import home

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'lms.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),

    # Home URLs
    url(r'^$', home.index, name='home.index'),
)


text:
namespace content {

namespace {

template<typename SRC, typename DEST>
void ConvertVector(const SRC& src, DEST* dest) {
  dest->reserve(src.size());
  for (typename SRC::const_iterator i = src.begin(); i != src.end(); ++i)
    dest->push_back(typename DEST::value_type(*i));
}

}  // namespace

UtilityThreadImpl::UtilityThreadImpl() : single_process_(false) {
  Init();
}

UtilityThreadImpl::UtilityThreadImpl(const std::string& channel_name)
    : ChildThreadImpl(Options::Builder()
                          .InBrowserProcess(true)
                          .WithChannelName(channel_name)
                          .Build()),
      single_process_(true) {
  Init();
}

UtilityThreadImpl::~UtilityThreadImpl() {
}

void UtilityThreadImpl::Shutdown() {
  ChildThreadImpl::Shutdown();

  if (!single_process_)
    blink::shutdown();
}

void UtilityThreadImpl::ReleaseProcessIfNeeded() {
  if (batch_mode_)
    return;

  if (single_process_) {
    // Close the channel to cause UtilityProcessHostImpl to be deleted. We need
    // to take a different code path than the multi-process case because that
    // depends on the child process going away to close the channel, but that
    // can't happen when we're in single process mode.
    channel()->Close();
  } else {
    ChildProcess::current()->ReleaseProcess();
  }
}

void UtilityThreadImpl::Init() {
  batch_mode_ = false;
  ChildProcess::current()->AddRefProcess();
  if (!single_process_) {
    // We can only initialize WebKit on one thread, and in single process mode
    // we run the utility thread on separate thread. This means that if any code
    // needs WebKit initialized in the utility process, they need to have
    // another path to support single process mode.
    blink_platform_impl_.reset(new BlinkPlatformImpl);
    blink::initialize(blink_platform_impl_.get());
  }
  GetContentClient()->utility()->UtilityThreadStarted();
  GetContentClient()->utility()->RegisterMojoServices(service_registry());
}

bool UtilityThreadImpl::OnControlMessageReceived(const IPC::Message& msg) {
  if (GetContentClient()->utility()->OnMessageReceived(msg))
    return true;

  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(UtilityThreadImpl, msg)
    IPC_MESSAGE_HANDLER(UtilityMsg_BatchMode_Started, OnBatchModeStarted)
    IPC_MESSAGE_HANDLER(UtilityMsg_BatchMode_Finished, OnBatchModeFinished)
#if defined(OS_POSIX) && defined(ENABLE_PLUGINS)
    IPC_MESSAGE_HANDLER(UtilityMsg_LoadPlugins, OnLoadPlugins)
#endif
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void UtilityThreadImpl::OnBatchModeStarted() {
  batch_mode_ = true;
}

void UtilityThreadImpl::OnBatchModeFinished() {
  batch_mode_ = false;
  ReleaseProcessIfNeeded();
}

#if defined(OS_POSIX) && defined(ENABLE_PLUGINS)
void UtilityThreadImpl::OnLoadPlugins(
    const std::vector<base::FilePath>& plugin_paths) {
  PluginList* plugin_list = PluginList::Singleton();

  std::vector<WebPluginInfo> plugins;
  // TODO(bauerb): If we restart loading plug-ins, we might mess up the logic in
  // PluginList::ShouldLoadPlugin due to missing the previously loaded plug-ins
  // in |plugin_groups|.
  for (size_t i = 0; i < plugin_paths.size(); ++i) {
    WebPluginInfo plugin;
    if (!plugin_list->LoadPluginIntoPluginList(
        plugin_paths[i], &plugins, &plugin))
      Send(new UtilityHostMsg_LoadPluginFailed(i, plugin_paths[i]));
    else
      Send(new UtilityHostMsg_LoadedPlugin(i, plugin));
  }

  ReleaseProcessIfNeeded();
}
#endif

}  // namespace content