text:
package Regexp::Common::net;

use Regexp::Common qw /pattern clean no_defaults/;

use strict;
use warnings;

use vars qw /$VERSION/;
$VERSION = '2013031301';

my %IPunit = (
    dec => q{(?k:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})},
    oct => q{(?k:[0-3]?[0-7]{1,2})},
    hex => q{(?k:[0-9a-fA-F]{1,2})},
    bin => q{(?k:[0-1]{1,8})},
);
my %MACunit = (
    %IPunit,
    hex => q{(?k:[0-9a-fA-F]{1,2})},
);

my %IPv6unit = (
    hex => q {(?k:[0-9a-f]{1,4})},
    HEX => q {(?k:[0-9A-F]{1,4})},
    HeX => q {(?k:[0-9a-fA-F]{1,4})},
);

sub dec {$_};
sub bin {oct "0b$_"}

my $IPdefsep   = '[.]';
my $MACdefsep  =  ':';
my $IPv6defsep =  ':';

pattern name   => [qw (net IPv4)],
        create => "(?k:$IPunit{dec}$IPdefsep$IPunit{dec}$IPdefsep" .
                      "$IPunit{dec}$IPdefsep$IPunit{dec})",
        ;

pattern name   => [qw (net MAC)],
        create => "(?k:" . join ($MACdefsep => ($MACunit{hex}) x 6) . ")",
        subs   => sub {
            $_ [1] = join ":" => map {sprintf "%02x" => hex}
                                 split /$MACdefsep/ => $_ [1]
                     if $_ [1] =~ /$_[0]/
        },
        ;

foreach my $type (qw /dec oct hex bin/) {
    pattern name   => [qw (net IPv4), $type, "-sep=$IPdefsep"],
            create => sub {my $sep = $_ [1] -> {-sep};
                           "(?k:$IPunit{$type}$sep$IPunit{$type}$sep" .
                               "$IPunit{$type}$sep$IPunit{$type})"
                      },
            ;

    pattern name   => [qw (net MAC), $type, "-sep=$MACdefsep"],
            create => sub {my $sep = $_ [1] -> {-sep};
                           "(?k:" . join ($sep => ($MACunit{$type}) x 6) . ")",
                      },
            subs   => sub {
                return if $] < 5.006 and $type eq 'bin';
                $_ [1] = join ":" => map {sprintf "%02x" => eval $type}
                                     $2, $3, $4, $5, $6, $7
                         if $_ [1] =~ $RE {net} {MAC} {$type}
                                          {-sep => $_ [0] -> {flags} {-sep}}
                                          {-keep};
            },
            ;

}

my %cache6;
pattern name   => [qw (net IPv6), "-sep=$IPv6defsep", "-style=HeX"],
        create => sub {
            my $style = $_ [1] {-style};
            my $sep   = $_ [1] {-sep};

            return $cache6 {$style, $sep} if $cache6 {$style, $sep};

            my @re;

            die "Impossible style '$style'\n" unless exists $IPv6unit {$style};

            #
            # Nothing missing
            #
            push @re => join $sep => ($IPv6unit {$style}) x 8;

            #
            # For "double colon" representations, at least 2 units must
            # be omitted, leaving us with at most 6 units. 0 units is also
            # possible. Note we can have at most one double colon.
            #
            for (my $l = 0; $l <= 6; $l ++) {
                #
                # We prefer to do longest match, so larger $r gets priority
                #
                for (my $r = 6 - $l; $r >= 0; $r --) {
                    #
                    # $l is the number of blocks left of the double colon,
                    # $r is the number of blocks left of the double colon,
                    # $m is the number of omitted blocks
                    #
                    my $m    = 8 - $l - $r;
                    my $patl = $l ? ($IPv6unit {$style} . $sep) x $l : $sep;
                    my $patr = $r ? ($sep . $IPv6unit {$style}) x $r : $sep;
                    my $patm = "(?k:)" x $m;
                    my $pat  = $patl . $patm . $patr;
                    push @re => "(?:$pat)";
                }
            }
            local $" = "|";
            $cache6 {$style, $sep} = qq /(?k:(?|@re))/;
        },
        version => 5.010
;

my $letter      =  "[A-Za-z]";
my $let_dig     =  "[A-Za-z0-9]";
my $let_dig_hyp = "[-A-Za-z0-9]";

# Domain names, from RFC 1035.
pattern name   => [qw (net domain -nospace= -rfc1101=)],
        create => sub {
            my $rfc1101 = exists $_ [1] {-rfc1101} &&
                        !defined $_ [1] {-rfc1101};

            my $lead = $rfc1101 ? "(?!$RE{net}{IPv4}(?:[.]|\$))$let_dig"
                                : $letter;

            if (exists $_ [1] {-nospace} && !defined $_ [1] {-nospace}) {
                return "(?k:$lead(?:(?:$let_dig_hyp){0,61}$let_dig)?" .
                       "(?:\\.$lead(?:(?:$let_dig_hyp){0,61}$let_dig)?)*)"
            }
            else {
                return "(?k: |(?:$lead(?:(?:$let_dig_hyp){0,61}$let_dig)?" .
                       "(?:\\.$lead(?:(?:$let_dig_hyp){0,61}$let_dig)?)*))"
            }
        },
        ;

1;

__END__

=head1 NAME

Regexp::Common::net -- provide regexes for IPv4 addresses.

=head1 SYNOPSIS

    use Regexp::Common qw /net/;

    while (<>) {
        /$RE{net}{IPv4}/       and print "Dotted decimal IP address";
        /$RE{net}{IPv4}{hex}/  and print "Dotted hexadecimal IP address";
        /$RE{net}{IPv4}{oct}{-sep => ':'}/ and
                               print "Colon separated octal IP address";
        /$RE{net}{IPv4}{bin}/  and print "Dotted binary IP address";
        /$RE{net}{MAC}/        and print "MAC address";
        /$RE{net}{MAC}{oct}{-sep => " "}/ and
                               print "Space separated octal MAC address";
    }

=head1 DESCRIPTION

Please consult the manual of L<Regexp::Common> for a general description
of the works of this interface.

Do not use this module directly, but load it via I<Regexp::Common>.

This modules gives you regular expressions for various style IPv4
and MAC (or ethernet) addresses.

=head2 C<$RE{net}{IPv4}>

Returns a pattern that matches a valid IP address in "dotted decimal".
Note that while C<318.99.183.11> is not a valid IP address, it does
match C</$RE{net}{IPv4}/>, but this is because C<318.99.183.11> contains
a valid IP address, namely C<18.99.183.11>. To prevent the unwanted
matching, one needs to anchor the regexp: C</^$RE{net}{IPv4}$/>.

For this pattern and the next four, under C<-keep> (See L<Regexp::Common>):

=over 4

=item $1

captures the entire match

=item $2

captures the first component of the address

=item $3

captures the second component of the address

=item $4

captures the third component of the address

=item $5

captures the final component of the address

=back

=head2 C<$RE{net}{IPv4}{dec}{-sep}>

Returns a pattern that matches a valid IP address in "dotted decimal"

If C<< -sep=I<P> >> is specified the pattern I<P> is used as the separator.
By default I<P> is C<qr/[.]/>.

=head2 C<$RE{net}{IPv4}{hex}{-sep}>

Returns a pattern that matches a valid IP address in "dotted hexadecimal",
with the letters C<A> to C<F> capitalized.

If C<< -sep=I<P> >> is specified the pattern I<P> is used as the separator.
By default I<P> is C<qr/[.]/>. C<< -sep="" >> and
C<< -sep=" " >> are useful alternatives.

=head2 C<$RE{net}{IPv4}{oct}{-sep}>

Returns a pattern that matches a valid IP address in "dotted octal"

If C<< -sep=I<P> >> is specified the pattern I<P> is used as the separator.
By default I<P> is C<qr/[.]/>.

=head2 C<$RE{net}{IPv4}{bin}{-sep}>

Returns a pattern that matches a valid IP address in "dotted binary"

If C<< -sep=I<P> >> is specified the pattern I<P> is used as the separator.
By default I<P> is C<qr/[.]/>.

=head2 C<$RE{net}{MAC}>

Returns a pattern that matches a valid MAC or ethernet address as
colon separated hexadecimals.

For this pattern, and the next four, under C<-keep> (See L<Regexp::Common>):

=over 4

=item $1

captures the entire match

=item $2

captures the first component of the address

=item $3

captures the second component of the address

=item $4

captures the third component of the address

=item $5

captures the fourth component of the address

=item $6

captures the fifth component of the address

=item $7

captures the sixth and final component of the address

=back

This pattern, and the next four, have a C<subs> method as well, which
will transform a matching MAC address into so called canonical format.
Canonical format means that every component of the address will be
exactly two hexadecimals (with a leading zero if necessary), and the
components will be separated by a colon.

The C<subs> method will not work for binary MAC addresses if the
Perl version predates 5.6.0.

=head2 C<$RE{net}{MAC}{dec}{-sep}>

Returns a pattern that matches a valid MAC address as colon separated
decimals.

If C<< -sep=I<P> >> is specified the pattern I<P> is used as the separator.
By default I<P> is C<qr/:/>.

=head2 C<$RE{net}{MAC}{hex}{-sep}>

Returns a pattern that matches a valid MAC address as colon separated
hexadecimals, with the letters C<a> to C<f> in lower case.

If C<< -sep=I<P> >> is specified the pattern I<P> is used as the separator.
By default I<P> is C<qr/:/>.

=head2 C<$RE{net}{MAC}{oct}{-sep}>

Returns a pattern that matches a valid MAC address as colon separated
octals.

If C<< -sep=I<P> >> is specified the pattern I<P> is used as the separator.
By default I<P> is C<qr/:/>.

=head2 C<$RE{net}{MAC}{bin}{-sep}>

Returns a pattern that matches a valid MAC address as colon separated
binary numbers.

If C<< -sep=I<P> >> is specified the pattern I<P> is used as the separator.
By default I<P> is C<qr/:/>.

=head2 C<$RE{net}{IPv6}{-sep => ':'}{-style => 'HeX'}>

Returns a pattern matching IPv6 numbers. An IPv6 address consists of
eigth groups of four hexadecimal digits, separated by colons. In each
group, leading zeros may be omitted. Two or more consecutive groups
consisting of only zeros may be omitted (including any colons separating
them), resulting into two sets of groups, separated by a double colon.
(Each of the groups may be empty; C<< :: >> is a valid address, equal to
C<< 0000:0000:0000:0000:0000:0000:0000:0000 >>). The hex numbers may be
in either case.

If the C<< -sep >> option is used, its argument is a pattern that matches
the separator that separates groups. This defaults to C<< : >>. The
C<< -style >> option is used to denote which case the hex numbers may be.
The default style, C<< 'HeX' >> indicates both lower case letters C<< 'a' >>
to C<< 'f' >> and upper case letters C<< 'A' >> to C<< 'F' >> will be
matched. The style C<< 'HEX' >> restricts matching to upper case letters,
and C<< 'hex' >> only matches lower case letters.

If C<< {-keep} >> is used, C<< $1 >> to C<< $9 >> will be set. C<< $1 >>
will be set to the matched address, while C<< $2 >> to C<< $9 >> will be
set to each matched group. If a group is omitted because it contains all
zeros, its matching variable will be the empty string.

Example:

  "2001:db8:85a3::8a2e:370:7334" =~ /$RE{net}{IPv6}{-keep}/;
  print $2;    # '2001'
  print $4;    # '85a3'
  print $6;    # Empty string
  print $8;    # '370'

Perl 5.10 (or later) is required for this pattern.

=head2 C<$RE{net}{domain}>

Returns a pattern to match domains (and hosts) as defined in RFC 1035.
Under I{-keep} only the entire domain name is returned.

RFC 1035 says that a single space can be a domainname too. So, the
pattern returned by C<$RE{net}{domain}> recognizes a single space
as well. This is not always what people want. If you want to recognize
domainnames, but not a space, you can do one of two things, either use

    /(?! )$RE{net}{domain}/

or use the C<{-nospace}> option (without an argument).

RFC 1035 does B<not> allow host or domain names to start with a digits;
however, this restriction is relaxed in RFC 1101; this RFC allows host
and domain names to start with a digit, as long as the first part of
a domain does not look like an IP address. If the C<< {-rfc1101} >> option
is given (as in C<< $RE {net} {domain} {-rfc1101} >>), we will match using
the relaxed rules.

=head1 REFERENCES

=over 4

=item B<RFC 1035>

Mockapetris, P.: I<DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION>.
November 1987.

=item B<RFC 1101>

Mockapetris, P.: I<DNS Encoding of Network Names and Other Types>.
April 1987.

=back

=head1 SEE ALSO

L<Regexp::Common> for a general description of how to use this interface.

=head1 AUTHOR

Damian Conway I<damian@conway.org>.

=head1 MAINTAINANCE

This package is maintained by Abigail S<(I<regexp-common@abigail.be>)>.

=head1 BUGS AND IRRITATIONS

Bound to be plenty.

For a start, there are many common regexes missing.
Send them in to I<regexp-common@abigail.be>.

=head1 LICENSE and COPYRIGHT

This software is Copyright (c) 2001 - 2013, Damian Conway and Abigail.

This module is free software, and maybe used under any of the following
licenses:

 1) The Perl Artistic License.     See the file COPYRIGHT.AL.
 2) The Perl Artistic License 2.0. See the file COPYRIGHT.AL2.
 3) The BSD Licence.               See the file COPYRIGHT.BSD.
 4) The MIT Licence.               See the file COPYRIGHT.MIT.

=cut


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
A. F. C. P. de Saint-Hilaire, Fl. Bras. merid. 2:367. 1833

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
chrome.app.runtime.onLaunched.addListener(function() {
    chrome.app.window.create('index.html', {
        id: 'main',
        outerBounds: {
            width: 800,
            height: 640
        }
    });
});

// background script
var app = {};

if (!Promise.defer) {
    Promise.defer = function () {
        let deferred = {};
        let promise = new Promise(function (resolve, reject) {
            deferred.resolve = resolve;
            deferred.reject  = reject;
        });
        deferred.promise = promise;
        return deferred;
    };
}
app.Promise = Promise;

app.disk = {
    browse: function () {
        return new Promise(function (resolve, reject) {
            let wins = chrome.app.window.getAll();
            if (wins && wins.length) {
                let win = wins[0].contentWindow;
                win.chrome.fileSystem.chooseEntry({type: 'openDirectory'}, function (folder) {
                    chrome.storage.local.set({
                        folder: chrome.fileSystem.retainEntry(folder)
                    });
                    resolve(folder.name);
                });
            } else {
                reject();
            }
        });
    }
};

app.play = (src) => {
    let audio = new Audio(chrome.runtime.getURL('/data/' + src));
    audio.play();
};

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
app.fileSystem = {
    file: {
        exists: function (root, name) {
            return new Promise(function (resolve) {
                root.getFile(name, {create: true, exclusive: true}, () => resolve(false), () => resolve(true));
            });
        },
        create: function (root, name) {
            return new Promise(function (resolve, reject) {
                root.getFile(
                    name,    // a unique name
                    {create: true, exclusive: false},
                    (fe) => resolve(fe),
                    (e) => reject(e)
                );
            });
        },
        truncate: function (file, bytes) {
            return new Promise(function (resolve, reject) {
                file.createWriter(function (fileWriter) {
                    fileWriter.onwrite = () => resolve();
                    fileWriter.onerror = (e) => reject(e);
                    fileWriter.truncate(bytes);
                });
            });
        },
        write: function (file, offset, arr) {
            return new Promise(function (resolve, reject) {
                file.createWriter(function (fileWriter) {
                    let blob = new Blob(arr, {type: 'application/octet-stream'});
                    fileWriter.onerror = (e) => reject(e);
                    fileWriter.onwrite = () => resolve();
                    fileWriter.seek(offset);
                    fileWriter.write(blob);
                }, (e) => reject(e));
            });
        },
        md5: function (file, bytes) {
            return new Promise(function (resolve, reject) {
                if (!file) {
                    return resolve('file is not found');
                }
                if (bytes > 50 * 1024 * 1024) {
                    return resolve('MD5 calculation is skipped');
                }
                file.file(function (file) {
                    let reader = new FileReader();
                    reader.onloadend = function () {
                        resolve(CryptoJS.MD5(CryptoJS.enc.Latin1.parse(this.result)).toString());
                    };
                    reader.readAsBinaryString(file);
                }, (e) => reject(e));
            });
        },
        rename: function (file, root, name) {
            return new Promise((resolve, reject) => file.moveTo(root, name, resolve, reject));
        },
        remove: function (file) {
            return new Promise((resolve, reject) => file.remove(resolve, reject));
        },
        launch: () => Promise.reject(new Error('not implemented')),
        reveal: () => Promise.reject(new Error('not implemented')),
        close: () => Promise.resolve(),
        toURL: (file) => {
            return new Promise(function (resolve, reject) {
                file.file(f => resolve(URL.createObjectURL(f)), (e) => reject(e));
            });
        }
    },
    root: {
        internal: function (bytes) {
            return new Promise(function (resolve, reject) {
                navigator.webkitTemporaryStorage.requestQuota(bytes, function (grantedBytes) {
                    if (grantedBytes === bytes) {
                        window.requestFileSystem(
                            window.TEMPORARY, bytes, function (fs) {
                                resolve(fs.root);
                            },
                            (e) => reject(e)
                        );
                    }
                    else {
                        reject(new Error('cannot allocate space in the internal storage'));
                    }
                });
            });
        },
        external: function () {
            return new Promise(function (resolve, reject) {
                chrome.storage.local.get(null, function (storage) {
                    if (storage.folder && config.wget.directory) {
                        try {
                            chrome.fileSystem.restoreEntry(storage.folder, function (root) {
                                if (root) {
                                    resolve(root);
                                }
                                else {
                                    reject(new Error('storage.folder is undefined'));
                                }
                            });
                        }
                        catch (e) {
                            reject(e);
                        }
                    }
                    else {
                        reject(new Error('either storage.folder or config.wget.directory is undefined'));
                    }
                });
            });
        }
    }
};


text:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <poll.h>
#include <netdb.h>

#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <getopt.h>
#include <strings.h>
#include <errno.h>
#include <fcntl.h>

#include <s2n.h>
#include "common.h"
#include <error/s2n_errno.h>

#include "tls/s2n_connection.h"
#include "tls/s2n_tls13.h"
#include "utils/s2n_safety.h"

#define S2N_MAX_ECC_CURVE_NAME_LENGTH 10

void usage()
{
    fprintf(stderr, "usage: s2nc [options] host [port]\n");
    fprintf(stderr, " host: hostname or IP address to connect to\n");
    fprintf(stderr, " port: port to connect to\n");
    fprintf(stderr, "\n Options:\n\n");
    fprintf(stderr, "  -a [protocols]\n");
    fprintf(stderr, "  --alpn [protocols]\n");
    fprintf(stderr, "    Sets the application protocols supported by this client, as a comma separated list.\n");
    fprintf(stderr, "  -c [version_string]\n");
    fprintf(stderr, "  --ciphers [version_string]\n");
    fprintf(stderr, "    Set the cipher preference version string. Defaults to \"default\". See USAGE-GUIDE.md\n");
    fprintf(stderr, "  -e\n");
    fprintf(stderr, "  --echo\n");
    fprintf(stderr, "    Listen to stdin after TLS Connection is established and echo it to the Server\n");
    fprintf(stderr, "  -h,--help\n");
    fprintf(stderr, "    Display this message and quit.\n");
    fprintf(stderr, "  -n [server name]\n");
    fprintf(stderr, "  --name [server name]\n");
    fprintf(stderr, "    Sets the SNI server name header for this client.  If not specified, the host value is used.\n");
    fprintf(stderr, "\n");
    fprintf(stderr, "  -s,--status\n");
    fprintf(stderr, "    Request the OCSP status of the remote server certificate\n");
    fprintf(stderr, "  --mfl\n");
    fprintf(stderr, "    Request maximum fragment length from: 512, 1024, 2048, 4096\n");
    fprintf(stderr, "  -f,--ca-file [file path]\n");
    fprintf(stderr, "    Location of trust store CA file (PEM format). If neither -f or -d are specified. System defaults will be used.\n");
    fprintf(stderr, "  -d,--ca-dir [directory path]\n");
    fprintf(stderr, "    Directory containing hashed trusted certs. If neither -f or -d are specified. System defaults will be used.\n");
    fprintf(stderr, "  -i,--insecure\n");
    fprintf(stderr, "    Turns off certification validation altogether.\n");
    fprintf(stderr, "  --cert [file path]\n");
    fprintf(stderr, "    Path to a PEM encoded certificate. Optional. Will only be used for client auth\n");
    fprintf(stderr, "  --key [file path]\n");
    fprintf(stderr, "    Path to a PEM encoded private key that matches cert. Will only be used for client auth\n");
    fprintf(stderr, "  -r,--reconnect\n");
    fprintf(stderr, "    Drop and re-make the connection using Session ticket. If session ticket is disabled, then re-make the connection using Session-ID \n");
    fprintf(stderr, "  -T,--no-session-ticket \n");
    fprintf(stderr, "    Disable session ticket for resumption.\n");
    fprintf(stderr, "  -D,--dynamic\n");
    fprintf(stderr, "    Set dynamic record resize threshold\n");
    fprintf(stderr, "  -t,--timeout\n");
    fprintf(stderr, "    Set dynamic record timeout threshold\n");
    fprintf(stderr, "  -C,--corked-io\n");
    fprintf(stderr, "    Turn on corked io\n");
    fprintf(stderr, "  --tls13\n");
    fprintf(stderr, "    Turn on experimental TLS1.3 support.\n");
    fprintf(stderr, "  --non-blocking\n");
    fprintf(stderr, "    Set the non-blocking flag on the connection's socket.\n");
    fprintf(stderr, "  -K ,--keyshares\n");
    fprintf(stderr, "    Colon separated list of curve names.\n"
                    "    The client will generate keyshares only for the curve names present in the ecc_preferences list configured in the security_policy.\n"
                    "    The curves currently supported by s2n are: `x25519`, `secp256r1` and `secp384r1`. Note that `none` represents a list of empty keyshares.\n"
                    "    By default, the client will generate keyshares for all curves present in the ecc_preferences list.\n");
    fprintf(stderr, "\n");
    exit(1);
}

struct verify_data {
    const char *trusted_host;
};

static uint8_t unsafe_verify_host(const char *host_name, size_t host_name_len, void *data) {
    struct verify_data *verify_data = (struct verify_data *)data;

    if (host_name_len > 2 && host_name[0] == '*' && host_name[1] == '.') {
        char *suffix = strstr(verify_data->trusted_host, ".");
        return (uint8_t)(strcasecmp(suffix, host_name + 1) == 0);
    }

    int equals = strcasecmp(host_name, verify_data->trusted_host);
    return (uint8_t)(equals == 0);
}

static void setup_s2n_config(struct s2n_config *config, const char *cipher_prefs, s2n_status_request_type type,
    struct verify_data *unsafe_verify_data, const char *host, const char *alpn_protocols, uint16_t mfl_value) {

    if (config == NULL) {
        print_s2n_error("Error getting new config");
        exit(1);
    }

    GUARD_EXIT(s2n_config_set_cipher_preferences(config, cipher_prefs), "Error setting cipher prefs");

    GUARD_EXIT(s2n_config_set_status_request_type(config, type), "OCSP validation is not supported by the linked libCrypto implementation. It cannot be set.");

    if (s2n_config_set_verify_host_callback(config, unsafe_verify_host, unsafe_verify_data) < 0) {
        print_s2n_error("Error setting host name verification function.");
    }

    if (type == S2N_STATUS_REQUEST_OCSP) {
        if(s2n_config_set_check_stapled_ocsp_response(config, 1)) {
            print_s2n_error("OCSP validation is not supported by the linked libCrypto implementation. It cannot be set.");
        }
    }

    unsafe_verify_data->trusted_host = host;

    if (alpn_protocols) {
        /* Count the number of commas, this tells us how many protocols there
           are in the list */
        const char *ptr = alpn_protocols;
        int protocol_count = 1;
        while (*ptr) {
            if (*ptr == ',') {
                protocol_count++;
            }
            ptr++;
        }

        char **protocols = malloc(sizeof(char *) * protocol_count);
        if (!protocols) {
            fprintf(stderr, "Error allocating memory\n");
            exit(1);
        }

        const char *next = alpn_protocols;
        int idx = 0;
        int length = 0;
        ptr = alpn_protocols;
        while (*ptr) {
            if (*ptr == ',') {
                protocols[idx] = malloc(length + 1);
                if (!protocols[idx]) {
                    fprintf(stderr, "Error allocating memory\n");
                    exit(1);
                }
                memcpy(protocols[idx], next, length);
                protocols[idx][length] = '\0';
                length = 0;
                idx++;
                ptr++;
                next = ptr;
            } else {
                length++;
                ptr++;
            }
        }
        if (ptr != next) {
            protocols[idx] = malloc(length + 1);
            if (!protocols[idx]) {
                fprintf(stderr, "Error allocating memory\n");
                exit(1);
            }
            memcpy(protocols[idx], next, length);
            protocols[idx][length] = '\0';
        }

        GUARD_EXIT(s2n_config_set_protocol_preferences(config, (const char *const *)protocols, protocol_count), "Failed to set protocol preferences");

        while (protocol_count) {
            protocol_count--;
            free(protocols[protocol_count]);
        }
        free(protocols);
    }

    uint8_t mfl_code = 0;
    if (mfl_value > 0) {
        switch(mfl_value) {
            case 512:
                mfl_code = S2N_TLS_MAX_FRAG_LEN_512;
                break;
            case 1024:
                mfl_code = S2N_TLS_MAX_FRAG_LEN_1024;
                break;
            case 2048:
                mfl_code = S2N_TLS_MAX_FRAG_LEN_2048;
                break;
            case 4096:
                mfl_code = S2N_TLS_MAX_FRAG_LEN_4096;
                break;
            default:
                fprintf(stderr, "Invalid maximum fragment length value\n");
                exit(1);
        }
    }

    GUARD_EXIT(s2n_config_send_max_fragment_length(config, mfl_code), "Error setting maximum fragment length");
}

int main(int argc, char *const *argv)
{
    struct addrinfo hints, *ai_list, *ai;
    int r, sockfd = 0;
    ssize_t session_state_length = 0;
    uint8_t *session_state = NULL;
    /* Optional args */
    const char *alpn_protocols = NULL;
    const char *server_name = NULL;
    const char *ca_file = NULL;
    const char *ca_dir = NULL;
    const char *client_cert = NULL;
    const char *client_key = NULL;
    bool client_cert_input = false;
    bool client_key_input = false;
    uint16_t mfl_value = 0;
    uint8_t insecure = 0;
    int reconnect = 0;
    uint8_t session_ticket = 1;
    s2n_status_request_type type = S2N_STATUS_REQUEST_NONE;
    uint32_t dyn_rec_threshold = 0;
    uint8_t dyn_rec_timeout = 0;
    /* required args */
    const char *cipher_prefs = "default";
    const char *host = NULL;
    struct verify_data unsafe_verify_data;
    const char *port = "443";
    int echo_input = 0;
    int use_corked_io = 0;
    int use_tls13 = 0;
    uint8_t non_blocking = 0;
    int keyshares_count = 0;
    char keyshares[S2N_ECC_EVP_SUPPORTED_CURVES_COUNT][S2N_MAX_ECC_CURVE_NAME_LENGTH];
    char *input = NULL;
    char *token = NULL;

    static struct option long_options[] = {
        {"alpn", required_argument, 0, 'a'},
        {"ciphers", required_argument, 0, 'c'},
        {"echo", no_argument, 0, 'e'},
        {"help", no_argument, 0, 'h'},
        {"name", required_argument, 0, 'n'},
        {"status", no_argument, 0, 's'},
        {"mfl", required_argument, 0, 'm'},
        {"ca-file", required_argument, 0, 'f'},
        {"ca-dir", required_argument, 0, 'd'},
        {"cert", required_argument, 0, 'l'},
        {"key", required_argument, 0, 'k'},
        {"insecure", no_argument, 0, 'i'},
        {"reconnect", no_argument, 0, 'r'},
        {"no-session-ticket", no_argument, 0, 'T'},
        {"dynamic", required_argument, 0, 'D'},
        {"timeout", required_argument, 0, 't'},
        {"corked-io", no_argument, 0, 'C'},
        {"tls13", no_argument, 0, '3'},
        {"keyshares", required_argument, 0, 'K'},
        {"non-blocking", no_argument, 0, 'B'},
    };

    while (1) {
        int option_index = 0;
        int c = getopt_long(argc, argv, "a:c:ehn:sf:d:l:k:D:t:irTCK:", long_options, &option_index);
        if (c == -1) {
            break;
        }
        switch (c) {
        case 'a':
            alpn_protocols = optarg;
            break;
        case 'C':
            use_corked_io = 1;
            break;
        case 'c':
            cipher_prefs = optarg;
            break;
        case 'e':
            echo_input = 1;
            break;
        case 'h':
            usage();
            break;
        case 'K':
            input = optarg;
            token = strtok(input, ":");
            while( token != NULL ) {
                strcpy(keyshares[keyshares_count], token);
                if (++keyshares_count == S2N_ECC_EVP_SUPPORTED_CURVES_COUNT) {
                    break;
                }
                token = strtok(NULL, ":");
            }
            break;
        case 'n':
            server_name = optarg;
            break;
        case 's':
            type = S2N_STATUS_REQUEST_OCSP;
            break;
        case 'm':
            mfl_value = (uint16_t) atoi(optarg);
            break;
        case 'f':
            ca_file = optarg;
            break;
        case 'd':
            ca_dir = optarg;
            break;
        case 'l':
            client_cert = load_file_to_cstring(optarg);
            client_cert_input = true;
            break;
        case 'k':
            client_key = load_file_to_cstring(optarg);
            client_key_input = true;
            break;
        case 'i':
            insecure = 1;
            break;
        case 'r':
            reconnect = 5;
            break;
        case 'T':
            session_ticket = 0;
            break;
        case 't':
            dyn_rec_timeout = (uint8_t) MIN(255, atoi(optarg));
            break;
        case 'D':
            errno = 0;
            dyn_rec_threshold = strtoul(optarg, 0, 10);
            if (errno == ERANGE) {
                dyn_rec_threshold = 0;
            }
            break;
        case '3':
            use_tls13 = 1;
            break;
        case 'B':
            non_blocking = 1;
            break;
        case '?':
        default:
            usage();
            break;
        }
    }

    if (optind < argc) {
        host = argv[optind++];
    }

    /* cppcheck-suppress duplicateCondition */
    if (optind < argc) {
        port = argv[optind++];
    }

    if (!host) {
        usage();
    }

    if (!server_name) {
        server_name = host;
    }

    memset(&hints, 0, sizeof(hints));

    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
        fprintf(stderr, "Error disabling SIGPIPE\n");
        exit(1);
    }

    if (use_tls13) {
        GUARD_EXIT(s2n_enable_tls13(), "Error enabling TLS1.3");
    }

    GUARD_EXIT(s2n_init(), "Error running s2n_init()");

    if ((r = getaddrinfo(host, port, &hints, &ai_list)) != 0) {
        fprintf(stderr, "error: %s\n", gai_strerror(r));
        exit(1);
    }

    do {
        int connected = 0;
        for (ai = ai_list; ai != NULL; ai = ai->ai_next) {
            if ((sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) {
                continue;
            }

            if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) == -1) {
                close(sockfd);
                continue;
            }

            connected = 1;
            /* connect() succeeded */
            break;
        }

        if (connected == 0) {
            fprintf(stderr, "Failed to connect to %s:%s\n", host, port);
            exit(1);
        }

        if (non_blocking) {
            int flags = fcntl(sockfd, F_GETFL, 0);
            if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0) {
                fprintf(stderr, "fcntl error: %s\n", strerror(errno));
                exit(1);
            }
        }

        struct s2n_config *config = s2n_config_new();
        setup_s2n_config(config, cipher_prefs, type, &unsafe_verify_data, host, alpn_protocols, mfl_value);

        if (client_cert_input != client_key_input) {
            print_s2n_error("Client cert/key pair must be given.");
        }

        if (client_cert_input) {
            struct s2n_cert_chain_and_key *chain_and_key = s2n_cert_chain_and_key_new();
            GUARD_EXIT(s2n_cert_chain_and_key_load_pem(chain_and_key, client_cert, client_key), "Error getting certificate/key");
            GUARD_EXIT(s2n_config_add_cert_chain_and_key_to_store(config, chain_and_key), "Error setting certificate/key");
        }

        if (ca_file || ca_dir) {
            if (s2n_config_set_verification_ca_location(config, ca_file, ca_dir) < 0) {
                print_s2n_error("Error setting CA file for trust store.");
            }
        }
        else if (insecure) {
            GUARD_EXIT(s2n_config_disable_x509_verification(config), "Error disabling X.509 validation");
        }

        if (session_ticket) {
            GUARD_EXIT(s2n_config_set_session_tickets_onoff(config, 1), "Error enabling session tickets");
        }

        struct s2n_connection *conn = s2n_connection_new(S2N_CLIENT);

        if (conn == NULL) {
            print_s2n_error("Error getting new connection");
            exit(1);
        }

        GUARD_EXIT(s2n_connection_set_config(conn, config), "Error setting configuration");

        GUARD_EXIT(s2n_set_server_name(conn, server_name), "Error setting server name");

        GUARD_EXIT(s2n_connection_set_fd(conn, sockfd) , "Error setting file descriptor");

        GUARD_EXIT(s2n_connection_set_client_auth_type(conn, S2N_CERT_AUTH_OPTIONAL), "Error setting ClientAuth optional");

        if (use_corked_io) {
            GUARD_EXIT(s2n_connection_use_corked_io(conn), "Error setting corked io");
        }

        for (size_t i = 0; i < keyshares_count; i++) {
            if (keyshares[i]) {
                GUARD_EXIT(s2n_connection_set_keyshare_by_name_for_testing(conn, keyshares[i]), "Error setting keyshares to generate");
            }
        }

        /* Update session state in connection if exists */
        if (session_state_length > 0) {
            GUARD_EXIT(s2n_connection_set_session(conn, session_state, session_state_length), "Error setting session state in connection");
        }

        /* See echo.c */
        if (negotiate(conn, sockfd) != 0) {
            /* Error is printed in negotiate */
            S2N_ERROR_PRESERVE_ERRNO();
        }

        printf("Connected to %s:%s\n", host, port);

        /* Save session state from connection if reconnect is enabled */
        if (reconnect > 0) {
            if (!session_ticket && s2n_connection_get_session_id_length(conn) <= 0) {
                printf("Endpoint sent empty session id so cannot resume session\n");
                exit(1);
            }
            free(session_state);
            session_state_length = s2n_connection_get_session_length(conn);
            session_state = calloc(session_state_length, sizeof(uint8_t));
            if (s2n_connection_get_session(conn, session_state, session_state_length) != session_state_length) {
                print_s2n_error("Error getting serialized session state");
                exit(1);
            }
        }

        if (dyn_rec_threshold > 0 && dyn_rec_timeout > 0) {
            s2n_connection_set_dynamic_record_threshold(conn, dyn_rec_threshold, dyn_rec_timeout);
        }

        if (echo_input == 1) {
            fflush(stdout);
            fflush(stderr);
            echo(conn, sockfd);
        }

        s2n_blocked_status blocked;
        s2n_shutdown(conn, &blocked);

        GUARD_EXIT(s2n_connection_free(conn), "Error freeing connection");

        GUARD_EXIT(s2n_config_free(config), "Error freeing configuration");

        close(sockfd);
        reconnect--;

    } while (reconnect >= 0);

    GUARD_EXIT(s2n_cleanup(), "Error running s2n_cleanup()");

    free(session_state);
    freeaddrinfo(ai_list);
    return 0;
}


text:
var React = require('React');
var ReactStyle = require('ReactStyle');
var ReactStyleHead = require('ReactStyleHead');
var SiteBoilerPlateStyleRules = require('./SiteBoilerPlateStyleRules.js');

/**
 * We should support/experiment with modelling css dependencies using the exact
 * same commonJS resolution, so that we can include CSS files in our React npm
 * modules. An npm module should include everything needed to work with your
 * component - and it is impossible to know where your component will be
 * installed to.
 *
 *    // Depends on css from my project - relative paths automatically resolved.
 *    require('./SiteBoilerPlate.css');
 *
 *    // Depends on css from dependency 'bootstrap' in package.json
 *    require('bootstrap/Text-Input.css');
 *
 * For now, you have to use {ReactStyle#addRules} to make sure the
 * index.js page includes the styles that your project depends on directly.
 * Even in that case, we'll use commonJS resolution for css files as well,
 * so that if you whitelist things in node_modules for inclusion in your
 * bundle, the resources in those will be
 * accessible as well.
 */

/**
 * Component for performing some redundant site wrapping. Customize to your
 * liking, or create a new, similar module. `react-page` automatically ensures
 * that all fo the JavaScript used to generate the page, will be bundled and
 * sent into the response so that all the event handlers will work.
 *
 * Usage:
 *
 * var React = require('React');
 * var SiteBoilerPlate = require('./components/SiteBoilerPlate.jsx');
 * var MyPage = React.createClass({
 *   render: function() {
 *     return (
 *       <SiteBoilerPlate>
 *
Hello This Is My App!

 *       </SiteBoilerPlate>
 *     );
 *   }
 * });
 */

ReactStyle.addRules(SiteBoilerPlateStyleRules);

var SiteBoilerPlate = React.createClass({
  render: function() {
    return (

        <ReactStyleHead>
          <meta charset="UTF-8" />
          <title>React Page | Client-Server JavaScript Rendering</title>
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0, user-scalable=no"
          />

        </ReactStyleHead>

          {this.props.children}

    );
  }
});

module.exports = SiteBoilerPlate;


text:
<?php

?>

<?php get_header(); ?>

<?php design_breadcrumbs() ?>

 <?php if (have_posts()) : while (have_posts()) : the_post();?>

 <h1 id="post-<?php the_ID(); ?>" class="page-title"><?php the_title();?>

 <?php the_content(); ?>

 <?php edit_post_link('Edit This Entry', '
', '
'); ?>
<?php comments_template(); ?>
 <?php endwhile; endif; ?>

<?php get_footer(); ?>


text:
/**
 *
 */
package com.jarp.tutorials.bigranchprohects.ch11;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.jarp.tutorials.bigranchprohects.R;

/**
 * @author JARP
 *
 */
public class CrimeListFragment extends ListFragment {

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

			if(requestCode == REQUEST_CRIME)
			{

			}
	}

	private static final int REQUEST_CRIME = 1;

	@Override
	public void onResume() {

		super.onResume();

		((CrimeAdapter) getListAdapter()).notifyDataSetChanged();
	}

	private static final String TAG = "CrimeListFragment";

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		//Crime c = (Crime) (getListAdapter()).getItem(position);

		Crime c = ((CrimeAdapter)getListAdapter()).getItem(position);
		/*
		 * CH 10
		 * */
		//Intent i = new Intent(getActivity(), CrimeActivity.class);
		//i.putExtra(CrimeFragment.EXTRA_CRIME_ID, c.getmId());
		//startActivity(i);

		Intent i = new Intent(getActivity(), CrimePagerActivity.class);
		i.putExtra(CrimeFragment.EXTRA_CRIME_ID, c.getmId());

		startActivity(i);

		Log.d(TAG, c.getmTitle() + "was clicked");

	}

	private ArrayList<Crime> mCrimes ;

	private ArrayAdapter<Crime> adapter;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getActivity().setTitle(R.string.crime_titles);

		mCrimes = CrimeLab.get(getActivity()).getCrimes();

		//adapter = new ArrayAdapter<Crime>(getActivity(),android.R.layout.simple_list_item_1,mCrimes);

		adapter = new CrimeAdapter(mCrimes);

		setListAdapter(adapter);

	}

	private class CrimeAdapter extends ArrayAdapter<Crime>
	{

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if(convertView ==null)
			{
				convertView = getActivity().getLayoutInflater().inflate(R.layout.ch11_list_item_crime , null);
			}

			Crime c = getItem(position);

			TextView titleTextView = (TextView) convertView.findViewById(R.id.crime_list_item_titleTextView);

			titleTextView.setText(c.getmTitle());

			TextView dateTextView = (TextView) convertView.findViewById(R.id.crime_list_item_dateTextView);

			dateTextView.setText(c.getDate().toString());

			CheckBox solvedCheckBox = (CheckBox) convertView.findViewById(R.id.crime_list_item_solvedCheckBox);

			solvedCheckBox.setChecked(c.isSolved());

			return convertView;

		}

		public CrimeAdapter(ArrayList<Crime> Crimes) {
			super(getActivity(),0,Crimes);
			// TODO Auto-generated constructor stub
		}

	}

}


text:
author: muyiwagbadegesin
comments: true
date: 2017-02-27 07:47:00+00:00
excerpt:
Elections in Nigeria are chaotic and fraught with numerous problems like
  late arrival of election materials, ballot box snatching, rigging and violence.
  We developed the Pollwatch project
  to support the election monitoring role of the Coalition
  of Democrats for Electoral Reform (CODER).

layout: post
link: https://mgblog477.wordpress.com/2017/02/27/2016419pollwatch/
slug: 2016419pollwatch
title: 'PollwatchNG: Real-time Monitoring of Elections in Nigeria'
wordpress_id: 40
categories:
- Politics
- Projects
- Technology
tags:
- coder
- election monitoring
- pollwatch
- quickcount
- ushahidi
---

# Introducing Pollwatch

   [youtube=://www.youtube.com/watch?v=DID-gG8EjkI&w=640&h=480]

Elections in Nigeria are chaotic and fraught with numerous problems like late arrival of election materials, ballot box snatching, rigging and violence. We developed the [Pollwatch](http://www.pollwatchnigeria.org) project to support the election monitoring role of the [Coalition of Democrats for Electoral Reform](https://www.facebook.com/codernigeria) (CODER). Pollwatch is built on [Ushahidi](https://www.ushahidi.com), the well-known Kenyan incident monitoring platform. The Pollwatch project evolved from [Quickcount 2007](https://muyiwagbadegesin.com/projects/2016/4/17/quickcount-2007).

Pollwatch successfully crowd-sourced incidence reports from verified poll monitors and members of the public. While we were able to extract individual PU results from SMS, email and phonecalls, Ushahidi was not able to pull results automatically from posted reports like the [Quickcount 2007](https://muyiwagbadegesin.com/projects/2016/4/17/quickcount-2007) system. There is a need to design an open-source Quickcount-As-A-Service (QAAS) platform. Such a platform could be used by political parties and poll monitors alike to monitor election results real-time.

Pollwatch Incidence Reports were also posted to the Pollwatch Twitter account [@pollwatchNG](https://twitter.com/pollwatchng).

The Pollwatch system was administered from the Pollwatch Contact Center shown in the pictures below:

   ![](https://mgblog477.files.wordpress.com/2017/02/823be-_dsc8415.jpg)

   ![](https://mgblog477.files.wordpress.com/2017/02/b8bd3-_dsc9281.jpg)

   ![](https://mgblog477.files.wordpress.com/2017/02/b8cba-_dsc9287.jpg)

   ![](https://mgblog477.files.wordpress.com/2017/02/0b92b-_dsc9290.jpg)

   ![](https://mgblog477.files.wordpress.com/2017/02/4c9ea-_dsc9292.jpg)

   ![](https://mgblog477.files.wordpress.com/2017/02/51f4e-_dsc9341.jpg)

# Tools and Techniques

  1. Server Host (Mediatemple)
  2. Ushahidi self-hosted version
  3. Contact Center:
    1. 6 iMac desktop PCs
    2. GSM modems to receive SMS data from observers
    3. 4 GSM voice lines
  4. Training materials: color-coded Quick Reference Cards, training manual (shown below)
  5. Publicity:
    1. Newspaper adverts
    2. Election Day interviews on national television
    3. Television adverts
    4. Youtube video
  6. GIS Data (nationwide polling unit locations)

Quick Reference cards and training manuals were used to train poll watchers:

       [caption id="" align="alignnone" width="850.0"]![Quick Reference Card for Poll Watchers](https://mgblog477.files.wordpress.com/2017/02/3cb41-pollwatch2011.jpg) Quick Reference Card for Poll Watchers[/caption]

   [slideshare id=vzqZdxEpJjD7lY?wmode=opaque&w=427&h=356&fb=0&mw=0&mh=0&style=border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;&sc=no]

** [CODER Pollwatch Election Monitoring Guide](https://www.slideshare.net/muyiwag/coder-pollwatch-election-monitoring-guide) ** from **[muyiwag](http://www.slideshare.net/muyiwag)**

# Results

Reports were generated in powerpoint and PDF format:

   [slideshare id=6N3cWfBj4Mn5iD?wmode=opaque&w=427&h=356&fb=0&mw=0&mh=0&style=border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;&sc=no]

** [Pollwatch2011 National Assembly Election Report](https://www.slideshare.net/muyiwag/pollwatch2011-national-assembly-election-report) ** from **[muyiwag](http://www.slideshare.net/muyiwag)**

# Next Steps

The [National Democratic Institute (NDI)](https://www.ndi.org) recently released the open source web-based [Democracy Toolkit](https://www.nditech.org/demtools) software (DemTools) which consists of four modules. The four modules are designed to enhance organization and communication by political parties and civic groups during elections.

[DemTools](https://www.nditech.org/demtools) promises to be a useful tool for monitoring future elections.


text:
    <form class="form-contact br">

Contact

      Name:
      <input type="text" id="name">

      Email:
      <input type="email" id="email" placeholder="email@website.com" disabled>

      Interests:
      <input type="checkbox" id="development" name="user_interest">Development

      <input type="checkbox" id="design" name="user_interest">Design

      <input type="checkbox" id="business" name="user_interest">Business

      Message:
      <textarea id="msg" rows="4"></textarea>

      <input class="btn default" type="submit" value="Submit">
    </form>


text:
package io.reactivex.android.schedulers;

import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.util.concurrent.atomic.AtomicBoolean;

import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableContainer;

class ScheduledRunnable extends AtomicBoolean implements Runnable, Disposable {
    private final Handler handler;
    private final Runnable delegate;
    private final DisposableContainer disposableContainer;

    ScheduledRunnable(@NonNull Handler handler,
                      @NonNull Runnable delegate,
                      @Nullable DisposableContainer disposableContainer) {
        this.handler = handler;
        this.delegate = delegate;
        this.disposableContainer = disposableContainer;

        if (disposableContainer != null) {
            disposableContainer.add(this);
        }
    }

    @Override
    public void dispose() {
        if (!getAndSet(true)) {
            if (disposableContainer != null) {
                disposableContainer.delete(this);
            }
            handler.removeCallbacks(this);
        }
    }

    @Override
    public boolean isDisposed() {
        return get();
    }

    @Override
    public void run() {
        delegate.run();
        if (!reschedule()) {
            if (disposableContainer != null) {
                disposableContainer.delete(this);
            }
            set(true);
        }
    }

    protected boolean reschedule() {
        return false;
    }
}


text:
export train_data=""
export test_data=""
export label=""
export run_name=""
export iterations="50"
export models="RF DT SGD AB SVM NN"
export thresholds="0.9 0.8 0.7 0.6 0.5 0.4"


text:
title: "Deployment architecture for Sensu"
linkTitle: "Deployment Architecture"
description: "This guide describes considerations, potential architectures, and recommendations for a production-ready Sensu deployment."
weight: 30
version: "6.7"
product: "Sensu Go"
platformContent: false
menu:
  sensu-go-6.7:
    parent: deploy-sensu
---

This guide describes various planning considerations and recommendations for a production-ready Sensu deployment, including details related to communication security and common deployment architectures.

etcd is a key-value store that is used by applications of varying complexity, from simple web apps to Kubernetes.
The Sensu backend uses an embedded etcd instance for storing both configuration and observability event data, so you can get Sensu up and running without external dependencies.

By building atop etcd, Sensu's backend inherits a number of characteristics to consider when you're planning for a Sensu deployment.

## Create and maintain clusters

Sensu's embedded etcd supports initial cluster creation via a static list of peer URLs.
After you create a cluster, you can add and remove cluster members with etcdctl tooling.

If you have a healthy clustered backend, you only need to make [Sensu API][2] calls to any one of the cluster members.
The cluster protocol will replicate your changes to all cluster members.

Read [Run a Sensu cluster][7] and the [etcd documentation][4] for more information.

## Hardware sizing

Because etcd's design prioritizes consistency across a cluster, the speed with which write operations can be completed is very important to the Sensu cluster's performance and health.
This means that you should provision Sensu backend infrastructure to provide sustained input/output operations per second (IOPS) appropriate for the rate of observability events the system will be required to process.

To maximize Sensu Go performance, we recommend that you:
 * Follow our [recommended backend hardware configuration][1].
 * Implement [documented etcd system tuning practices][11].
 * [Benchmark your etcd storage volume][12] to establish baseline IOPS for your system.
 * [Scale event storage using PostgreSQL][13] to reduce the overall volume of etcd transactions.

## Communications security

Whether you're using using a single Sensu backend or multiple Sensu backends in a cluster, communication with the backend's various network ports (web UI, HTTP API, WebSocket API, etcd client and peer) occurs in cleartext by default.
We recommend that you encrypt network communications via TLS, which requires planning and explicit configuration.

### Plan TLS for etcd

The URLs for each member of an etcd cluster are persisted to the database after initialization.
As a result, moving a cluster from cleartext to encrypted communications requires resetting the cluster, which destroys all configuration and event data in the database.
Therefore, we recommend planning for encryption before initiating a clustered Sensu backend deployment.

{{% notice warning %}}
**WARNING**: Reconfiguring a Sensu cluster for TLS post-deployment will require resetting all etcd cluster members, resulting in the loss of all data.
{{% /notice %}}

As described in [Secure Sensu][6], the backend uses a shared certificate and key for web UI and agent communications.
You can secure communications with etcd using the same certificate and key.
The certificate's Common Name (CN) or Subject Alternative Name (SAN) must include the network interfaces and DNS names that will point to those systems.

{{% notice note %}}
**NOTE**: As of [Go 1.15](https://golang.google.cn/doc/go1.15#commonname), certificates must include their CN as an SAN field.
To prevent connection errors, follow [Generate certificates](../generate-certificates/) to make sure your certificates' SAN fields include their CNs.
{{% /notice %}}

Read [Run a Sensu cluster][7] and the [etcd documentation][4] for more information about TLS setup and configuration, including a walkthrough for generating TLS certificates for your cluster.

## Common Sensu architectures

Depending on your infrastructure and the type of environments you'll be monitoring, you may use one or a combination of these architectures to best fit your needs.

### Single backend (standalone)

The single backend (standalone) with embedded etcd architecture requires minimal resources but provides no redundancy in the event of failure.

{{
}}

*
Single Sensu Go backend or standalone architecture
*

You can reconfigure a single backend as a member of a cluster, but this operation requires destroying the existing database.

The single backend (standalone) architecture may be a good fit for small- to medium-sized deployments (such as monitoring a remote office or datacenter), deploying alongside individual auto-scaling groups, or deploying in various segments of a logical environment spanning multiple cloud providers.

For example, in environments with unreliable WAN connectivity, having agents connect to a local backend may be more reliable than having agents connect over WAN or VPN tunnel to a backend running in a central location.

### Clustered deployment for single availability zone

To increase availability and replicate both configuration and data, join the embedded etcd databases of multiple Sensu backend instances together in a cluster.
Read [Run a Sensu cluster][7] for more information.

{{
}}

*
Clustered Sensu Go architecture for a single availability zone
*

Clustering requires an odd number of backend instances.
Although larger clusters provide better fault tolerance, write performance suffers because data must be replicated across more machines.
The etcd maintainers recommend clusters of 3, 5, or 7 backends.
Read the [etcd documentation][4] for more information.

### Clustered deployment for multiple availability zones

Distributing infrastructure across multiple availability zones in a given region helps ensure continuous availability of customer infrastructure in the region if any one availability zone becomes unavailable.
With this in mind, you can deploy a Sensu cluster across multiple availability zones in a given region, configured to tolerate reasonable latency between those availability zones.

{{
}}

*
Clustered Sensu Go architecture for multiple availability zones
*

### Large-scale clustered deployment for multiple availability zones

In a large-scale clustered Sensu Go deployment, you can use as many backends as you wish.
Use one etcd node per availiability zone, with a minimum of three etcd nodes and a maximum of five.
Three etcd nodes allow you to tolerate the loss of a single node with minimal effect on performance.
Five etcd nodes allow you to tolerate the loss of two nodes, but with a greater effect on performance.

{{
}}

*
Large-scale clustered Sensu Go architecture for multiple availability zones
*

#### Scaled cluster performance with PostgreSQL

To achieve the high rate of event processing that many enterprises require, Sensu supports PostgreSQL event storage as a [commercial feature][9].
Read the [datastore reference][8] to configure the Sensu backend to use PostgreSQL for event storage.

{{
}}

*
Clustered Sensu Go architecture with PostgreSQL event storage
*

In load testing, Sensu Go has proven capable of processing 36,000 events per second when using PostgreSQL as the event store.
Review the [sensu-perf project repository][10] for a detailed explanation of our testing methodology and results.

### Large-scale cloud deployment for multiple regions

In a large-scale cloud deployment for multiple regions, place all backends, etcd nodes, and event datastores in a single region.
The backends communicate with agents in other regions via WebSocket transport.
This configuration allows you to load-balance traffic between the backends in the main regions and the agents in other regions.

{{% notice note %}}
**NOTE**: Do not use read replicas in a cloud deployment.
Sensu is write-heavy, and the brief, unavoidable replication delays will cause inconsistency between etcd data and PostgreSQL data.
{{% /notice %}}

This diagram depicts an example architecture for a Google Cloud Platform (GCP) deployment, but you can reproduce this architecture with your preferred cloud provider:

{{
}}

*
Example Sensu Go architecture for multi-region cloud deployments
*

In this example, the load balancer translates traffic on port 80 to port 3000 so that users do not need to include `:3000` in the web UI URL.
API traffic is load-balanced to the backends as well.

## Architecture considerations

### Networking

Clustered deployments benefit from a fast and reliable network.
Ideally, they should be co-located in the same network segment with as little latency as possible between all the nodes.
We do not recommend clustering backends across disparate subnets or WAN connections.

Although 1GbE is sufficient for common deployments, larger deployments will benefit from 10GbE, which allows a shorter mean time to recovery.

As the number of agents connected to a backend cluster grows, so will the amount of communication between members of the cluster required for data replication.
With this in mind, clusters with a thousand or more agents should use a discrete network interface for peer communication.

### Load balancing

Although you can configure each Sensu agent with the URLs for multiple backend instances, we recommend that you configure agents to connect to a load balancer.
This approach gives operators more control over agent connection distribution and makes it possible to replace members of the backend cluster without updates to agent configuration.

Conversely, you cannot configure the sensuctl command line tool with multiple backend URLs.
Under normal conditions, sensuctl communications and browser access to the web UI should be routed via a load balancer.

#### Load balancing algorithms

If the load balancer uses round robin mode, when an agent comes online, the load balancer sends the agent's traffic to whichever backend is next in the pattern, regardless of load.
This can result in slow load balancing among backends, especially after restarting a backend.

In least connection mode, the load balancer sends new agent traffic to the backend with the least traffic.
This helps to evenly distribute the load among backends more quickly.

[1]: ../hardware-requirements/#backend-recommended-configuration
[2]: ../../../api/
[4]: https://etcd.io/docs/
[5]: https://etcd.io/docs/current/op-guide/security/
[6]: ../secure-sensu/
[7]: ../cluster-sensu/
[8]: ../datastore/
[9]: ../../../commercial/
[10]: https://github.com/sensu/sensu-perf
[11]: https://etcd.io/docs/latest/tuning/#disk
[12]: https://www.ibm.com/cloud/blog/using-fio-to-tell-whether-your-storage-is-fast-enough-for-etcd
[13]: ../datastore/#scale-event-storage


text:
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">

</button>

资产归还

            <form id="assets-stk-form" name="assets-stk-form" class="form-horizontal">
                <input type="hidden" name="id">

                                选择资产*

                                    <select id="assetsStkID" class="form-control select2" name="stkID" style="width:100%;" disabled="disabled">
                                        <option selected="selected" value="">选择一个已有资产</option>
                                    </select>

                                数量:*

                                    <input type="text" class="form-control" id="quantity" name="quantity" placeholder="数量" onkeyup="value=value.replace(/[^\d.]/g,'')" readonly="readonly">

                                型号:*

                                    <input type="text" class="form-control" id="model" name="model" readonly="readonly">

                                规格:*

                                    <input type="text" class="form-control" id="norm" name="norm" readonly="readonly">

                                生产厂商:*

                                    <input type="text" class="form-control" id="vendor" name="vendor" readonly="readonly">

                                已归还数量:*

                                    <input type="text" class="form-control" id="quantityReturned" name="quantityReturned" placeholder="已归还数量" onkeyup="value=value.replace(/[^\d.]/g,'')" readonly="readonly">

                                本次归还数量:*

                                    <input type="text" class="form-control" id="quantityReturning" name="quantityReturning" placeholder="本次归还数量" onkeyup="value=value.replace(/[^\d.]/g,'')">

                        <button type="submit" class="btn btn-primary" data-btn-type="next">提交</button>

            </form>


text:
(* ::Package:: *)

(* Mathematica Package *)
(* Created by Mathematica Plugin for IntelliJ IDEA *)

(* :Title: POVRayRender *)
(* :Context: POVRayRender` *)
(* :Author: xslittlegrass *)
(* :Date: 2016-08-29 *)

(* :Package Version: 0.1 *)
(* :Mathematica Version: *)
(* :Copyright: (c) 2016 xslittlegrass *)
(* :Keywords: *)
(* :Discussion: *)

BeginPackage["POVRayRender`"];
(* Exported symbols added here with SymbolName::usage *)

POVRayRender::usage = "POVRayRender[3Dgraphics] render a 3D graphics using POVRay.";
ConfigurePOVRayRender::usage = "ConfigurePOVRayRender[\"POVRayPath\"->\"path\"] configures the POVRay path.";
ToPOVRayScene::usage = "ToPOVRayScene[3Dgraphics] generates POVRay scence file content in string.";

Begin["`Private`"];

(* Load and check configuration *)

$applicationDataDirectory = FileNameJoin[{$UserBaseDirectory, "ApplicationData", "POVRayRender"}];
If[Not@DirectoryQ[$applicationDataDirectory], CreateDirectory[$applicationDataDirectory]];

$configFile = FileNameJoin[{$applicationDataDirectory, "config.m"}];

(* Load configuration, if it exists *)
If[FileExistsQ[$configFile], $POVRayPath = Import[$configFile, "Package"], $POVRayPath=""];
If[$POVRayPath==""||!FileExistsQ[$POVRayPath],

  Print["POVRay Path not configured. Please use ConfigurePOVRayRender[\"POVRayPath\"->\"path to POVRay executable\"] to configure the path."];
];

Options[ConfigurePOVRayRender]={"POVRayPath"->$POVRayPath};
ConfigurePOVRayRender[OptionsPattern[]]:=Module[{povrayPath},
  povrayPath=OptionValue["POVRayPath"];
  If[povrayPath==""||!FileExistsQ[povrayPath],Print["path not correct"];Abort[]];

  Export[$configFile, povrayPath, "Package"];
  $POVRayPath = povrayPath;
  povrayPath

];

globalStr="

global_settings {
  max_trace_level 5
  assumed_gamma 1.0
  radiosity {
    pretrace_start 0.08
    pretrace_end   0.01
    count 35
    nearest_count 5
    error_bound 1.8
    recursion_limit 2
    low_error_factor .5
    gray_threshold 0.0
    minimum_reuse 0.015
    brightness 1
    adc_bailout 0.01/2
  }
}

#default {
  texture {
    pigment {rgb 1}
    finish {
      ambient 0.0
      diffuse 0.6
      specular 0.6 roughness 0.001
      reflection { 0.0 1.0 fresnel on }
      conserve_energy
    }
  }
}

light_source { <50,-50,50> 1 }
background { rgb <0,.25,.5> }
";

generatePovrayString[p_Graphics3D]:=Module[{povStr,replaceStr1,replaceStr2,replaceStr3},

  replaceStr1="finish {ambient color rgb 1}";(*remove the default light*)
  replaceStr2="finish {ambient rgb 1}";(* remove additional light*)
  replaceStr3="pigment {color rgb <0., 0., 0.>}";(*remove the default color*)

  If[ByteCount[p]<200||p[[1]]==={},(*if the graphics is empty*)
    povStr=globalStr;,
    povStr=StringJoin[globalStr,StringReplace[StringDrop[#,Last@Flatten@StringPosition[#,"/*ViewPoint*/"]]&@ExportString[p,"pov"],{replaceStr1->"",replaceStr2->"",replaceStr3->""}]]];
  povStr
];
(* export povray file to string from Graphics3D object *)

(* graphicsComplexToMesh2 convert a GraphicsComplex object into mesh2 object in povray.
Right now only support one object in GraphicsComplex.*)

graphicsComplexToMesh2[gc_]:=Module[{scform,NoVertex,vertex,vertexNormals,NoFaces,faceIndex,vertexStr,vertexNormalsStr,faceIndexStr,vertexColors,vertexColorsStr},
  scform[x_]:=ScientificForm[x,8,NumberFormat->(Row[If[#3=="",{#1},{#1,"e",#3}]]&)];
  vertex=gc[[1]];
  vertexNormals=First@Cases[gc,Rule[VertexNormals,x__]:>x,\[Infinity]];
  faceIndex=First@Cases[gc,GraphicsGroup[{Polygon[x__],___}]|GraphicsGroup[Annotation[{Polygon[x__], ___}, ___]]:>x,\[Infinity]]-1;
  (*The pattern with Annotation is for the bug introduced in Mathematica version 11.01*)
  NoVertex=ToString@Length[vertex];
  NoFaces=ToString@Length[faceIndex];
  vertexStr=StringRiffle[Apply["<" <> ToString[#1] <> "," <> ToString[#2] <> "," <> ToString[#3] <> ">" &, Map[ToString[scform[#]] &, vertex, {-1}], {1}], ",\n"];
  vertexNormalsStr=StringRiffle[Apply["<" <> ToString[#1] <> "," <> ToString[#2] <> "," <> ToString[#3] <> ">" &,Map[ToString[scform[#]] &, vertexNormals, {-1}],{1}],",\n"];

  If[
    Cases[gc,Rule[VertexColors,x_]:>x,\[Infinity]]=={},

  (* no color in the original plot*)
    faceIndexStr=StringRiffle[Apply[StringTemplate["<`1`,`2`,`3`>"],faceIndex,{1}],",\n"];
    StringTemplate["
	mesh2{
		vertex_vectors{
			``,
			``
		}
		normal_vectors{
			``,
			``
		}
		face_indices{
			``,
			``
		}
	}
"][NoVertex,vertexStr,NoVertex,vertexNormalsStr,NoFaces,faceIndexStr],

  (* color presented in the original plot*)

    faceIndexStr=StringRiffle[Apply["<" <> ToString[#1] <> "," <> ToString[#2] <> "," <> ToString[#3] <> ">" <> "," <> ToString[#1] <> "," <> ToString[#2] <> "," <> ToString[#3] &, faceIndex, {1}], ",\n"];
    (* this is the same as StringRiffle[Apply[StringTemplate["<`1`,`2`,`3`>,`1`,`2`,`3`"], faceIndex, {1}], ",\n"], but StringTemplate has a huge performance issue.*)
    vertexColors=First@Cases[Replace[gc,Line[x__]:>{},\[Infinity]],Rule[VertexColors,x__]:>x,\[Infinity]];
    If[!VectorQ[vertexColors,NumberQ],vertexColors=ColorConvert[vertexColors,"RGB"]/.RGBColor->List];
    (*sometimes the color is stored as VertexColors\[Rule]{Hue[...],Hue[...],...}, this tries to convert to RGB numbers.*)
    vertexColorsStr=StringRiffle[Apply["texture{pigment{rgb <" <> ToString[#1] <> "," <> ToString[#2] <> "," <> ToString[#3] <> ">}}" &, Map[ToString[scform[#]] &, vertexColors, {-1}], {1}], "\n"];

    StringTemplate["
	mesh2{
		vertex_vectors{
			``,
			``
		}
		normal_vectors{
			``,
			``
		}
		texture_list{
			``,
			``
		}
		face_indices{
			``,
			``
		}
	}
"][NoVertex,vertexStr,NoVertex,vertexNormalsStr,NoVertex,vertexColorsStr,NoFaces,faceIndexStr]
  ]
];

generatePovrayStringUsingMesh[p_Graphics3D]:=Module[{gc,camera},
  gc=If[$VersionNumber>=12,First@Cases[p,_GraphicsComplex,Infinity],First@Cases[p,_GraphicsComplex]];
  camera=First@StringCases[ExportString[p/.GraphicsComplex[___]:>GraphicsComplex[{{0,0,0}},{Sphere[1]}],"POV"],"camera {"~~Shortest[x__]~~"}"];
  (*This gets only the camera information. We dump the content of the 3d Graphics so that the export can be much faster.*)
  povStr=StringJoin[globalStr,camera,graphicsComplexToMesh2[gc]];
  povStr
];

povrayExec[inputPath_,outputPath_,povpath_,povrayOptions_]:=Module[{renderCmd},
  renderCmd="\""<>povpath<>"\" "<>povrayOptions<>""<>outputPath<>" "<>inputPath;
  Run[renderCmd]
];
(* call povray exectuable to render the graphics *)

(* put together the subroutines *)

Options[POVRayRender]={"Method"->"Mesh","OutputPath"->None,"ImageSize"->{800,600},"RenderOptions"->"+A0.001 -J"};

Block[{$POVRayPath},
POVRayRender[p_Graphics3D,povpath_String:$POVRayPath,OptionsPattern[]]:=Module[{imageWidth,imageHeight,tracingOptions,inputPath,outputPath,povrayOptions,tempFileStream,povraySceneStr,temp},

(*-----path for povray executables and options -------------*)
  {imageWidth,imageHeight}=OptionValue["ImageSize"];
  tracingOptions=OptionValue["RenderOptions"];
  povrayOptions=StringTemplate["+W`1` +H`2` `3` +O"][imageWidth,imageHeight,tracingOptions];

(*	temp=AbsoluteTime[];*)

  povraySceneStr=If[OptionValue["Method"]=="Mesh",
    generatePovrayStringUsingMesh[p],
    generatePovrayString[p]];

(*	Print["parse Graphics3D"];
	Print[AbsoluteTime[]-temp];
	temp=AbsoluteTime[];*)

  (*----generate temporary pov file from Grpahics3D object----*)
  (* this is intent to generate uniqu filename each time *)
  inputPath=$TemporaryDirectory<>"/"<>DateString[{ToString@$KernelID,"Year","-","MonthNameShort","Day","-","Hour24","Minute","SecondExact"}]<>StringJoin@@ToString/@RandomInteger[{1,1000},{10}]<>".pov";
  tempFileStream=OpenWrite[inputPath];
  WriteString[inputPath,povraySceneStr];
  Close[tempFileStream];

  outputPath=$TemporaryDirectory<>"/"<>DateString[{ToString@$KernelID,"Year","-","MonthNameShort","Day","-","Hour24","Minute","SecondExact"}]<>StringJoin@@ToString/@RandomInteger[{1,1000},{10}]<>".png";
  (*------call povray to render and output rendered file------*)

(*	Print["writting to disk"];
	Print[AbsoluteTime[]-temp];
	temp=AbsoluteTime[];*)

  povrayExec[inputPath,outputPath,povpath,povrayOptions];

(*	Print["POVRay render"];
	Print[AbsoluteTime[]-temp];
	temp=AbsoluteTime[];*)

  If[OptionValue["OutputPath"]===None,
    Import[outputPath],
    CopyFile[outputPath,OptionValue["OutputPath"]];
    OptionValue["OutputPath"]
  ]
]];

Options[ToPOVRayScene]={"Method"->"Mesh"};

ToPOVRayScene[p_Graphics3D,OptionsPattern[]]:=Module[{},
  If[OptionValue["Method"]=="Mesh",
    generatePovrayStringUsingMesh[p],
    generatePovrayString[p]]

];

End[]; (* `Private` *)

EndPackage[]


text:
sheet.fx.getRemoteCellRangeValue = function(sheet, addressStart, addressStop){

    var identifier = $(sheet).attr('data-calx-identifier');

    if(!identifier || typeof(calx.sheetRegistry[identifier]) == 'undefined'){
        return false;
    }

    return calx.sheetRegistry[identifier].getCellRangeValue(addressStart, addressStop);
};


text:
# What is Doctor
* Doctor is a Documentation Server for all your project docs.
* Doctor beautifully decouples document serving and document contents.
* Create your docs in markdown. Store them anywhere (github/dropbox/google drive/ anywhere really).
* Login to Doctor's Dashboard. Setup links to your doc files in Doctor's Dashboard.
* You are done!

## Live Demo
* [Doctor's website](http://doctor.minio.io) is a site hosted on doctor using this very Readme.MD file. Yeah very meta.
* [Minio Docs](https://docs.minio.io) has a doctor server running that pulls together MD files that reside across a number of github repos :
 Eg:
  * README.md in https://github.com/minio/minio
  * Markdown files in https://github.com/minio/minio/tree/master/docs

You may use the `Suggest Edits` feature in Doctor to submit changes to any of the MD files in github. Doctor relies on github workflow to accept PRs for changes.

## Deployment

### Heroku
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/minio/doctor)

### Scalingo
[![Deploy](https://cdn.scalingo.com/deploy/button.svg)](https://my.scalingo.com/deploy?source=https://github.com/minio/doctor)

### Docker
[![Doctor.Docker](https://d207aa93qlcgug.cloudfront.net/1.95.5.qa/img/nav/docker-logo-loggedout.png)](https://hub.docker.com/r/minio/doctor/)

#### Using Docker Compose

Pre-requisite: Install and set up [docker](https://docs.docker.com/engine/installation/) on your machine.

```bash
# get the docker-compose.yml file from the minio/doctor repo
wget https://raw.githubusercontent.com/minio/doctor/master/docker-compose.yml
wget https://raw.githubusercontent.com/minio/doctor/master/.env

# If you want to start the services in production
RAILS_ENV=production docker-compose up -d

# If you want to start the services in development
docker-compose up -d

# get the container name of the web service
docker ps

# setup the database in a one-off command
docker exec docapp bundle exec rake db:setup
```
* Open http://localhost:3000 on your browser to see doctor running from docker container.
* Note: If you start doctor in production mode, all http requests are redirected to https.

## Features
* Documents are organized under Categories.
* Login to the dashboard
* Step 1 : Use the Dashboard to create a new Category : http://localhost:3000/categories/new
* Step 2 : Use the Dashboard to create a link to a new Document : http://localhost:3000/docs/new
* Step 3: Paste the raw URL to the md file when linking a new document. The "Raw" button is on the top of the MD file in github.
* Required : All documents need to be associated under a Category

## Development

### Quickstart: Setup on OSX
* Install Ruby 2.2.2 using the instructions [here](https://rvm.io/rvm/install).
* Install Rails 4.2.4 using the instructions [here](https://rvm.io/rvm/install).
* Install Postgres using the command `brew install postgres`. Configure Launch Agent to start it automatically or use the command `pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start` to start it manually.

### Quickstart: Setup on Ubuntu
* Install Rails & Ruby using the instructions [here](https://www.digitalocean.com/community/tutorials/how-to-install-ruby-on-rails-on-ubuntu-14-04-using-rvm).
* Install Postgres using the instructions [here](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-14-04).

Clone and start doctor

```
> git clone https://github.com/minio/doctor.git
> cd doctor
> bundle install
> rake db:drop
> rake db:setup
> rails s
```
Now visit http://localhost:3000

Use `sysadmin@doctor.io` with password `Doctor!23` to login. Visit [http://localhost:3000](http://localhost:3000) to navigate the docs. This can be changed anytime via the Dashboard. We highly recommend that you do if you use Doctor in deployment.

**Note** -
* On Ubuntu vanilla installations, `bundle install` sometimes may not go through smoothly. In that case, you may need to run `sudo apt install libpg-dev`
* If you get error message: `Gem Load Error is: Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes.`, during `bundle install`,
then run `sudo apt-get install nodejs`
* If you see error: `ActiveRecord::NoDatabaseError: FATAL:  role <your_user_name> does not exist` during `rake:db setup`, then run: `sudo -u postgres createuser --superuser <your_user_name>`
* Ping us on our [gitter channel](https://gitter.im/minio/minio) to report any installation issues on your platform.


text:
const {app, BrowserWindow, globalShortcut, dialog} = require('electron')
const path = require('path')
const url = require('url')

let win
let choice = -1

function createWindow() {
  win = new BrowserWindow({width:1000, height: 800})

  win.on('close', (e) => {
    if (choice === -1) {
      choice = dialog.showMessageBox({type:'question', title:'温馨提示', message: '确定要退出应用吗?', buttons:['退出', '最小化到系统托盘']})
    }
    if (choice === 0) {
      win = null
    } else {
      e.preventDefault()
      win.hide()
    }
  })

  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file',
    slashes: true
  }))

  win.setMenuBarVisibility(false)

  const ret = globalShortcut.register('CommandOrControl+F12', () => {
      console.log('CommandOrControl+F12 is pressed')
      win.webContents.openDevTools()
  })

  if (!ret) {
      console.log('CommandOrControl+F12 registration failed')
  }
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})


text:
package app.miner.module.step.processors;

import app.guice.MessageService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import app.miner.module.step.AbstractStepProcessor;

import javax.inject.Inject;
import java.io.IOException;
import java.util.Map;

/**
 * Created by Issen on 15.11.2015.
 */
public class GetPage extends AbstractStepProcessor {

    @Inject
    private MessageService messageService;

	private String url;

    public static class DataParameters {
        public static String URL = "url";
        public static String PAGE_CONTENT = "PAGE_CONTENT";
    }

    @Override
    public void initialize(Map<String, Object> config) {
    	url = (String) config.get(DataParameters.URL);
    }

    @Override
    public Map<String, Object> processStep(Map<String, Object> data) {
        messageService.sendMessage("Step processor injector is working", this.getClass().getName());
        try {
            Document doc = Jsoup.connect(url).get();
            data.put(DataParameters.PAGE_CONTENT, doc);
            System.out.println(doc.getElementById("header_home"));
        } catch (IOException e) {
            System.out.println("Something went wrong while downloading page " + url);
            e.printStackTrace();
        }

        return data;
    }

}


text:
package com.cognifide.aet.validation.impl;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;

import com.cognifide.aet.validation.ErrorMessage;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;

public class ValidationResultBuilderImplTest {

  private ValidationResultBuilderImpl tested;

  private static final String MSG_1 = "msg1";

  private static final String MSG_2 = "msg2";

  private static final String MSG_3 = "msg1";

  @Before
  public void setUp() {
    tested = new ValidationResultBuilderImpl();
  }

  @Test
  public void addErrorMessage() {
    tested.addErrorMessage(MSG_1);
    assertThat(tested.getErrorMessages(), hasSize(1));

    ErrorMessage errorMessage = tested.getErrorMessages().get(0);
    assertThat(errorMessage.getMessage(), is(MSG_1));
    assertThat(tested.isValid(), is(false));
    assertThat(tested.hasErrors(), is(true));
  }

  @Test
  public void addErrorMessage_multiple() {
    tested.addErrorMessage(MSG_1).addErrorMessage(MSG_2).addErrorMessage(MSG_3);
    assertThat(tested.getErrorMessages(), hasSize(3));

    ErrorMessage errorMessage = tested.getErrorMessages().get(0);
    assertThat(errorMessage.getMessage(), is(MSG_1));

    errorMessage = tested.getErrorMessages().get(1);
    assertThat(errorMessage.getMessage(), is(MSG_2));

    errorMessage = tested.getErrorMessages().get(2);
    assertThat(errorMessage.getMessage(), is(MSG_3));
    assertThat(tested.isValid(), is(false));
    assertThat(tested.hasErrors(), is(true));
  }

  @Test
  public void testToString() throws Exception {
    //empty builder
    ValidationResultBuilderImpl validationResultBuilder = new ValidationResultBuilderImpl();
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        is(StringUtils.EMPTY));

    //single error message
    validationResultBuilder.addErrorMessage("MSG_1");
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("1 errors were found"));
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("Message: MSG_1"));

    //two error messages
    validationResultBuilder.addErrorMessage("MSG_2");
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("2 errors were found"));
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("Message: MSG_1"));
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("Message: MSG_2"));

    //two error messages
    validationResultBuilder.addErrorMessage("MSG_3", new NoSuchFieldException());
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("3 errors were found"));
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("Message: MSG_1"));
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("Message: MSG_2"));
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("Message: MSG_3"));
    assertThat(ValidationUtils.validationResultToString(validationResultBuilder),
        containsString("Caused by: java.lang.NoSuchFieldException"));
  }
}


text:
HTTP/1.1 200 OK
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>ADSL Internet Broadband ISP - ADSL2 ADSL2+ Naked DSL Mobile VoIP</title>
		<meta name="description" content="ADSL Internet Broadband Internet Service Provider ISP, cheap ADSL, ADSL2+, DSL, Naked DSL, Mobile, VoIP plans. Cheap Modems & mobiles or BYO" />
		<meta name="keywords" content="Internet, isp, internet service provider,  internet access, internet connection, cheap internet, broadband, best broadband, dsl, adsl, adsl2, adsl2+, naked dsl, naked adsl2+, mobile, mobile service, mobile plans, dial up, voip, voice over ip, internet phone, iptv, email, shdsl, business broadband, website hosting, VPN, business internet, networking, TPG, TPG Internet" />
		<meta name="copyright" content="TPG Internet Pty Ltd, Sydney 2004. All rights reserved" />
		<meta http-equiv="pragma" content="no-cache" />
	<meta http-equiv="cache-control" content="no-cache" />
	<link href="/res/css_new/style.css" rel="stylesheet" type="text/css" />

  <object type="application/x-shockwave-flash" data="/res/banners/TPG_topbanner_111209.swf" width="537" height="85"  class="Swfbanner">
    <param name="movie" value="/res/banners/TPG_topbanner_111209.swf" />
  </object>

Company Profile

Contact TPG

Contact TPG

Branch Addresses

Job Opportunities

Investor Relations

Register Online

Products & Services

ADSL2+ Broadband

Naked ADSL2+

Mobile

Home Phone

Broadband Residential

Broadband Business

Churn to TPG Broadband

VoIP Telephone Service

Virtual Phone Card

Dial Up

Business SHDSL

POP3 Email Account

IMAP Email Account

Website Hosting

Domain Name Hosting

IP Addressing

Mail List Server

IPTV

TPG Network

Your TPG Account

Account Management

Service Status

Access Numbers

Support

TPG News

TPG Newsletter

TPG Media Releases

Direct Dealers

Terms & Conditions

Service Status

Job Opportunities

Printable Forms

Online Safety

Customer Feedback

TPG Forum

Home

Enter your Username, Customer ID or Mobile number and your password below to view and manage your account details. You can also view your internet and call usage, activate your mobile SIM or change your password.

<form action="index.php" method="post" name="form">

      Username, Customer ID OR TPG Mobile number
      <input name="check_username" type="text" size="13"  >

      Password
      <input name="password" type="password" size="13">

      <input type="submit" name="Submit" value="GO!" class="button">

</form>

      Safe Surfing|Sitemap|Contact Us|Privacy|Report Spamming

  Copyright © 2010 TPG Internet Pty Ltd ABN 15 068 383 737 - All Rights Reserved


text:
#ifndef CLASSEINTERFACE_H_
#define CLASSEINTERFACE_H_
#include<iostream>
#include"classeControle.h"
#include<string>
#include<iomanip>
using std::cout;
using std::cin;
using std::endl;
//***************************************************************
//Esta classe tem como responsabilidade a "comunicacao" com o usuario
// comunicacao do tipo usuario/interface
//**********************************************************
class Interface
{
	//Metodos
	public:
		static void menuPrincipal(Controle &ctrl);
		static void lerPessoa(std::string &nome, unsigned long &telefone, std::string &email);
		static void lerPessoaA(const std::string &nome, unsigned long &telefone, std::string &email);
		static void escreverPessoa(const std::string &nome, unsigned long telefone, const std::string &email);
};

void Interface::menuPrincipal(Controle &ctrl)//Metodo q tem como parametro um objeto da classe controle
{// inicio metodo
	unsigned int opcao=1;
	while(opcao){// inicio while
		std::string superior="_________________________",
                    inferior="_________________________",
                    lateral=" | ";
        system("cls");
		cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
		cout<<endl<<"  MENU PRINCIPAL"<<endl;
		cout<<superior;
        cout<<endl<<"| 1 - INCLUIR           |";
		cout<<endl<<"| 2 - EXCLUIR           |";
		cout<<endl<<"| 3 - ALTERAR           |";
		cout<<endl<<"| 4 - CONSULTAR         |";
		cout<<endl<<"| 5 - LISTAGEM GERAL    |";
		cout<<endl<<"| 6 - LISTAGEM POR LETRA|";
		cout<<endl<<"| 0 - SAIR              |";
		cout<<endl<<inferior;
        cout<<endl<<endl;
		cout<<"OPCAO: ";
		cin>>opcao;
		switch(opcao){// inicio switch
			case 1:{// inicio case 1 - INCLUIR
			//chamar o metodo ler, receber os dados, fez a chamada do metodo
            //incluir da classe controle, que retorna um numero. esse numero é o
            //status da inclusao. de acordo com a resposta eu vou saber o que aconteceu com a
            //inclusao.
					std::string nome,email;
					unsigned long telefone;
					lerPessoa(nome,telefone,email);//chamando o metodo para ler os dados digitados pelo user
					int resposta=ctrl.incluir(nome,telefone,email);//enviando os dados digitados para o metodo incluir da classe Controle 01.1
					if(resposta == 1) cout<<endl<<"INCLUSAO NA AGENDA - SUCESSO";
					if(resposta == 2) cout<<endl<<"-> ERRO"<<endl<<"INCLUSAO NA AGENDA - NOME JA EXISTE";
					if(resposta == 3) cout<<endl<<"-> ERRO"<<endl<<"INCLUSAO NA AGENDA - AGENDA CHEIA";
					cout<<endl<<endl<<"<ENTER> PARA CONTINUAR";
					cin.get();
				break;
			}// fim case 1
			case 2:{//inicio case 2   -  EXCLUIR
					std::string nome,email;
					unsigned long telefone;
					system("cls");
                    cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
                    cout<<endl<<" EXCLUIR";
                    cout<<endl<<"NOME: ";
					cin.get();
					getline(cin,nome);
					if(ctrl.consultar(nome,telefone,email)){
						escreverPessoa(nome,telefone,email);
						cout<<endl<<endl<<"Confirma Exclusao[s/n]:  ";
						char resp;
						resp=cin.get();
						if(resp!='s' && resp!='S' && resp=='n' && resp=='N') resp = 'n';
						if(resp=='s' || resp=='S'){
							ctrl.excluir(nome);
							cout<<endl<<"EXCLUSAO CONCLUIDA";
						}else cout<<"Exclusao Cancelada"<<endl;
					}else cout<<endl<<"PESSOA NAO EXISTE NA AGENDA";
					cout<<endl<<endl<<"<ENTER> PARA CONTINUAR";
					cin.get();
				break;
			}//fim case 2
			case 3:{//inicio case 3    - ALTERAR
					std::string nome,email;
					unsigned long telefone;
					system("cls");
                    cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
                    cout<<endl<<" ALTERAR";
                    cout<<endl<<"NOME: ";
					cin.get();
					getline(cin,nome);
					if(ctrl.consultar(nome,telefone,email)){
						escreverPessoa(nome,telefone,email);
						cout<<endl<<endl<<"Confirma Alteracao[s/n]:  ";
						char resp;
						resp=cin.get();
						if(resp!='s' && resp!='S' && resp!='n' && resp!='N') resp = 'n';
						if(resp=='s' || resp=='S'){
							lerPessoaA(nome,telefone,email);
							ctrl.alterar(nome,telefone,email);
						}
					}else cout<<endl<<"PESSOA NAO EXISTE NA AGENDA";
					cout<<endl<<endl<<"<ENTER> PARA CONTINUAR";
					cin.get();
				break;
			}//fim case 3
			case 4:{// inicio case 4 - CONSULTAR
					std::string nome,email;
					unsigned long telefone;
					system("cls");
                    cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
                    cout<<endl<<" CONSULTAR";
                    cout<<endl<<"NOME: ";
					cin.get();
					getline(cin,nome);
					if(ctrl.consultar(nome,telefone,email))	escreverPessoa(nome,telefone,email);
						else cout<<endl<<"PESSOA NAO EXISTE NA AGENDA";
					cout<<endl<<endl<<"<ENTER> PARA CONTINUAR";
					cin.get();
				break;
			}//fim case 4
			case 5:{//inicio case 5  -  LISTAGEM GERAL
                    Iterator *iterator = ctrl.listagemGeral();//chamando o metodo listagem geral q retorna um objeto da classe persistencia
				//listagemGeral é um método da classe controle.
				//ele retorna o método obter todas as pessoas da classe persistencia
				//e o tipo desse metodo é INTERADOR!!!

                	if (iterator->estaVazio()){ //verifica se a agenda que está no iterador
                                                   //está vazia.
                       cin.ignore();// ignora tudo o que foi armazenado no buffer do último cin.
                       cout<<" Agenda Vazia" << endl;
                       cin.get();
                       break;
                     }
                    //agora tem todos os nomes do arquivo dentro de um vetor de objetos da classe pessoa
                    std::string superior="__________________________________________________________",
					            inferior="__________________________________________________________",
					            lateral=" | ";
                    system("cls");
					cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
                    cout<<endl<<"  LISTAGEM GERAL"<<endl;
					cout<<superior<<endl;
                    cout<<"______NOME_________TELEFONE______________EMAIL__________"<<lateral<<endl;

                    iterator->inicio();//comando pro interador ir para o inicio.
					bool teste=true;
					while(teste){//vai repetir enquanto a variavel teste for verdadeira
						Pessoa pessoa=iterator->obter();
                        //obter retorna um objeto da classe pessoa

						std::string nome;
						pessoa.obterNome(nome);
						cout<<std::setw(15)<<nome<<lateral<<std::setw(10)<<pessoa.obterTelefone()<<lateral<<std::setw(25)<<pessoa.obterEmail()<<lateral<<endl;
						teste=iterator->proximo();
						//pergunta ao "metodo" proximo, se ainda tem posições ocupadas
						//na agenda, se tiver retorna 1. e entra no while novamente.
						//se retornar 0, continua o prog.
					}
					cout<<inferior<<endl;
					cout<<endl<<endl<<"<ENTER> PARA CONTINUAR";
					cin.get();
					cin.get();
					delete iterator; //deletando o ponteiro criado dentro do case.
				break;
			}//fim case 5
			case 6:{//inicio do case 6 - LISTAGEM POR LETRA
			     	char letra;
                    std::string superior="__________________________________________________________",
					            inferior="__________________________________________________________",
					            lateral=" | ";
                    cout<<"Digite a 1ª letra do nome p/listagem: ";
					cin.ignore();//limpando buffer do teclado
					letra=cin.get();//captura a letra digitada na variavel letra
					Iterator *iterator = ctrl.listagemNome(letra);
					if (iterator->estaVazio()){//verifica se a agenda dentro do iterador
					                           //está vazia , neste caso vai ser pq n
                                               //encontrara nenhum nome com a letra desejada
                       cout<<" NOME DESEJADO NAO ENCONTRADO" << endl;
                       cin.ignore(); //limpando buffer do teclado
                       cin.get(); //pausa a tela
                       break;
                    }
					system("cls");
					cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
					cout<<letra;
                    cout<<endl<<" LISTAGEM POR NOME"<<endl;
					cout<<superior<<endl;
                    cout<<"______NOME_________TELEFONE______________EMAIL__________"<<lateral<<endl;
					iterator->inicio();//função que leva ao inicio da copia da agenda
					bool teste=true;
					while(teste){
						Pessoa pessoa=iterator->obter();
						std::string nome;
						pessoa.obterNome(nome);
						cout<<std::setw(15)<<nome<<lateral<<std::setw(10)<<pessoa.obterTelefone()<<lateral<<std::setw(25)<<pessoa.obterEmail()<<lateral<<endl;
						teste=iterator->proximo();
					}
					cout<<inferior<<endl;
					cout<<endl<<endl<<"<ENTER> PARA CONTINUAR";
					cin.get();
					cin.get();
					delete iterator;//toda vez q eh criado um ponteiro eh preciso ser deletado
           }//fim do case 6
		}// fim switch
	}// fim while
}// fim metodo

void Interface::lerPessoa(std::string &nome, unsigned long &telefone, std::string &email)
{//inicio metodo
	system("cls");
	cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
    cout<<endl<<" DADOS DA PESSOA - ENTRADA"<<endl;
	cout<<endl<<"    NOME: ";
	cin.get();
	getline(cin,nome);//lendo o nome e armazenando na var nome
	cout<<"TELEFONE: ";
	cin>>telefone;//lendo o telefone e armazenando na var telefone
	cin.get();
	cout<<"   EMAIL: ";
	getline(cin,email);//lendo o email e armazenando na var email
}// fim metodo

void Interface::lerPessoaA(const std::string &nome, unsigned long &telefone, std::string &email)
//metodo usado para a alteração de nomes
{//inicio metodo
	system("cls");
	cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
    cout<<endl<<" DADOS DA PESSOA - ENTRADA"<<endl;
	cout<<endl<<"    NOME: "<<nome<<endl;
	cout<<"TELEFONE: ";
	cin>>telefone;
	cin.get();
	cout<<"   EMAIL: ";
	getline(cin,email);
}// fim metodo

void Interface::escreverPessoa(const std::string &nome, unsigned long telefone, const std::string &email)
{//este metodo serve apenas para escrever os dados na tela
	system("cls");
	cout<<"\t**_SISTEMA_DA_AGENDA_**"<<endl;
    cout<<endl<<" DADOS DA PESSOA - SAIDA"<<endl;
	cout<<endl<<"    NOME: "<<nome;
	cout<<endl<<"TELEFONE: "<<telefone;
	cout<<endl<<"   EMAIL: "<<email;
}

#endif /*CLASSEINTERFACE_H_*/


text:
title: what was that word again?
author: alba
layout: post
permalink: /2001/11/01/what-was-that-word-again/
categories:
  - web
tags:
  - web
---
iTools, (not the apple [thingamajig][1]) the reference site is a simple and fast starting point for all your dictionary, thesaurus & translation needs.

 [1]: http://itools.mac.com/


text:
package com.vfdev.gettingthingsdonemusicapp.Animations;

import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;

/**
 * Created by vfomin on 10/17/15.
 */
public class DefaultAnimations {

    TranslateAnimation mButtonAnimation;

    // -------- Public methods
    public DefaultAnimations() {
        setupButtonAnimation();
    }

    public Animation getButtonAnimation() {
        return mButtonAnimation;
    }

    // -------- Other methods

    private void setupButtonAnimation() {
        mButtonAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0.05f);
        mButtonAnimation.setDuration(150);

    }

}