text:
from __future__ import print_function

import argparse
import os
import subprocess
import sys
import settings

OUTPUT_DIR = os.path.join(settings.PROJECT_DIR, 'build', 'tests')

class Options(object):
    def __init__(self, name='', build_args=None, test_args=None):
        if build_args is None:
            build_args = []

        if test_args is None:
            test_args = []

        self.build_args = build_args
        self.name = name
        self.test_args = test_args

def get_binary_path(bin_dir_path):
    return os.path.join(bin_dir_path, 'jerry')

# Test options for unittests
JERRY_UNITTESTS_OPTIONS = [
    Options('unittests',
            ['--unittests', '--jerry-cmdline=off', '--error-messages=on', '--snapshot-save=on', '--snapshot-exec=on', '--vm-exec-stop=on', '--profile=es2015-subset', '--mem-stats=on']),
    Options('unittests-debug',
            ['--unittests', '--jerry-cmdline=off', '--debug', '--error-messages=on', '--snapshot-save=on', '--snapshot-exec=on', '--vm-exec-stop=on', '--profile=es2015-subset', '--mem-stats=on']),
    Options('doctests',
            ['--doctests', '--jerry-cmdline=off', '--error-messages=on', '--snapshot-save=on', '--snapshot-exec=on', '--vm-exec-stop=on', '--profile=es2015-subset']),
    Options('doctests-debug',
            ['--doctests', '--jerry-cmdline=off', '--debug', '--error-messages=on', '--snapshot-save=on', '--snapshot-exec=on', '--vm-exec-stop=on', '--profile=es2015-subset'])
]

# Test options for jerry-tests
JERRY_TESTS_OPTIONS = [
    Options('jerry_tests'),
    Options('jerry_tests-debug',
            ['--debug']),
    Options('jerry_tests-debug-cpointer_32bit',
            ['--debug', '--cpointer-32bit=on', '--mem-heap=1024']),
    Options('jerry_tests-snapshot',
            ['--snapshot-save=on', '--snapshot-exec=on'],
            ['--snapshot']),
    Options('jerry_tests-debug-snapshot',
            ['--debug', '--snapshot-save=on', '--snapshot-exec=on'],
            ['--snapshot']),
    Options('jerry_tests-es2015-subset-debug',
            ['--debug', '--profile=es2015-subset']),
    Options('jerry_tests-debug-external-context',
            ['--debug', '--jerry-libc=off', '--external-context=on'])
]

# Test options for jerry-test-suite
JERRY_TEST_SUITE_OPTIONS = JERRY_TESTS_OPTIONS[:]
JERRY_TEST_SUITE_OPTIONS.extend([
    Options('jerry_test_suite-minimal',
            ['--profile=minimal']),
    Options('jerry_test_suite-minimal-snapshot',
            ['--profile=minimal', '--snapshot-save=on', '--snapshot-exec=on'],
            ['--snapshot']),
    Options('jerry_test_suite-minimal-debug',
            ['--debug', '--profile=minimal']),
    Options('jerry_test_suite-minimal-debug-snapshot',
            ['--debug', '--profile=minimal', '--snapshot-save=on', '--snapshot-exec=on'],
            ['--snapshot']),
    Options('jerry_test_suite-es2015-subset',
            ['--profile=es2015-subset']),
    Options('jerry_test_suite-es2015-subset-snapshot',
            ['--profile=es2015-subset', '--snapshot-save=on', '--snapshot-exec=on'],
            ['--snapshot']),
    Options('jerry_test_suite-es2015-subset-debug-snapshot',
            ['--debug', '--profile=es2015-subset', '--snapshot-save=on', '--snapshot-exec=on'],
            ['--snapshot'])
])

# Test options for test262
TEST262_TEST_SUITE_OPTIONS = [
    Options('test262_tests')
]

# Test options for jerry-debugger
DEBUGGER_TEST_OPTIONS = [
    Options('jerry_debugger_tests',
            ['--debug', '--jerry-debugger=on', '--jerry-libc=off'])
]

# Test options for buildoption-test
JERRY_BUILDOPTIONS = [
    Options('buildoption_test-lto',
            ['--lto=on']),
    Options('buildoption_test-error_messages',
            ['--error-messages=on']),
    Options('buildoption_test-all_in_one',
            ['--all-in-one=on']),
    Options('buildoption_test-valgrind',
            ['--valgrind=on']),
    Options('buildoption_test-valgrind_freya',
            ['--valgrind-freya=on']),
    Options('buildoption_test-mem_stats',
            ['--mem-stats=on']),
    Options('buildoption_test-show_opcodes',
            ['--show-opcodes=on']),
    Options('buildoption_test-show_regexp_opcodes',
            ['--show-regexp-opcodes=on']),
    Options('buildoption_test-compiler_default_libc',
            ['--jerry-libc=off']),
    Options('buildoption_test-cpointer_32bit',
            ['--jerry-libc=off', '--compile-flag=-m32', '--cpointer-32bit=on', '--system-allocator=on']),
    Options('buildoption_test-external_context',
            ['--jerry-libc=off', '--external-context=on']),
    Options('buildoption_test-snapshot_tool',
            ['--jerry-cmdline-snapshot=on']),
]

def get_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument('--toolchain', action='store', default='', help='Add toolchain file')
    parser.add_argument('--buildoptions', action='store', default='',
                        help='Add a comma separated list of extra build options to each test')
    parser.add_argument('--skip-list', action='store', default='',
                        help='Add a comma separated list of patterns of the excluded JS-tests')
    parser.add_argument('--outdir', action='store', default=OUTPUT_DIR,
                        help='Specify output directory (default: %(default)s)')
    parser.add_argument('--check-signed-off', action='store_true', default=False,
                        help='Run signed-off check')
    parser.add_argument('--check-signed-off-tolerant', action='store_true', default=False,
                        help='Run signed-off check in tolerant mode')
    parser.add_argument('--check-signed-off-travis', action='store_true', default=False,
                        help='Run signed-off check in tolerant mode if on Travis CI and not checking a pull request')
    parser.add_argument('--check-cppcheck', action='store_true', default=False, help='Run cppcheck')
    parser.add_argument('--check-doxygen', action='store_true', default=False, help='Run doxygen')
    parser.add_argument('--check-pylint', action='store_true', default=False, help='Run pylint')
    parser.add_argument('--check-vera', action='store_true', default=False, help='Run vera check')
    parser.add_argument('--check-license', action='store_true', default=False, help='Run license check')
    parser.add_argument('--check-magic-strings', action='store_true', default=False,
                        help='Run "magic string source code generator should be executed" check')
    parser.add_argument('--buildoption-test', action='store_true', default=False, help='Run buildoption-test')
    parser.add_argument('--jerry-debugger', action='store_true', default=False, help='Run jerry-debugger tests')
    parser.add_argument('--jerry-tests', action='store_true', default=False, help='Run jerry-tests')
    parser.add_argument('--jerry-test-suite', action='store_true', default=False, help='Run jerry-test-suite')
    parser.add_argument('--unittests', action='store_true', default=False, help='Run unittests (including doctests)')
    parser.add_argument('--precommit', action='store_true', default=False, dest='all', help='Run all test')
    parser.add_argument('--test262', action='store_true', default=False, help='Run test262')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    script_args = parser.parse_args()

    return script_args

BINARY_CACHE = {}

def create_binary(job, options):
    build_cmd = [settings.BUILD_SCRIPT]
    build_cmd.extend(job.build_args)

    build_dir_path = os.path.join(options.outdir, job.name)
    build_cmd.append('--builddir=%s' % build_dir_path)

    if options.toolchain:
        build_cmd.append('--toolchain=%s' % options.toolchain)

    if options.buildoptions:
        build_cmd.extend(options.buildoptions.split(','))

    sys.stderr.write('Build command: %s\n' % ' '.join(build_cmd))

    binary_key = tuple(job.build_args)
    if binary_key in BINARY_CACHE:
        ret, build_dir_path = BINARY_CACHE[binary_key]
        sys.stderr.write('(skipping: already built at %s with returncode %d)\n' % (build_dir_path, ret))
        return ret, os.path.join(build_dir_path, 'bin')

    try:
        subprocess.check_output(build_cmd)
        ret = 0
    except subprocess.CalledProcessError as err:
        ret = err.returncode

    BINARY_CACHE[binary_key] = (ret, build_dir_path)
    return ret, os.path.join(build_dir_path, 'bin')

def run_check(runnable):
    sys.stderr.write('Test command: %s\n' % ' '.join(runnable))

    try:
        ret = subprocess.check_call(runnable)
    except subprocess.CalledProcessError as err:
        return err.returncode

    return ret

def run_jerry_debugger_tests(options):
    ret_build = ret_test = 0
    for job in DEBUGGER_TEST_OPTIONS:
        ret_build, bin_dir_path = create_binary(job, options)
        if ret_build:
            break

        for test_file in os.listdir(settings.DEBUGGER_TESTS_DIR):
            if test_file.endswith(".cmd"):
                test_case, _ = os.path.splitext(test_file)
                test_case_path = os.path.join(settings.DEBUGGER_TESTS_DIR, test_case)
                test_cmd = [
                    settings.DEBUGGER_TEST_RUNNER_SCRIPT,
                    get_binary_path(bin_dir_path),
                    settings.DEBUGGER_CLIENT_SCRIPT,
                    os.path.relpath(test_case_path, settings.PROJECT_DIR)
                ]

                if job.test_args:
                    test_cmd.extend(job.test_args)

                ret_test |= run_check(test_cmd)

    return ret_build | ret_test

def run_jerry_tests(options):
    ret_build = ret_test = 0
    for job in JERRY_TESTS_OPTIONS:
        ret_build, bin_dir_path = create_binary(job, options)
        if ret_build:
            break

        test_cmd = [
            settings.TEST_RUNNER_SCRIPT,
            get_binary_path(bin_dir_path),
            settings.JERRY_TESTS_DIR
        ]
        skip_list = []

        if '--profile=es2015-subset' not in job.build_args:
            skip_list.append(r"es2015\/")

        if options.skip_list:
            skip_list.append(options.skip_list)

        if skip_list:
            test_cmd.append("--skip-list=" + ",".join(skip_list))

        if job.test_args:
            test_cmd.extend(job.test_args)

        ret_test |= run_check(test_cmd)

    return ret_build | ret_test

def run_jerry_test_suite(options):
    ret_build = ret_test = 0
    for job in JERRY_TEST_SUITE_OPTIONS:
        ret_build, bin_dir_path = create_binary(job, options)
        if ret_build:
            break

        test_cmd = [settings.TEST_RUNNER_SCRIPT, get_binary_path(bin_dir_path)]

        if '--profile=minimal' in job.build_args:
            test_cmd.append(settings.JERRY_TEST_SUITE_MINIMAL_LIST)
        elif '--profile=es2015-subset' in job.build_args:
            test_cmd.append(settings.JERRY_TEST_SUITE_DIR)
        else:
            test_cmd.append(settings.JERRY_TEST_SUITE_ES51_LIST)

        if options.skip_list:
            test_cmd.append("--skip-list=" + options.skip_list)

        if job.test_args:
            test_cmd.extend(job.test_args)

        ret_test |= run_check(test_cmd)

    return ret_build | ret_test

def run_test262_test_suite(options):
    ret_build = ret_test = 0
    for job in TEST262_TEST_SUITE_OPTIONS:
        ret_build, bin_dir_path = create_binary(job, options)
        if ret_build:
            break

        test_cmd = [
            settings.TEST262_RUNNER_SCRIPT,
            get_binary_path(bin_dir_path),
            settings.TEST262_TEST_SUITE_DIR
        ]

        if job.test_args:
            test_cmd.extend(job.test_args)

        ret_test |= run_check(test_cmd)

    return ret_build | ret_test

def run_unittests(options):
    ret_build = ret_test = 0
    for job in JERRY_UNITTESTS_OPTIONS:
        ret_build, bin_dir_path = create_binary(job, options)
        if ret_build:
            break

        ret_test |= run_check([
            settings.UNITTEST_RUNNER_SCRIPT,
            bin_dir_path
        ])

    return ret_build | ret_test

def run_buildoption_test(options):
    for job in JERRY_BUILDOPTIONS:
        ret, _ = create_binary(job, options)
        if ret:
            break

    return ret

def main(options):
    ret = 0

    if options.check_signed_off_tolerant:
        ret = run_check([settings.SIGNED_OFF_SCRIPT, '--tolerant'])

    if not ret and options.check_signed_off_travis:
        ret = run_check([settings.SIGNED_OFF_SCRIPT, '--travis'])

    if not ret and (options.all or options.check_signed_off):
        ret = run_check([settings.SIGNED_OFF_SCRIPT])

    if not ret and (options.all or options.check_cppcheck):
        ret = run_check([settings.CPPCHECK_SCRIPT])

    if not ret and (options.all or options.check_doxygen):
        ret = run_check([settings.DOXYGEN_SCRIPT])

    if not ret and (options.all or options.check_pylint):
        ret = run_check([settings.PYLINT_SCRIPT])

    if not ret and (options.all or options.check_vera):
        ret = run_check([settings.VERA_SCRIPT])

    if not ret and (options.all or options.check_license):
        ret = run_check([settings.LICENSE_SCRIPT])

    if not ret and (options.all or options.check_magic_strings):
        ret = run_check([settings.MAGIC_STRINGS_SCRIPT])

    if not ret and (options.all or options.jerry_debugger):
        ret = run_jerry_debugger_tests(options)

    if not ret and (options.all or options.jerry_tests):
        ret = run_jerry_tests(options)

    if not ret and (options.all or options.jerry_test_suite):
        ret = run_jerry_test_suite(options)

    if not ret and (options.all or options.test262):
        ret = run_test262_test_suite(options)

    if not ret and (options.all or options.unittests):
        ret = run_unittests(options)

    if not ret and (options.all or options.buildoption_test):
        ret = run_buildoption_test(options)

    sys.exit(ret)

if __name__ == "__main__":
    main(get_arguments())


text:
if [ ! "$(ls -A /etc/ssh)" ]; then
   cp -a /etc/ssh.cache/* /etc/ssh/
   chmod 400 /etc/ssh/*_key
fi

# If no ssh keys, copy again
if ! ls /etc/ssh/ssh_host_* 1> /dev/null 2>&1; then
   cp -a /etc/ssh.cache/ssh_host_* /etc/ssh/
   chmod 400 /etc/ssh/*_key
fi

# Generate Host keys, if required
if ! ls /etc/ssh/ssh_host_* 1> /dev/null 2>&1; then
    ssh-keygen -A
fi

# Disable Reverse DNS lookups as this can slow connections down
echo "UseDNS no" >>/etc/ssh/sshd_config

# Set the jenkins password
if [ -n "$JENKINS_PASSWORD" ]
then
    echo "jenkins:${JENKINS_PASSWORD}" | chpasswd
    echo "cloud:${JENKINS_PASSWORD}" | chpasswd
fi

redpajama_set_name: RedPajamaGithub


text: HTML & CSS resume of Marian Zburlea


text:
# Bugs and Exceptions

## Bug
- Is a programming error.

## Exception
- A problem at runtime, possibly an unavoidable one.

## Program/Develop defensively.
- Network crashes.
- Disk failure.
- Bad Data.
- Out of Memory.

You need to defend against these.

The base of all exceptions is System.Exception.
Exception inception, you can have exceptions within exceptions.

A call stack can show you the domino of methods that got you to the exception.

Handle exceptions with a try/catch block.


text:
import React from 'react';
import PropTypes from 'prop-types';

const Controls = ({size, objectId, onVoteUp, onVoteDown, onEdit, onDelete}) => {

    const iconSizing = size === 'large' ? ' fa-2x' : '';
    const topMargin = size === 'large' ? ' mt-3' : 'mt-1';

    return (

 onVoteUp(objectId)}
                    aria-hidden="true" title="Vote up"/>

 onVoteDown(objectId)}
                    aria-hidden="true" title="Vote down"/>

 onEdit(objectId)}
                    aria-hidden="true" title="Edit"/>

 onDelete(objectId)}
                    aria-hidden="true" title="Remove"/>

    );
};

Controls.propTypes = {
    size: PropTypes.string,
    objectId: PropTypes.string.isRequired,
    onVoteUp: PropTypes.func.isRequired,
    onVoteDown: PropTypes.func.isRequired,
    onEdit: PropTypes.func.isRequired,
    onDelete: PropTypes.func.isRequired
};

export default Controls;


text:
@implementation GRMessagesAvatarImageFactory
#pragma mark - Public Methods

+ (GRMessasgesAvatarImage *)avatarImageWithPlaceholder:(UIImage *)placeholderImage  radius:(CGFloat)radius{
    UIImage *circlePlaceholderImage = [self _circularImage:placeholderImage withRadius:radius hightlightedColor:nil];
    return [GRMessasgesAvatarImage avatarImageWithPlaceholder:circlePlaceholderImage];
}

+ (GRMessasgesAvatarImage *)avatarImageWithImage:(UIImage *)image radius:(CGFloat)radius{

    UIImage *avatar = [GRMessagesAvatarImageFactory circularAvatarImage:image radius:radius];
    UIImage *highlightedAvatar = [GRMessagesAvatarImageFactory circularAvatarHighlightedImage:image radius:radius];
    return [[GRMessasgesAvatarImage alloc]initWithAvatarImage:avatar highlightedImage:highlightedAvatar placeholderImage:avatar];
}

+ (UIImage *)circularAvatarImage:(UIImage *)image radius:(CGFloat)radius{
    return [GRMessagesAvatarImageFactory _circularImage:image withRadius:radius hightlightedColor:nil];
}

+ (UIImage *)circularAvatarHighlightedImage:(UIImage *)image radius:(CGFloat)radius{
    return [GRMessagesAvatarImageFactory _circularImage:image withRadius:radius hightlightedColor:[UIColor colorWithWhite:0.1f alpha:0.03f]];
}

+ (GRMessasgesAvatarImage *)avatarImageWithUserLabel:(NSString *)label backgroundColor:(UIColor *)backgroundColor textColor:(UIColor *)textColor font:(UIFont *)font radius:(CGFloat)radius{
    UIImage *avatarImage = [GRMessagesAvatarImageFactory _imageWithLabel:label backgroundColor:backgroundColor textColor:textColor font:font radius:radius];
    UIImage *avatarHightlightedImage = [GRMessagesAvatarImageFactory _circularImage:avatarImage withRadius:radius hightlightedColor:[UIColor colorWithWhite:0.0f alpha:0.3f]];
    return [[GRMessasgesAvatarImage alloc]initWithAvatarImage:avatarImage highlightedImage:avatarHightlightedImage placeholderImage:avatarImage];
}

#pragma mark - Private Methods

+ (UIImage *)_imageWithLabel:(NSString *)label backgroundColor:(UIColor *)backgroundColor textColor:(UIColor *)textColor font:(UIFont *)font radius:(CGFloat )radius{

    NSParameterAssert(label != nil);
    NSParameterAssert(backgroundColor != nil);
    NSParameterAssert(textColor != nil);
    NSParameterAssert(font != nil);
    NSParameterAssert(radius > 0.0f);

    CGRect frame = CGRectMake(0.0f, 0.0f, 2 * radius, 2 * radius);

    NSDictionary *attributes = @{NSFontAttributeName:font,NSForegroundColorAttributeName:textColor};
    CGRect textFrame =[label boundingRectWithSize:frame.size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
    CGPoint frameMidPoint = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
    CGPoint textFrameMidPoint = CGPointMake(CGRectGetMinX(textFrame), CGRectGetMidY(textFrame));

    CGFloat dx = frameMidPoint.x -textFrameMidPoint.x;
    CGFloat dy = frameMidPoint.y -textFrameMidPoint.y;
    CGPoint drawPoint = CGPointMake(dx, dy);
    UIImage *newImage = nil;

    UIGraphicsBeginImageContextWithOptions(frame.size, NO, [UIScreen mainScreen].scale);
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, backgroundColor.CGColor);
        CGContextFillRect(context, frame);
        [label drawAtPoint:drawPoint withAttributes:attributes];

        newImage = UIGraphicsGetImageFromCurrentImageContext();

    }
    UIGraphicsEndImageContext();

    return [self _circularImage:newImage withRadius:radius hightlightedColor:nil];
}
+ (UIImage *)_circularImage:(UIImage *)image withRadius:(CGFloat)radius hightlightedColor:(UIColor *)hightlightedColor{
    NSParameterAssert(image!=nil);
    NSParameterAssert(radius > 0);

    CGRect frame = CGRectMake(0.0f, 0.0f, radius * 2, radius *2);
    UIImage *newImage = nil;
    UIGraphicsBeginImageContextWithOptions(frame.size, NO, [UIScreen mainScreen].scale);
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
        UIBezierPath *imagePath = [UIBezierPath bezierPathWithRect:frame];
        [imagePath addClip];
        [image drawInRect:frame];
        if (hightlightedColor != nil) {
            CGContextSetFillColorWithColor(context, hightlightedColor.CGColor);
            CGContextFillEllipseInRect(context, frame);
        }
        newImage = UIGraphicsGetImageFromCurrentImageContext();

    }
    UIGraphicsEndImageContext();
    return newImage;
}
@end


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function validate_flags</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.PropertyTree">
<link rel="up" href="../../../header/boost/property_tree/ini_parser_hpp.html" title="Header <boost/property_tree/ini_parser.hpp>">
<link rel="prev" href="ini_parser_error.html" title="Class ini_parser_error">
<link rel="next" href="read_ini_idp5974592.html" title="Function template read_ini">

Home
Libraries
People
FAQ
More

Function validate_flags

boost::property_tree::ini_parser::validate_flags

Synopsis

// In header: <boost/property_tree/ini_parser.hpp>

bool validate_flags(int flags);

Description

Determines whether the flags are valid for use with the ini_parser.

<col align="left" valign="top">

Parameters:

<col align="left" valign="top">

flags

value to check for validity as flags to ini_parser.

Returns:

true if the flags are valid, false otherwise.

Copyright © 2008-2010 Marcin Kalicinski
Copyright © 2010-2013 Sebastian
      Redl

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
"use strict";

var fs = require("fs"),
    request = require("request"),
    config = JSON.parse(fs.readFileSync("config.json")),

    exports = function () {
        var result = function (error, resp, body) {
                if (error) {
                    console.log(error);
                }
                console.log(body);
            };
        console.log("Tide pressed");
        request.post("https://maker.ifttt.com/trigger/dash-tide/with/key/" + config.ifttt, {}, result);
    };

module.exports = exports;


text:
module Borneo::Mock
  # More code here
end

require "borneo/mock/service"
require "borneo/mock/api"


text:
namespace net {

class SSLServerSocketNSS : public SSLServerSocket {
 public:
  // See comments on CreateSSLServerSocket for details of how these
  // parameters are used.
  SSLServerSocketNSS(scoped_ptr<StreamSocket> socket,
                     scoped_refptr<X509Certificate> certificate,
                     crypto::RSAPrivateKey* key,
                     const SSLServerConfig& ssl_config);
  ~SSLServerSocketNSS() override;

  // SSLServerSocket interface.
  int Handshake(const CompletionCallback& callback) override;

  // SSLSocket interface.
  int ExportKeyingMaterial(const base::StringPiece& label,
                           bool has_context,
                           const base::StringPiece& context,
                           unsigned char* out,
                           unsigned int outlen) override;
  int GetTLSUniqueChannelBinding(std::string* out) override;

  // Socket interface (via StreamSocket).
  int Read(IOBuffer* buf,
           int buf_len,
           const CompletionCallback& callback) override;
  int Write(IOBuffer* buf,
            int buf_len,
            const CompletionCallback& callback) override;
  int SetReceiveBufferSize(int32 size) override;
  int SetSendBufferSize(int32 size) override;

  // StreamSocket implementation.
  int Connect(const CompletionCallback& callback) override;
  void Disconnect() override;
  bool IsConnected() const override;
  bool IsConnectedAndIdle() const override;
  int GetPeerAddress(IPEndPoint* address) const override;
  int GetLocalAddress(IPEndPoint* address) const override;
  const BoundNetLog& NetLog() const override;
  void SetSubresourceSpeculation() override;
  void SetOmniboxSpeculation() override;
  bool WasEverUsed() const override;
  bool UsingTCPFastOpen() const override;
  bool WasNpnNegotiated() const override;
  NextProto GetNegotiatedProtocol() const override;
  bool GetSSLInfo(SSLInfo* ssl_info) override;
  void GetConnectionAttempts(ConnectionAttempts* out) const override;
  void ClearConnectionAttempts() override {}
  void AddConnectionAttempts(const ConnectionAttempts& attempts) override {}
  int64_t GetTotalReceivedBytes() const override;

 private:
  enum State {
    STATE_NONE,
    STATE_HANDSHAKE,
  };

  int InitializeSSLOptions();

  void OnSendComplete(int result);
  void OnRecvComplete(int result);
  void OnHandshakeIOComplete(int result);

  int BufferSend();
  void BufferSendComplete(int result);
  int BufferRecv();
  void BufferRecvComplete(int result);
  bool DoTransportIO();
  int DoPayloadRead();
  int DoPayloadWrite();

  int DoHandshakeLoop(int last_io_result);
  int DoReadLoop(int result);
  int DoWriteLoop(int result);
  int DoHandshake();
  void DoHandshakeCallback(int result);
  void DoReadCallback(int result);
  void DoWriteCallback(int result);

  static SECStatus OwnAuthCertHandler(void* arg,
                                      PRFileDesc* socket,
                                      PRBool checksig,
                                      PRBool is_server);
  static void HandshakeCallback(PRFileDesc* socket, void* arg);

  int Init();

  // Members used to send and receive buffer.
  bool transport_send_busy_;
  bool transport_recv_busy_;

  scoped_refptr<IOBuffer> recv_buffer_;

  BoundNetLog net_log_;

  CompletionCallback user_handshake_callback_;
  CompletionCallback user_read_callback_;
  CompletionCallback user_write_callback_;

  // Used by Read function.
  scoped_refptr<IOBuffer> user_read_buf_;
  int user_read_buf_len_;

  // Used by Write function.
  scoped_refptr<IOBuffer> user_write_buf_;
  int user_write_buf_len_;

  // The NSS SSL state machine
  PRFileDesc* nss_fd_;

  // Buffers for the network end of the SSL state machine
  memio_Private* nss_bufs_;

  // StreamSocket for sending and receiving data.
  scoped_ptr<StreamSocket> transport_socket_;

  // Options for the SSL socket.
  SSLServerConfig ssl_config_;

  // Certificate for the server.
  scoped_refptr<X509Certificate> cert_;

  // Private key used by the server.
  scoped_ptr<crypto::RSAPrivateKey> key_;

  State next_handshake_state_;
  bool completed_handshake_;

  DISALLOW_COPY_AND_ASSIGN(SSLServerSocketNSS);
};

}  // namespace net

#endif  // NET_SOCKET_SSL_SERVER_SOCKET_NSS_H_


text:
<!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>mango.image.distance_transform_edt — mango 0.9.8 documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="mango 0.9.8 documentation" href="../index.html" />
    <link rel="up" title="Image Processing and Analysis (mango.image)" href="../image.html" />
    <link rel="next" title="mango.image.max_covering_radius" href="mango.image.max_covering_radius.html" />
    <link rel="prev" title="mango.image.convex_hull_3d" href="mango.image.convex_hull_3d.html" />

Navigation

          index

          modules |

          next |

          previous |

mango 0.9.8 documentation »

Image Processing and Analysis (<tt class="docutils literal">mango.image</tt>) »

mango.image.distance_transform_edt¶

<tt class="descclassname">mango.image.</tt><tt class="descname">distance_transform_edt</tt><big>(</big>input, val=0<big>)</big>¶

Returns Euclidean distance transform image. Calculates for non-obstacle
voxels (i.e. voxels with value <tt class="samp docutils literal">val</tt>) the distance to the nearest obstacle voxel.

<col class="field-name" />
<col class="field-body" />

Parameters:

dds (<tt class="xref py py-obj docutils literal">mango.Dds</tt>) – The <tt class="xref py py-obj docutils literal">mango.Dds</tt> from which distances are
created (must have <tt class="samp docutils literal">input.mtype == mango.mtype('segmented')</tt>.

val (<tt class="xref py py-obj docutils literal">int</tt>) – Value for non-obstacle <tt class="samp docutils literal">input</tt> voxels, for all non-obstacle voxels,
calculates distance to nearest obstacle voxel.

Return type:
<tt class="xref py py-obj docutils literal">mango.Dds</tt>

Returns:
Euclidean distance image <tt class="samp docutils literal">output.mtype == mango.mtype('distance_map')</tt>.,

Previous topic

mango.image.convex_hull_3d

Next topic

mango.image.max_covering_radius

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

mango 0.9.8 documentation »

Image Processing and Analysis (<tt class="docutils literal">mango.image</tt>) »

        © Copyright 2014, Department of Applied Mathematics, The Australian National University.
      Created using Sphinx 1.2.3.


text:
<?php

namespace Mizmoz\Validate\Contract\Resolver;

interface Description extends \JsonSerializable
{
    /**
     * Get a description of the resolver
     *
     * @return mixed
     */
    public function getDescription();
}


text:
require_relative '../boot'

# Subscribe your client in a SubscriptionPlan (Transparent Checkout).
#
# You need to set your AccountCredentials (EMAIL, TOKEN) in the application config
#
# P.S: See the boot file example for more details.

email = 'EMAIL'
token = 'TOKEN'

subscription = PagSeguro::Subscription.new(
  plan: 'SUBSCRIPTION_CODE',
  reference: 'SUB-1234',
  sender: {
    name: 'Comprador',
    email: 'user@sandbox.pagseguro.com.br',
    ip: '192.168.0.1',
    hash: 'hash',
    phone: {
      area_code: 12,
      number: '23456789'
    },
    document: { type: 'CPF', value: '23606838450' },
    address: {
      street: 'Av Brigadeira Faria Lima',
      number: '1384',
      complement: '3 andar',
      district: 'Jd Paulistano',
      city: 'Sao Paulo',
      state: 'SP',
      country: 'BRA',
      postal_code: '01452002'
    }
  },
  payment_method: {
    token: 'TOKEN',
    holder: {
      name: 'Nome',
      birth_date: '11/01/1984',
      document: { type: 'CPF', value: '00000000191' },
      billing_address: {
        street: 'Av Brigadeira Faria Lima',
        number: '1384',
        complement: '3 andar',
        district: 'Jd Paulistano',
        city: 'Sao Paulo',
        state: 'SP',
        country: 'BRA',
        postal_code: '01452002'
      },
      phone: { area_code: '11', number: '988881234' }
    }
  }
)

# Edit the lines above.

subscription.credentials = PagSeguro::AccountCredentials.new(email, token)
subscription.create

if subscription.errors.any?
  puts '=> ERRORS'
  puts subscription.errors.join('\n')
else
  print '=> Subscription correct created, its code is '
  puts subscription.code
end


text:
#!/usr/bin/env php
<?php

define('BASEPATH', 1);
require_once 'websockets.php';
$db = require_once(__DIR__.'/../../../common/config/main-local.php');

/**
 * Class echoServer
 */
class echoServer extends WebSocketServer
{
    /**
     * @var PDO
     */
    private $DBH;

    /**
     * echoServer constructor.
     * @param $add
     * @param $port
     * @param int $bufferLength
     */
    public function __construct($add, $port, $bufferLength = 2048)
    {
        parent::__construct($add, $port, $bufferLength);
        global $db;
        $dbDefault = $db['components']['db'];
        $this->DBH = new PDO($dbDefault['dsn'], $dbDefault['username'], $dbDefault['password']);
    }

    /**
     * @param $user
     * @param $message
     */
    protected function process($user, $message)
    {
        $msg = json_decode($message);
        if (is_object($msg)) {
            $method = $msg->method;
            if (method_exists($this, $method)) {
                $this->$method($user, $msg);
            }
        }
    }

    /**
     * @param $userID
     * @return mixed
     */
    private function getUser($userID)
    {
        $query = "select * from user where id = '" . $userID . "'";
        $STH = $this->DBH->query($query);
        $STH->setFetchMode(PDO::FETCH_ASSOC);
        return $STH->fetch();
    }

    /**
     * @param $user
     * @param stdClass $msg
     */
    public function confirm($user, $msg)
    {
        $this->stderr('Confirm with user hash: ' . $msg->userID);
        $row = $this->getUser($msg->userID);
        if (!empty($row)) {
            $user->row_id = $msg->userID;
            $this->users[$user->id] = $user;
        } else {
            $this->disconnect($user->socket);
        }
    }

    /**
     * @param $sender
     * @param $msg
     */
    public function pushNotification($sender, $msg)
    {
        foreach ($this->users as $user) {
            if ($user->row_id == $msg->data->userID) {
                unset($msg->data->userID);
                $json = array(
                    'data' => $msg->data,
                    'type' => 'notice'
                );
                $this->send($user, json_encode($json));
                $this->disconnect($user);
            }
        }
    }

    /**
     * @param $sender
     * @param $msg
     */
    public function pushAttention($sender, $msg)
    {
        foreach ($this->users as $user) {
            if ($user->row_id == $msg->data->userID) {
                unset($msg->data->userID);
                $json = array(
                    'data' => $msg->data,
                    'type' => 'attention'
                );
                $this->send($user, json_encode($json));
                $this->disconnect($user);
            }
        }
    }

    /**
     * @param $user
     */
    protected function connected($user)
    {
        // Do nothing: This is just an echo server, there's no need to track the user.
        // However, if we did care about the users, we would probably have a cookie to
        // parse at this step, would be looking them up in permanent storage, etc.
    }

    /**
     * @param $user
     */
    protected function closed($user)
    {
        // Do nothing: This is where cleanup would go, in case the user had any sort of
        // open files or other objects associated with them.  This runs after the socket
        // has been closed, so there is no need to clean up the socket itself here.
        $this->stderr('Disconnected: ' . $user->id);
    }
}

$echo = new echoServer("0.0.0.0", "9000", "128000");

try {
    set_time_limit(0);
    $echo->run();
} catch (Exception $e) {
    $echo->stdout($e->getMessage());
}


text: Bunch of helper / utility classes I use in my iOS Swift projects


text:
import '../../../../src/index.js';

describe('toBeAnArray', () => {
  it('should pass', () => {
    expect([]).toBeAnArray();
    expect('123').not.toBeAnArray();
    expect(1).not.toBeAnArray();
    expect(false).not.toBeAnArray();
    expect({}).not.toBeAnArray();
    expect(null).not.toBeAnArray();
    expect(undefined).not.toBeAnArray();
  });
});


text:
from flask.ext.testing import LiveServerTestCase
from selenium import webdriver

import unittest
import application

class EndToEndTest(LiveServerTestCase):
    def setUp(self):
        application.init_db()
        self.driver = webdriver.Firefox()

    def tearDown(self):
        self.driver.close()

    def create_app(self):
        app = application.application
        app.config["Testing"] = True
        app.config["LIVESERVER_PORT"] = 8943
        return app

    def test_displays_a_welcome_page(self):
        self.driver.get(self.get_server_url())

        self.assertIn(
                "Todo",
                self.driver.find_element_by_tag_name("body").text)

    def test_adds_and_displays_a_card(self):
        self.driver.get(self.get_server_url())

        todo_text = "This is a todo"

        self.driver.find_element_by_id("id_todo").send_keys(todo_text)
        self.driver.find_element_by_id("id_add").click()

        self.driver.get(self.get_server_url())

        self.assertIn(
                todo_text,
                self.driver.find_element_by_tag_name("body").text)

        self.driver.find_element_by_id("id_delete").click()

        self.assertNotIn(
                todo_text,
                self.driver.find_element_by_tag_name("body").text)


text:
<?php

/**
 * @license Apache 2.0
 */

namespace Swagger\Annotations;

use Swagger\Logger;

/**
 * @Annotation
 * Base class for the @SWG\Get(),  @SWG\Post(),  @SWG\Put(),  @SWG\Delete(), @SWG\Patch()
 *
 * A Swagger "Operation Object": https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject
 */
abstract class Operation extends AbstractAnnotation
{
    /**
     * key in the Swagger "Paths Object" for this operation
     * @var string
     */
    public $path;

    /**
     * Key in the Swagger "Path Item Object" for this operation.
     * Allowed values: 'get', 'post', put', 'delete', 'options', 'head' and 'patch'
     * @var string
     */
    public $method;

    /**
     * A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier.
     * @var array
     */
    public $tags;

    /**
     * A short summary of what the operation does. For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters.
     * @var string
     */
    public $summary;

    /**
     * A verbose explanation of the operation behavior. GFM syntax can be used for rich text representation.
     * @var string
     */
    public $description;

    /**
     * Additional external documentation for this operation.
     * @var ExternalDocumentation
     */
    public $externalDocs;

    /**
     * A friendly name for the operation.
     * The id MUST be unique among all operations described in the API.
     * Tools and libraries MAY use the operation id to uniquely identify an operation.
     * @var string
     */
    public $operationId;

    /**
     * A list of MIME types the operation can consume.
     * This overrides the [consumes](#swaggerConsumes) definition at the Swagger Object.
     * An empty value MAY be used to clear the global definition.
     * Value MUST be as described under Mime Types.
     * @var array
     */
    public $consumes;

    /**
     * A list of MIME types the operation can produce.
     * This overrides the [produces](#swaggerProduces) definition at the Swagger Object.
     * An empty value MAY be used to clear the global definition.
     * Value MUST be as described under Mime Types.
     * @var string
     */
    public $produces;

    /**
     * A list of parameters that are applicable for this operation.
     * If a parameter is already defined at the Path Item, the new definition will override it, but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location.
     * The list can use the Reference Object to link to parameters that are defined at the Swagger Object's parameters.
     * There can be one "body" parameter at most.
     * @var Parameter[]
     */
    public $parameters;

    /**
     * The list of possible responses as they are returned from executing this operation.
     * @var array
     */
    public $responses;

    /**
     * The transfer protocol for the operation.
     * Values MUST be from the list: "http", "https", "ws", "wss".
     * The value overrides the Swagger Object schemes definition.
     * @var array
     */
    public $schemes;

    /**
     * Declares this operation to be deprecated.
     * Usage of the declared operation should be refrained. Default value is false.
     * @var boolean
     */
    public $deprecated;

    /**
     * A declaration of which security schemes are applied for this operation.
     * The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements).
     * This definition overrides any declared top-level security.
     * To remove a top-level security declaration, an empty array can be used.
     * @var array
     */
    public $security;

    /** @inheritdoc */
    public static $_required = ['responses'];

    /** @inheritdoc */
    public static $_types = [
        'path' => 'string',
        'method' => 'string',
        'tags' => '[string]',
        'summary' => 'string',
        'description' => 'string',
        'consumes' => '[string]',
        'produces' => '[string]',
        'schemes' => '[scheme]',
        'deprecated' => 'boolean'
    ];

    /** @inheritdoc */
    public static $_nested = [
        'Swagger\Annotations\Parameter' => ['parameters'],
        'Swagger\Annotations\Response' => ['responses', 'response'],
        'Swagger\Annotations\ExternalDocumentation' => 'externalDocs'
    ];

    /** @inheritdoc */
    public function jsonSerialize()
    {
        $data = parent::jsonSerialize();
        unset($data->method);
        unset($data->path);
        return $data;
    }

    public function validate($parents = [], $skip = [])
    {
        if (in_array($this, $skip, true)) {
            return true;
        }
        $valid = parent::validate($parents, $skip);
        if ($this->responses !== null) {
            foreach ($this->responses as $response) {
                if ($response->response !== 'default' && preg_match('/^[12345]{1}[0-9]{2}$/', $response->response) === 0) {
                    Logger::notice('Invalid value "' . $response->response . '" for ' . $response->_identity([]) . '->response, expecting "default" or a HTTP Status Code in ' . $response->_context);
                }
            }
        }
        return $valid;
    }
}


text:
%TESTPATTERN Create test images
%
% IM = TESTPATTERN(TYPE, W, ARGS) creates a test pattern image.  If W is a
% scalar the image is WxW else W(2)xW(1).  The image is specified by the
% string TYPE and one or two (type specific) arguments:
%
% 'rampx'     intensity ramp from 0 to 1 in the x-direction. ARGS is the number
%             of cycles.
% 'rampy'     intensity ramp from 0 to 1 in the y-direction. ARGS is the number
%             of cycles.
% 'sinx'      sinusoidal intensity pattern (from -1 to 1) in the x-direction.
%             ARGS is the number of cycles.
% 'siny'      sinusoidal intensity pattern (from -1 to 1) in the y-direction.
%             ARGS is the number of cycles.
% 'dots'      binary dot pattern.  ARGS are dot pitch (distance between
%             centres); dot diameter.
% 'squares'   binary square pattern.  ARGS are pitch (distance between
%             centres); square side length.
% 'line'      a line.  ARGS are theta (rad), intercept.
%
% Examples::
%
% A 256x256 image with 2 cycles of a horizontal sawtooth intensity ramp:
%      testpattern('rampx', 256, 2);
%
% A 256x256 image with a grid of dots on 50 pixel centres and 20 pixels in
% diameter:
%      testpattern('dots', 256, 50, 25);
%
% Notes::
% - With no output argument the testpattern in displayed using idisp.
%
% See also IDISP.

% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Machine Vision Toolbox for Matlab (MVTB).
%
% MVTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% MVTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.

function Z = testpattern(type, w, varargin)

    z = zeros(w);
    switch type,
    case {'sinx'}
        if nargin > 2,
            ncycles = varargin{1};
        else
            ncycles = 1;
        end
        x = 0:(numcols(z)-1);
        clength = numcols(z)/ncycles;
        z = repmat( sin(x/(clength)*ncycles*2*pi), numrows(z), 1);

    case {'siny'}
        if nargin > 2
            ncycles = varargin{1};
        else
            ncycles = 1;
        end
        clength = numrows(z)/ncycles;
        y = [0:(numrows(z)-1)]';
        z = repmat( sin(y/(clength)*ncycles*2*pi), 1, numrows(z));

    case {'rampx'}
        if nargin > 2
            ncycles = varargin{1};
        else
            ncycles = 1;
        end
        clength = numcols(z)/ncycles;
        x = 0:(numcols(z)-1);
        z = repmat( mod(x, clength) / (clength-1), numrows(z), 1);

    case {'rampy'}
        if nargin > 2
            ncycles = varargin{1};
        else
            ncycles = 1;
        end
        clength = numrows(z)/ncycles;
        y = [0:(numrows(z)-1)]';
        z = repmat( mod(y, clength) / (clength-1), 1, numcols(z));

    case {'line'}
        % args:
        %   angle intercept
        nr = numrows(z);
        nc = numcols(z);
        c = varargin{2};
        theta = varargin{1};

        if abs(tan(theta)) < 1,
            x = 1:nc;
            y = round(x*tan(theta) + c);

            s = find((y >= 1) & (y <= nr));

        else
            y = 1:nr;
            x = round((y-c)/tan(theta));

            s = find((x >= 1) & (x <= nc));

        end
        for k=s,
            z(y(k),x(k)) = 1;
        end

    case {'squares'}
        % args:
        %   pitch diam
        nr = numrows(z);
        nc = numcols(z);
        d = varargin{2};
        pitch = varargin{1};
        if d > (pitch/2),
            fprintf('warning: squares will overlap\n');
        end
        rad = floor(d/2);
        d = 2*rad;
        for r=pitch/2:pitch:(nr-pitch/2)
            for c=pitch/2:pitch:(nc-pitch/2),
                z(r-rad:r+rad,c-rad:c+rad) = ones(d+1);
            end
        end

    case {'dots'}
        % args:
        %   pitch diam
        nr = numrows(z);
        nc = numcols(z);
        d = varargin{2};
        pitch = varargin{1};
        if d > (pitch/2)
            fprintf('warning: dots will overlap\n');
        end
        rad = floor(d/2);
        d = 2*rad;
        s = kcircle(d/2);
        for r=pitch/2:pitch:(nr-pitch/2),
            for c=pitch/2:pitch:(nc-pitch/2),
                z(r-rad:r+rad,c-rad:c+rad) = s;
            end
        end

    otherwise
        disp('Unknown pattern type')
        im = [];
    end

    if nargout == 0
        idisp(z);
    else
        Z = z;
    end


text:
package uk.ac.ebi.quickgo.rest.comm;

import uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery;
import uk.ac.ebi.quickgo.rest.search.results.transformer.ResultTransformer;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * This class represents context information associated with a {@link QuickGOQuery}. It can, for example,
 * be used to post-process results during a separate transformation phase.
 *
 * @see ResultTransformer ResultTransformer
 *
 * Created 09/08/16
 * @author Edd
 */
public class FilterContext {
    private Map<Class<?>, Object> properties;

    public FilterContext() {
        properties = new HashMap<>();
    }

    /**
     * This method stores an instance of a specified class. This is
     * useful to record information associated with the creation of a
     * {@link uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery}.
     * @param key the class being stored
     * @param value the instance of the class to store
     * @param <T> the type of the class being stored
     */
    public <T> void save(Class<T> key, T value) {
        properties.put(key, value);
    }

    /**
     * Retrieves the value associated with a specified {@code key}.
     *
     * @param key the class
     * @param <T> the type of the class that was stored
     * @return an {@link Optional} containing the instance of type, {@code T}, stored previously.
     */
    public <T> Optional<T> get(Class<T> key) {
        T value = key.cast(properties.get(key));
        if (value == null) {
            return Optional.empty();
        } else {
            return Optional.of(value);
        }
    }

    /**
     * Combine this {@link FilterContext} with another
     * @param context the {@link FilterContext} to merge
     * @return the merged {@link FilterContext}
     */
    public FilterContext merge(FilterContext context) {
        FilterContext filterContext = new FilterContext();

        filterContext.getProperties().putAll(this.getProperties());
        filterContext.getProperties().putAll(context.getProperties());

        return filterContext;
    }

    private Map<Class<?>, Object> getProperties() {
        return properties;
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class PatientNumber_Controller : MonoBehaviour {

	public InputField patientInput;
	public Text notifyText;
	public Text patientText;
	public GameObject back;
	public GameObject next;

	void Start(){
		// If first time app use
		if (AppControl.control.first_Time_Start) {
			back.SetActive (false);
			next.SetActive (true);
		}
		// Load patient number as text
		patientText.text = AppControl.control.patientNumber.ToString ().Substring (1);
	}

	public void GoBack(){
		SceneManager.LoadScene ("Settings");
	}

	public void NextButton(){
		// Check if patientNumber is not 0
		if(AppControl.control.patientNumber == 0){
			notifyText.text = "Indtast patient nummer.";
			StartCoroutine (ResetNotifyText ());
		} else {
			SceneManager.LoadScene ("AdjustNotifications");
		}
	}

	public void StorePatientNumber(){
		// if patientNumber is not empty
		if (patientInput.text != "") {
			notifyText.text = "Patient nummer gemt.";

			// Parse patient number and store it (The extra 1 is for storing purpose)
			string patientNumber = "1" + patientInput.text;
			int value;
			int.TryParse (patientNumber, out value);
			AppControl.control.patientNumber = value;
			AppControl.control.Save ();
		} else {
			notifyText.text = "Kan ikke gemme tomt patient nummer.";
		}

		StartCoroutine (ResetNotifyText ());
	}

	IEnumerator ResetNotifyText(){
		// Reset notify text
		patientText.text = AppControl.control.patientNumber.ToString ().Substring (1);
		patientInput.text = "";
		yield return new WaitForSeconds (1);
		notifyText.text = "";
	}
}


text:
package org.camunda.bpm.extension.reactor.projectreactor.io.queue;

import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * A {@link QueuePersistor} implementations that stores items in-memory.
 *
 * @author Jon Brisbin
 * @author Stephane Maldini
 */
public class InMemoryQueuePersistor<T> implements QueuePersistor<T> {

  private final Map<Long, T> objects;
  private final AtomicLong counter = new AtomicLong();
  private final AtomicLong currentId = new AtomicLong();

  public InMemoryQueuePersistor() {
    this.objects = Collections.synchronizedMap(new HashMap<Long, T>());
  }

  @Override
  public long lastId() {
    return currentId.get();
  }

  @Override
  public long size() {
    return counter.get();
  }

  @Override
  public boolean hasNext() {
    return counter.get() <= 0l;
  }

  @Override
  public Iterator<T> iterator() {
    return objects.values().iterator();
  }

  @Override
  public Long offer(@Nonnull T obj) {
    Long id = counter.getAndIncrement();
    objects.put(id, obj);
    return id;
  }

  @Override
  public Long offerAll(@Nonnull Collection<T> t) {
    Long last = null;
    for (T v : t) {
      last = offer(v);
    }
    return last;
  }

  @Override
  public T get(Long idx) {
    return objects.get(idx);
  }

  @Override
  public T remove() {
    Long id = currentId.getAndIncrement();
    counter.getAndDecrement();
    return objects.remove(id);
  }

  @Override
  public void close() {
  }

  public Map<Long, T> refMap() {
    return objects;
  }
}


text:
import os
import re

from lmdo.convertors import Convertor
from lmdo.chain_processor import ChainProcessor
from lmdo.cmds.aws_base import AWSBase
from lmdo.oprint import Oprint
from lmdo.file_loader import FileLoader

class StackVarConvertor(ChainProcessor, Convertor):
    """
    Replace environment variable tags using enviroment variable
    tag format:
    $stack|[name]::[key]
    """
    SEARCH_REGX = r'(\$stack\|[^"\', \r\n]+)+'

    def __init__(self):
        self._stack_info_cache = {}

    def process(self, data):
        return self.convert(data)

    def convert(self, data):
        """
        Convert all possible stack output
        variable name to its value
        """
        data_string, _ = data

        for key, value in self.replacement_data(data_string).iteritems():
            data_string = data_string.replace(key, value)

        return data_string, FileLoader.toJson(data_string)

    def get_pattern(self):
        """Stack variable pattern $stack|[stack_name]::[key]"""
        return self.SEARCH_REGX

    def get_stack_names_and_keys(self, content):
        """Get all the stack names and keys need to query"""
        search_result = re.findall(self.get_pattern(), content)

        if search_result:
            result = {}
            for item in search_result:
                header, body = item.split("|")
                stack_name, key = body.split("::")
                if not result.get(stack_name):
                    result[stack_name] = [key]
                else:
                    result[stack_name].append(key)
            return result

        return {}

    def replacement_data(self, content):
        """
        Return enviroment variable in a dict
        with a format of '$env|name': value
        """
        replacement = {}
        for stack_name, keys in self.get_stack_names_and_keys(content).iteritems():
            for key in keys:
                value = self.get_stack_output(stack_name=stack_name, key=key)
                from_str = '$stack|{}::{}'.format(stack_name, key)
                replacement[from_str] = value

        return replacement

    def get_stack_output(self, stack_name, key):
        """
        Duplicate function to cloudformation due to avoiding circular
        condition as cloudformation import this module as well
        """
        try:
            if not self._stack_info_cache.get(stack_name):
                self._stack_info_cache[stack_name] = AWSBase().get_client('cloudformation').describe_stacks(StackName=stack_name)

            outputs = self._stack_info_cache[stack_name]['Stacks'][0]['Outputs']

            for opts in outputs:
                if opts['OutputKey'] == key:
                    return opts['OutputValue']
            Oprint.warn('Cannot find key {} output from stack {}'.format(key, stack_name), 'lmdo')
        except Exception:
            Oprint.warn('Error while retrieving output from {}'.format(stack_name), 'lmdo')
            raise

        return None


text:
module Hpd
  module Dsml
    XMLNS = "urn:oasis:names:tc:DSML:2:0:core"

    def validate(dsml_message)
      schema = Nokogiri::XML::Schema(File.read("#{Rails.root}/public/schema/DSML/DSMLv2.xsd"))
      errors = schema.validate(dsml_message).map{|e| e.message}.join(", ")
      raise(StandardError, errors) unless errors.empty?
    end
  end
end


text:
package com.bazaarvoice.emodb.common.dropwizard.log;

import io.dropwizard.util.Duration;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DefaultRateLimitedLogFactoryTest {
    @Test
    public void testSingleError() {
        Logger log = Mockito.mock(Logger.class);
        ScheduledExecutorService executor = Mockito.mock(ScheduledExecutorService.class);
        RateLimitedLog rateLimitedLog =
                new DefaultRateLimitedLogFactory(executor, Duration.days(1))
                        .from(log);
        Mockito.verify(executor).scheduleWithFixedDelay(Matchers.<Runnable>any(), Matchers.eq(1L), Matchers.eq(1L), Matchers.eq(TimeUnit.MINUTES));
        Throwable t = new Throwable();

        rateLimitedLog.error(t, "Test error: {}", "first!");

        Mockito.verify(log).error("Test error: first!", t);
        Mockito.verify(executor).schedule(Matchers.<Runnable>any(), Matchers.eq(1L), Matchers.eq(TimeUnit.DAYS));
        Mockito.verifyNoMoreInteractions(log, executor);
    }

    @Test
    public void testMultipleErrors() {
        Logger log = Mockito.mock(Logger.class);
        ScheduledExecutorService executor = Mockito.mock(ScheduledExecutorService.class);
        Duration seconds = Duration.seconds(30);
        RateLimitedLog rateLimitedLog =
                new DefaultRateLimitedLogFactory(executor, seconds)
                        .from(log);
        Mockito.verify(executor).scheduleWithFixedDelay(Matchers.<Runnable>any(), Matchers.eq(1L), Matchers.eq(1L), Matchers.eq(TimeUnit.MINUTES));
        Throwable t1 = new Throwable();
        Throwable t2 = new Throwable();
        Throwable t3 = new Throwable();

        rateLimitedLog.error(t1, "Test error: {}", "first!");
        rateLimitedLog.error(t2, "Test error: {}", "second!");
        rateLimitedLog.error(t3, "Test error: {}", "third!");

        // Check that the first error gets logged immediately.
        Mockito.verify(log).error("Test error: first!", t1);
        ArgumentCaptor<Runnable> captor1 = ArgumentCaptor.forClass(Runnable.class);
        Mockito.verify(executor).schedule(captor1.capture(), Matchers.eq(30L), Matchers.eq(TimeUnit.SECONDS));
        Mockito.verifyNoMoreInteractions(log, executor);
        Mockito.reset(executor);

        // Simulate the scheduled executor service running at the scheduled time after accumulating two more errors.
        captor1.getValue().run();

        Mockito.verify(log).error("Encountered {} {} within the last {}: {}", 2L, "errors", Duration.seconds(30), "Test error: third!", t3);
        ArgumentCaptor<Runnable> captor2 = ArgumentCaptor.forClass(Runnable.class);
        Mockito.verify(executor).schedule(captor2.capture(), Matchers.eq(30L), Matchers.eq(TimeUnit.SECONDS));
        Mockito.verifyNoMoreInteractions(log, executor);

        // Simulate the scheduled executor service running at the scheduled time, this time with no errors to report.
        captor2.getValue().run();

        Mockito.verifyNoMoreInteractions(log, executor);
    }

    @Test
    public void testDurationToString() {
        Assert.assertEquals("30 seconds", Duration.seconds(30).toString());
    }
}


text:
Icon Glyphs

140 icons in sprite form, available in dark gray (default) and white, provided by Glyphicons.

 icon-glass

 icon-music

 icon-search

 icon-envelope

 icon-heart

 icon-star

 icon-star-empty

 icon-user

Icon Autre planète

516 Beautiful web icons in png, svg, vector, CSS sprite and webfont formats, available for free at Autre planète.

 apico-atoms

 apico-printer

 apico-cloud-upload

 comment-user

 apico-magic

 apico-erase

 apico-airplane

 apico-book


text:
'use strict';

var appModule = angular.module('sample-app', [
        'ngRoute',
        'ngMaterial',
        'ngMap'

    ]);

// app.constant('appConst', {
//         PROJECT_MANAGER: 'Project Manager'
//     });

appModule.config(function($routeProvider, $locationProvider) {

    $locationProvider.hashPrefix('');
    $routeProvider
    .when("/", {
        templateUrl : "modules/home/home.html",
        controller: "homeCtrl"
    })
    .when("/login", {
        templateUrl : "modules/login/login.html",
        controller: "loginCtrl"
    })
    .when("/add-location", {
        templateUrl : "modules/add-location/add-location.html",
        controller: "addLocationCtrl"
    })
    .when("/participate", {
        templateUrl : "modules/participate/participate.html",
        controller: "participateCtrl"
    })

});


text:
dhtmlXTreeObject.prototype.getAllCheckedChildless = function () {
    var temp = this._getAllCheckedChildless("", "", 1);
    if (temp != "") temp += this.dlmtr;
    return temp;
};

dhtmlXTreeObject.prototype._getAllCheckedChildless = function (htmlNode, list, mode) {
    if (!htmlNode) htmlNode = this.htmlNode;
    if (htmlNode.checkstate == mode)
        if (!htmlNode.nocheckbox && htmlNode.childsCount == 0) { if (list) list += this.dlmtr + htmlNode.id; else list = htmlNode.id; }
    var j = htmlNode.childsCount;
    for (var i = 0; i < j; i++) {
        list = this._getAllCheckedChildless(htmlNode.childNodes[i], list, mode);
    };
    if (list) return list; else return "";
};


text:
package mysql

import (
	"database/sql/driver"
	"fmt"
	"io"
	"reflect"
	"strconv"
)

type mysqlStmt struct {
	mc         *mysqlConn
	id         uint32
	paramCount int
}

func (stmt *mysqlStmt) Close() error {
	if stmt.mc == nil || stmt.mc.closed.IsSet() {
		// driver.Stmt.Close can be called more than once, thus this function
		// has to be idempotent.
		// See also Issue #450 and golang/go#16019.
		//errLog.Print(ErrInvalidConn)
		return driver.ErrBadConn
	}

	err := stmt.mc.writeCommandPacketUint32(comStmtClose, stmt.id)
	stmt.mc = nil
	return err
}

func (stmt *mysqlStmt) NumInput() int {
	return stmt.paramCount
}

func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter {
	return converter{}
}

func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) {
	if stmt.mc.closed.IsSet() {
		errLog.Print(ErrInvalidConn)
		return nil, driver.ErrBadConn
	}
	// Send command
	err := stmt.writeExecutePacket(args)
	if err != nil {
		return nil, stmt.mc.markBadConn(err)
	}

	mc := stmt.mc

	mc.affectedRows = 0
	mc.insertId = 0

	// Read Result
	resLen, err := mc.readResultSetHeaderPacket()
	if err != nil {
		return nil, err
	}

	if resLen > 0 {
		// Columns
		if err = mc.readUntilEOF(); err != nil {
			return nil, err
		}

		// Rows
		if err := mc.readUntilEOF(); err != nil {
			return nil, err
		}
	}

	if err := mc.discardResults(); err != nil {
		return nil, err
	}

	return &mysqlResult{
		affectedRows: int64(mc.affectedRows),
		insertId:     int64(mc.insertId),
	}, nil
}

func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) {
	return stmt.query(args)
}

func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) {
	if stmt.mc.closed.IsSet() {
		errLog.Print(ErrInvalidConn)
		return nil, driver.ErrBadConn
	}
	// Send command
	err := stmt.writeExecutePacket(args)
	if err != nil {
		return nil, stmt.mc.markBadConn(err)
	}

	mc := stmt.mc

	// Read Result
	resLen, err := mc.readResultSetHeaderPacket()
	if err != nil {
		return nil, err
	}

	rows := new(binaryRows)

	if resLen > 0 {
		rows.mc = mc
		rows.rs.columns, err = mc.readColumns(resLen)
	} else {
		rows.rs.done = true

		switch err := rows.NextResultSet(); err {
		case nil, io.EOF:
			return rows, nil
		default:
			return nil, err
		}
	}

	return rows, err
}

type converter struct{}

func (c converter) ConvertValue(v interface{}) (driver.Value, error) {
	if driver.IsValue(v) {
		return v, nil
	}

	rv := reflect.ValueOf(v)
	switch rv.Kind() {
	case reflect.Ptr:
		// indirect pointers
		if rv.IsNil() {
			return nil, nil
		}
		return c.ConvertValue(rv.Elem().Interface())
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return rv.Int(), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
		return int64(rv.Uint()), nil
	case reflect.Uint64:
		u64 := rv.Uint()
		if u64 >= 1<<63 {
			return strconv.FormatUint(u64, 10), nil
		}
		return int64(u64), nil
	case reflect.Float32, reflect.Float64:
		return rv.Float(), nil
	}
	return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind())
}


text:
typedef struct {
  v3d_t pos;
  GLfloat color[4];
  GLfloat size;
} celestial_body;

class OrbitSky {
public:
  OrbitSky();
  ~OrbitSky();

  void setOrbit(Galaxy &galaxy, size_t planetHandle);

  void draw(GlCamera &cam, v3d_t playerPosition);

  vector<celestial_body> mBodies;
};


text:
"""
// ==========================================================================
// www.Bacon-Strip.com
// Luis Alonso
// Creative Commons 2017
// Bacon-Strip Node ID Block are: 0x0012a940 - 0x0012aa3f
// Registered for Bacon-Strip [Luis Alonso]
//
// ==========================================================================

////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Produces the dependency graph node "baconRig".
// This plug-in is part of a rigging package known as The "Bacon-Strip"
//
// ID:
// 0x0012a940
//
////////////////////////////////////////////////////////////////////////
"""

import math, sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx

kPluginNodeTypeName = "baconRig"
baconRigId = OpenMaya.MTypeId(0x0012a940)

class baconRig(OpenMayaMPx.MPxNode):

    rigName = OpenMaya.MObject()
    rigType = OpenMaya.MObject()
    pickerName = OpenMaya.MObject()
    baconBits = OpenMaya.MObject()
    lodMeshes = OpenMaya.MObject()

    def __init__(self):
        OpenMayaMPx.MPxNode.__init__(self)

    def compute(self, plug, dataBlock):
        # INPUTS
        rootDagHandle = dataBlock.inputValue(self.rootDag)

def nodeCreator():
    return OpenMayaMPx.asMPxPtr( baconRig() )

def nodeInitializer():
    self = baconRig

    # Name
    rigNameAttr = OpenMaya.MFnTypedAttribute()
    rigNameAttrStr = OpenMaya.MFnStringData().create("Bacon01")
    self.rigName = rigNameAttr.create("rigName", "rn", OpenMaya.MFnStringData.kString, rigNameAttrStr)
    rigNameAttr.setStorable(True)
    rigNameAttr.setKeyable(False)
    self.addAttribute( self.rigName )

    # Rig Type
    rigTypeAttr = OpenMaya.MFnEnumAttribute()
    self.rigType = rigTypeAttr.create("rigType", "rt", 0)
    rigTypeAttr.addField("Custom", 0)
    rigTypeAttr.addField("BipedAnatomical", 1)
    rigTypeAttr.addField("BipedCartoon", 2)
    rigTypeAttr.addField("Quadruped", 3)
    rigTypeAttr.setHidden(False)
    rigTypeAttr.setKeyable(False)
    rigTypeAttr.setDefault(1)
    self.addAttribute( self.rigType )

    # Picker Name
    pickerNameAttr = OpenMaya.MFnTypedAttribute()
    pickerNameAttrStr = OpenMaya.MFnStringData().create("Generic")
    self.pickerName = pickerNameAttr.create("pickerName", "pn", OpenMaya.MFnStringData.kString, pickerNameAttrStr)
    pickerNameAttr.setStorable(True)
    pickerNameAttr.setKeyable(False)
    self.addAttribute( self.pickerName )

    # Bacon Bits
    baconBitsAttr = OpenMaya.MFnMessageAttribute()
    self.baconBits = baconBitsAttr.create("baconBits", "bb")
    baconBitsAttr.setArray(True)
    baconBitsAttr.setStorable(True)
    baconBitsAttr.setKeyable(True)
    self.addAttribute( self.baconBits )

    # LOD Meshes
    typeAttr = OpenMaya.MFnTypedAttribute()
    lodMeshesAttr = OpenMaya.MFnCompoundAttribute()
    self.lodMeshes = lodMeshesAttr.create("LOD", "LOD")
    lodMeshesAttr.setArray(True)
    lodMeshesAttr.setKeyable(True)
    dagNodePlug = typeAttr.create('meshes', 'meshes', OpenMaya.MFnData.kString)
    typeAttr.setArray(True)
    lodMeshesAttr.addChild(dagNodePlug)
    lodMeshesAttr.setHidden(False)
    self.addAttribute( self.lodMeshes)

# initialize the script plug-in
def initializePlugin(mobject):
    mplugin = OpenMayaMPx.MFnPlugin(mobject)
    try:
        mplugin.registerNode( kPluginNodeTypeName, baconRigId, nodeCreator, nodeInitializer )
    except:
        sys.stderr.write( "Failed to register node: %s" % kPluginNodeTypeName )
        raise

# uninitialize the script plug-in
def uninitializePlugin(mobject):
    mplugin = OpenMayaMPx.MFnPlugin(mobject)
    try:
        mplugin.deregisterNode( baconRigId )
    except:
        sys.stderr.write( "Failed to deregister node: %s" % kPluginNodeTypeName )
        raise


text:
import * as Path from "path";

export { Path };
export * from "./File";


text:
package io.github.m0pt0pmatt.spongesurvivalgames.sponsor;

import org.bukkit.entity.EntityType;
import org.bukkit.potion.PotionEffectType;

import java.util.*;

public final class Sponsors {

    private static final Map<String, Sponsor> sponsors = new TreeMap<>();

    static {
        sponsors.put("restore-health", new RestoreHealthSponsor());
        sponsors.put("restore-hunger", new RestoreHungerSponsor());
        sponsors.put("light-armor", new OpenInventorySponsor(Collections.singletonList(SponsorItems.LIGHTARMOR)));
        sponsors.put("medium-armor", new OpenInventorySponsor(Collections.singletonList(SponsorItems.MEDIUMARMOR)));
        sponsors.put("light-sword", new OpenInventorySponsor(Collections.singletonList(SponsorItems.LIGHTSWORD)));
        sponsors.put("medium-sword", new OpenInventorySponsor(Collections.singletonList(SponsorItems.MEDIUMSWORD)));
        sponsors.put("bow", new OpenInventorySponsor(Collections.singletonList(SponsorItems.BOW)));
        sponsors.put("health-potion", new OpenInventorySponsor(Collections.singletonList(SponsorItems.HEALTHPOTION)));
        sponsors.put("poison-potion", new OpenInventorySponsor(Collections.singletonList(SponsorItems.POISONPOTION)));
        sponsors.put("food", new OpenInventorySponsor(Collections.singletonList(SponsorItems.FOOD1)));
        sponsors.put("food2", new OpenInventorySponsor(Collections.singletonList(SponsorItems.FOOD2)));
        sponsors.put("food3", new OpenInventorySponsor(Collections.singletonList(SponsorItems.FOOD3)));
        sponsors.put("clear-status-effects", new ClearStatusEffectSponsor());
        sponsors.put("wither", new StatusEffectSponsor(PotionEffectType.WITHER, 100, 1));
        sponsors.put("blindness", new StatusEffectSponsor(PotionEffectType.BLINDNESS, 200, 1));
        sponsors.put("poison1", new StatusEffectSponsor(PotionEffectType.POISON, 100, 1));
        sponsors.put("poison2", new StatusEffectSponsor(PotionEffectType.POISON, 100, 2));
        sponsors.put("nausea", new StatusEffectSponsor(PotionEffectType.CONFUSION, 400, 1));
        sponsors.put("spawn-zombies", new SpawnEntitySponsor(EntityType.ZOMBIE, 10));
        sponsors.put("spawn-skeletons", new SpawnEntitySponsor(EntityType.SKELETON, 10));
        sponsors.put("spawn-creepers", new SpawnEntitySponsor(EntityType.CREEPER, 3));
    }

    public static Optional<Sponsor> get(String name) {
        Sponsor sponsor = sponsors.get(name);
        return sponsor == null ? Optional.empty() : Optional.of(sponsor);
    }

    public static Set<String> listAll() {
        return sponsors.keySet();
    }
}


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'

import { connect } from 'react-redux'
import { Redirect } from 'react-router'
import { NavLink, Route } from 'react-router-dom'
import { fetchModelRuns, fetchSosModels, fetchSectorModels, fetchScenarios } from 'actions/actions.js'

import { setAppFormKeepEditing } from 'actions/actions.js'
import { setAppFormSave } from 'actions/actions.js'
import { setAppFormDiscard } from 'actions/actions.js'
import { setAppNavigate } from 'actions/actions.js'
import { setAppNavigateDone } from 'actions/actions.js'

import { FaHome, FaTasks, FaSlidersH, FaSitemap, FaCode, FaChartBar } from 'react-icons/fa'

import { ConfirmPopup } from 'components/ConfigForm/General/Popups.js'
import Footer from 'containers/Footer'
import history from '../history.js'

const Badge = (props) => (
    <span className={`badge badge-${props.color}`}>{props.children}
)

Badge.propTypes = {
    color: PropTypes.string,
    children: PropTypes.node
}

class Nav extends Component {
    constructor(props) {
        super(props)
        this.init = true
    }

    componentDidMount() {
        const { dispatch } = this.props

        dispatch(fetchModelRuns())
        dispatch(fetchSosModels())
        dispatch(fetchSectorModels())
        dispatch(fetchScenarios())
    }

    renderLoading() {
        return (

                        <NavLink exact className="nav-link" to="/">
                            <FaHome size={20}/>
                            Home
                        </NavLink>

                    Loading...

        )
    }

    renderError() {
        return (

                        <NavLink exact className="nav-link" to="/">
                            <FaHome size={20}/>
                            Home
                        </NavLink>

                    Error

        )
    }

    renderNav(model_runs, sos_models, sector_models, scenarios) {
        var job_status = ['unstarted', 'running', 'stopped', 'done', 'failed']
        const pathname = this.props.location.pathname
        const { dispatch } = this.props

        return (

 dispatch(setAppNavigate('/'))}>
                            <FaHome size={20}/>
                            Home

                    Simulation

 dispatch(setAppNavigate('/jobs/'))}>
                            <FaTasks size={20}/>
                                Jobs
                            <Badge color="secondary">{model_runs.length}</Badge>

                        <Route path="/jobs/" render={() =>

                                {job_status.map(status =>

 dispatch(setAppNavigate('/jobs/status=' + status))}>
                                            {status}

                                )}

                        }/>

 dispatch(setAppNavigate('/configure/model-runs'))}>
                            <FaSlidersH size={20}/>
                                Model Runs
                            <Badge color="secondary">{model_runs.length}</Badge>

                        <Route path="/configure/model-runs/" render={() =>

                                {model_runs.map(model_run =>

 dispatch(setAppNavigate('/configure/model-runs/' + model_run.name))}>
                                            {model_run.name}

                                )}

                        }/>

                    Configuration

 dispatch(setAppNavigate('/configure/sos-models'))}>
                            <FaSitemap size={20}/>
                                System-of-Systems Models
                            <Badge color="secondary">{sos_models.length}</Badge>

                        <Route path="/configure/sos-models/" render={() =>

                                {sos_models.map(sos_model =>

 dispatch(setAppNavigate('/configure/sos-models/' + sos_model.name))}>
                                            {sos_model.name}

                                )}

                        }/>

 dispatch(setAppNavigate('/configure/sector-models'))}>
                            <FaCode size={20}/>
                                Model Wrappers
                            <Badge color="secondary">{sector_models.length}</Badge>

                        <Route path="/configure/sector-models/" render={() =>

                                {sector_models.map(sector_model =>

 dispatch(setAppNavigate('/configure/sector-models/' + sector_model.name))}>
                                            {sector_model.name}

                                )}

                        }/>

 dispatch(setAppNavigate('/configure/scenarios'))}>
                            <FaChartBar size={20}/>
                                Scenarios
                            <Badge color="secondary">{scenarios.length}</Badge>

                        <Route path="/configure/scenarios/" render={() =>

                                {scenarios.map(scenario =>

 dispatch(setAppNavigate('/configure/scenarios/' + scenario.name))}>
                                            {scenario.name}

                                )}

                        }/>

                <ConfirmPopup
                    onRequestOpen={this.props.app.formEdit && this.props.app.formReqCancel && !this.props.app.formSaving}
                    onSave={() => dispatch(setAppFormSave())}
                    onConfirm={() => dispatch(setAppFormDiscard())}
                    onCancel={() => dispatch(setAppFormKeepEditing())}
                />

        )
    }

    render() {
        const {model_runs, sos_models, sector_models, scenarios, isFetching} = this.props

        if (this.props.app.redirect != '' &&
            this.props.location.pathname == this.props.app.redirect) {
            this.props.dispatch(setAppNavigateDone())
        }

        if (this.props.app.redirect != '' &&
            this.props.location.pathname != this.props.app.redirect &&
            this.props.app.formEdit == false &&
            this.props.app.formError == false &&
            this.props.app.formSaving == false) {

            history.push(this.props.app.redirect)
            return (

                    <Redirect to={this.props.app.redirect} />

            )
        }
        else if (isFetching && this.init) {
            return this.renderLoading()
        } else {
            this.init = false
            return this.renderNav(model_runs, sos_models, sector_models, scenarios)
        }
    }
}

Nav.propTypes = {
    app: PropTypes.object.isRequired,
    model_runs: PropTypes.array.isRequired,
    sos_models: PropTypes.array.isRequired,
    sector_models: PropTypes.array.isRequired,
    scenarios: PropTypes.array.isRequired,
    isFetching: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired,
    location: PropTypes.object.isRequired
}

function mapStateToProps(state) {
    const { model_runs, sos_models, sector_models, scenarios } = state
    return {
        app: state.app,
        model_runs: model_runs.items,
        sos_models: sos_models.items,
        sector_models: sector_models.items,
        scenarios: scenarios.items,

        isFetching: (
            state.model_runs.isFetching ||
            state.sos_models.isFetching ||
            state.sector_models.isFetching ||
            state.scenarios.isFetching
        )
    }
}

export default connect(mapStateToProps)(Nav)


text:
/**
*************************************************************
* @file stump.cpp
* @brief Breve descripción
* Another logging tool for our C++ projects
*
*
* @author Gaspar Fernández <blakeyed@totaki.com>
* @version
* @date 12 abr 2014
* Changelog:
*  - 20160519 : Disable individual logs
*  - 20140918 : Enable and disable logs
*  - 20141105 : Prevent logging empty strings
*  - 20141118 : finished stream operator to log with <<
*               comments cleanup
*  - 20141120 : fixed bug that mixes streams output when inserting many
*               streams from several threads at a time.
*  - 20141121 : fixed bug that aborts or segfaults when writing with streams
*               from several threads. New ostreamDataMutex.
*
* To-do:
*  - Clear one sigle output
*  - Clear_buffer must check if the buffers are not being used
*  - Clear_buffers must free buffers
*  - Clear one single user
*
*************************************************************/

#include "stump.h"
#include <iostream>
#include <pthread.h>
#include <ctime>

// Default settings
#define _LOG_FORMAT "%time% (%type%) : %message%"
#define _DATE_FORMAT "%d/%m/%Y %H:%M:%S"
#define _REPEAT_LOG_FORMAT "%time% - %timelast% (%type%) : %message% x%times%times."
#define _BUFFER_SIZE 20

unsigned Stump::bufferId = 0;

Stump::Stump()
{
  _internalMessages=true;
  workingMessageType="";
  __MUTEX_INIT(ostreamMutex);
  __MUTEX_INIT(ostreamDataMutex);
  streamBufferMax = 1024;
  streamBufferCropMsg = "[CROPPED]";
  // __MUTEX_INIT(writingMutex);
  initialize();
}

Stump::~Stump()
{
  for (std::map<std::string, std::vector<MessageOutput*> >::iterator i=messageTypes.begin(); i!=messageTypes.end(); ++i)
    {
      for (std::vector<MessageOutput*>::iterator j = i->second.begin(); j != i->second.end(); ++j)
	{
	  outputBuffer(**j, true);
	  delete *j;
	}
      // To-do: delete pending structures
    }
  internalMessage("Destroying...");
}

void Stump::internalMessages(bool enable)
{
  this->_internalMessages = enable;
}

void Stump::internalMessage(std::string msg)
{
  if (!_internalMessages)
    return;

  std::cerr << "[STUMP] "<<msg<<std::endl;
}

void Stump::clearBuffers()
{
  availableBuffers.clear();
}

void Stump::disableAll()
{
  for (std::map<std::string, std::vector<MessageOutput*> >::iterator i = messageTypes.begin(); i != messageTypes.end(); ++i)
    {
      for (std::vector<MessageOutput*>::iterator j = i->second.begin(); j != i->second.end(); ++j)
	(*j)->enabled=false;
    }
}

void Stump::enableAll()
{
  for (std::map<std::string, std::vector<MessageOutput*> >::iterator i = messageTypes.begin(); i != messageTypes.end(); ++i)
    {
      for (std::vector<MessageOutput*>::iterator j = i->second.begin(); j != i->second.end(); ++j)
	(*j)->enabled=true;
    }
}

void Stump::disable(std::string messageType)
{
  std::map<std::string, std::vector<MessageOutput*> >::iterator l = messageTypes.find(messageType);
  if (l == messageTypes.end())
    return;

  for (std::vector<MessageOutput*>::iterator j = l->second.begin(); j != l->second.end(); ++j)
    {
      (*j)->enabled=false;
    }
}

void Stump::enable(std::string messageType)
{
  std::map<std::string, std::vector<MessageOutput*> >::iterator l = messageTypes.find(messageType);
  if (l == messageTypes.end())
    return;

  for (std::vector<MessageOutput*>::iterator j = l->second.begin(); j != l->second.end(); ++j)
    {
      (*j)->enabled=true;
    }
}

void Stump::setStatus(std::string messageType, bool enabled)
{
  if (enabled)
    enable(messageType);
  else
    disable(messageType);
}

Stump::MessageBuffer *Stump::createBuffer(std::ostream &os, int bufferSize)
{
  MessageBuffer *buffer = new  MessageBuffer(os, bufferSize);
  // Buscar buffers repetidos
  availableBuffers.push_back(buffer);

  return buffer;
}

Stump::MessageBuffer *Stump::createBuffer(std::ostream &os, std::string bufferName, int bufferSize)
{
  MessageBuffer *buffer = new  MessageBuffer(os, bufferName, bufferSize);
  availableBuffers.push_back(buffer);

  return buffer;
}

Stump::MessageBuffer *Stump::createBuffer(std::string file, int bufferSize)
{
  MessageBuffer *buffer = new  MessageBuffer(file, bufferSize);
  availableBuffers.push_back(buffer);

  return buffer;
}

Stump::MessageBuffer *Stump::createBuffer(std::string file, std::string bufferName, int bufferSize)
{
  MessageBuffer *buffer = new  MessageBuffer(file, bufferName, bufferSize);
  availableBuffers.push_back(buffer);

  return buffer;
}

// FALTAN FUNCIONES PARA MODIFICAR PARAMETROS DE UNA SALIDA
// COLORES PARA CONSOLA
// ESCRIBIR EN ARCHIVO
void Stump::addOutput(std::string messageType, std::string typeLabel, MessageFormat messageFormat, int bufferSize)
{
  addOutput(messageType, typeLabel, messageFormat, bufferSize);
}

void Stump::addOutput(std::string messageType, std::string typeLabel, MessageFormat messageFormat, std::string bufferName)
{
  MessageBuffer *buffer = findMessageBuffer(bufferName);
  if (buffer==NULL)
    this->internalMessage("Could not find buffer "+bufferName);
  else
    addOutput(messageType, typeLabel, messageFormat, 0, buffer);
}

void Stump::clearOutputs()
{
  messageTypes.clear();
}

void Stump::addOutput(std::string messageType, std::string typeLabel, MessageFormat messageFormat, int bufferSize, MessageBuffer* buffer)
{
  if (buffer==NULL)
    {
      internalMessage("buffer can't be null");
      return;
    }

  messageTypes[messageType].push_back(new MessageOutput(// output,
							typeLabel,
							messageFormat,
							// file,
							// cbt1,
							buffer)
				      );
  if (defaultMessageType=="")
    defaultMessageType=messageType;
}

void Stump::initialize()
{
  this->defaultLogFormat = _LOG_FORMAT;
  this->defaultDateFormat = _DATE_FORMAT;
  this->defaultRepeatLogFormat = _REPEAT_LOG_FORMAT;
  this->defaultBufferSize = _BUFFER_SIZE;

  MessageBuffer *buf = createBuffer(std::cout, "logBuffer", 2);
  MessageBuffer *buf2 = createBuffer("mylog.txt", "fichero", 2);

  addOutput("info", "Information",
	    MessageFormat(this),
	    "logBuffer"
	    );
  addOutput("info", "Info",
	    MessageFormat(this),
	    "fichero"
	    );
  addOutput("warning", "Warning",
	    MessageFormat(this),
	    "logBuffer"
	    );
  addOutput("error", "Error",
	    MessageFormat(this),
	    "logBuffer"
	    );
  addOutput("fatal", "Fatal Error",
	    MessageFormat(this),
	    "logBuffer"
	    );
  addOutput("other", "Other Error",
	    MessageFormat(this),
	    "logBuffer"
	    );
}

void Stump::log(std :: string msg, std::string logType)
{
  if (!msg.length())
    return;

  if (logType=="")
    logType=this->defaultMessageType;

  if (messageTypes.size() == 0)
	return;

  std::map<std::string, std::vector<MessageOutput*> >::iterator mtype = messageTypes.find(logType);
  if (mtype==messageTypes.end())
    {
      this->internalMessage("No message types found");
      return;
    }

  time_t time = std::time(NULL);
  for (std::vector<MessageOutput*>::iterator i = mtype->second.begin(); i != mtype->second.end(); ++i)
    {
      this->logString(msg, **i, time);
    }
}

std::string Stump::getFormattedDate(std::string dateFormat, time_t time)
{
  char timeBuffer[300];
  if (std::strftime(timeBuffer, sizeof(timeBuffer), dateFormat.c_str(), std::localtime(&time)))
    return std::string (timeBuffer);

  internalMessage("date couldn't be written");
  return "DATE-ERROR";
}

std::string Stump::getFormattedMessage(std::string msg, time_t time, std::string typeLabel, std::string logFormat, std::string dateFormat, std::map<std::string,std::string> extra)
{
  std::map<std::string,std::string>strMap = extra;
  strMap["%time%"] = getFormattedDate(dateFormat, time);
  strMap["%type%"] = typeLabel;
  strMap["%message%"] = msg;

  return strReplaceMap(logFormat, strMap);
}

void Stump::logString(std :: string msg, MessageOutput &output, time_t time)
{
  if (!output.enabled)
    return;

  __MUTEX_LOCK(output.buffer->mutex);

  if ( (output.messageFormat.repeatLogFormat != "") && (output.buffer->lastMessage==msg) )
    {
      std::map<std::string,std::string> repeatData;
      repeatData["%times%"] = itoa(++output.buffer->lastRepeat);
      repeatData["%timelast%"] = getFormattedDate(output.messageFormat.dateFormat, output.buffer->lastDate);
      output.buffer->buffer.pop_back();
      // Let's do something with repeating messages!
      output.buffer->buffer.push_back(getFormattedMessage(msg,
							  time,
							  output.typeLabel,
							  output.messageFormat.repeatLogFormat,
							  output.messageFormat.dateFormat,
							  repeatData));
    }
  else
    {
      // if (output.buffer.size() < output.bufferSize)
      output.buffer->lastDate = time;
      output.buffer->lastRepeat = 1;
      output.buffer->buffer.push_back(getFormattedMessage(msg,
							  time,
							  output.typeLabel,
							  output.messageFormat.logFormat,
							  output.messageFormat.dateFormat));
      output.buffer->lastMessage=msg;
      outputBuffer(output);
    }
  __MUTEX_UNLOCK(output.buffer->mutex);

}

std::string Stump::strReplaceMap(std::string source, std::map<std::string,std::string>strMap, int offset, int times)
{
  int total = 0;
  std::string::size_type pos=offset;
  std::string::size_type newPos;
  std::string::size_type lowerPos;

  do
    {
      std::string rep;
      for (std::map<std::string, std::string>::iterator i=strMap.begin(); i!=strMap.end(); ++i)
	{
	  std::string fromStr = i->first;

	  newPos = source.find(fromStr, pos);
	  if ( (i==strMap.begin()) || (newPos<lowerPos) )
	    {
	      rep = fromStr;
	      lowerPos = newPos;
	    }
	}

      pos = lowerPos;
      if (pos == std::string::npos)
	break;

      std::string toStr = strMap[rep];

      source.replace(pos, rep.length(), toStr);
      pos+=toStr.size();

    } while ( (times==0) || (++total<times) );

  return source;
}

void Stump::outputBuffer(MessageOutput &output, bool flush)
{
  if ( (output.buffer->buffer.size()>=output.buffer->bufferSize) || (flush) )
    {
      switch (output.buffer->output)
	{
	case OSTREAM:
	  outputBufferOStream(output.buffer->ost, output.buffer);
	  break;
	case FILE:
	  outputBufferFile(output.buffer);
	  break;
	}

      // buffers debug
      // for (unsigned i=0; i<output.buffer->buffer.size(); ++i)
      // 	{
      // 	  std::cout << output.buffer->buffer[i] << std::endl;
      // 	}
      output.buffer->buffer.clear();
      output.buffer->lastMessage="";	// Avoid log repeating after flush
    }
}

void Stump::outputBufferOStream(std::ostream &os, const Stump::MessageBuffer *output)
{
  for (unsigned i=0; i<output->buffer.size(); ++i)
    {
      os << output->buffer[i] << std::endl;
    }

}

void Stump::outputBufferFile(const Stump::MessageBuffer *output)
{
  std::fstream f;
  f.open(output->file.c_str(), std::fstream::out | std::fstream::app);
  if (!f.is_open())
    {
      internalMessage("Cannot open file "+output->file);
      return;
    }
  outputBufferOStream(f, output);
  f.close();
}

Stump::MessageBuffer* Stump::findMessageBuffer(std::string bufferName)
{
  for (std::vector<MessageBuffer*>::iterator i=availableBuffers.begin(); i!=availableBuffers.end(); ++i)
    {
      if ((*i)->bufferName == bufferName)
	return (*i);
    }
  return NULL;
}

Stump::MessageBuffer* Stump::findMessageBuffer(unsigned bufferId)
{
  for (std::vector<MessageBuffer*>::iterator i=availableBuffers.begin(); i!=availableBuffers.end(); ++i)
    {
      if ((*i)->bufferId == bufferId)
	return (*i);
    }
  return NULL;
}

std::string Stump::itoa(int val)
{
  std::string out;

  for (; val ; val /= 10)
    out = "0123456789"[val % 10] + out;

  return out;
}


text:
#pragma once

namespace kuro
{

/*!
 * \brief Enum containing the possible build modes for contract assertions.
 * \details Passed as part of contract_violation_info to the current contract violation handler.
 */
enum class contract_assertion_mode
{
    opt,
    test,
    safe
};

/*!
 * \brief Struct containing info for a contract violation.
 * \details Passed to the contract violation handler.
 */
struct contract_violation_info
{
    //! The assertion mode of the contract violation.
    contract_assertion_mode mode;
    //! The source text of the expression that caused the contract violation.
    const char* expression_test;
    //! The filename containing the source code that caused the contract violation.
    const char* filename;
    //! The number of the line the contract violation occurred on.
    unsigned long line_number;
};

//! Type of a contract violation handler.
using contract_violation_handler = void (*)(contract_violation_info const& info);

//! Return the current contract violation handler or nullptr if none was set and the default handler is used.
contract_violation_handler get_contract_violation_handler() noexcept;

//! Set the contract violation handler and return the previous one or nullptr of the previous one is the default handler.
contract_violation_handler set_contract_violation_handler(contract_violation_handler handler) noexcept;

//! Handle the contract violation. Calls the current violation handler.
void handle_contract_violation(const contract_violation_info& info);

//! Some extensions not defined in N4253
inline namespace ext
{
class scoped_contract_violation_handler
{
public:
    explicit scoped_contract_violation_handler(contract_violation_handler handler) noexcept;
    ~scoped_contract_violation_handler() noexcept;

private:
    contract_violation_handler savedHandler_;
};
}  // namespace ext

//! Implementation details required in the header.
namespace detail
{

//! Set the status of the unit test macros. \c true means a contract violation occured.
void set_contract_assert_unit_test_status(bool status) noexcept;

//! Get the status of the unit test macros.
bool get_contract_assert_unit_test_status() noexcept;

//! Contract violation handler for use in the unit test pass macro. Calls \c set_contract_assert_unit_test_status(true).
void contract_assert_unit_test_handler(const contract_violation_info&);

//! Contract violation handler for use in the unit test fail opt macro Calls \c set_contract_assert_unit_test_status(true) if the contraction violation ocurred in opt mode.
void contract_assert_unit_test_opt_handler(const contract_violation_info& info);

//! Contract violation handler for use in the unit test fail opt macro Calls \c set_contract_assert_unit_test_status(true) if the contraction violation ocurred in test mode.
void contract_assert_unit_test_test_handler(const contract_violation_info& info);

//! Contract violation handler for use in the unit test fail opt macro Calls \c set_contract_assert_unit_test_status(true) if the contraction violation ocurred in safe mode.
void contract_assert_unit_test_safe_handler(const contract_violation_info& info);

}  // namespace detail

}  // namespace kuro

// Here be macros

//! Test that the given expression does not cause a contract violation.
#define kuro_contract_assert_pass(exp)                                                                     \
    [&]() {                                                                                \
        kuro::detail::set_contract_assert_unit_test_status(false);                                         \
        kuro::ext::scoped_contract_violation_handler h_{&kuro::detail::contract_assert_unit_test_handler}; \
        (exp);                                                                                \
        return !kuro::detail::get_contract_assert_unit_test_status();                                      \
    }()

//! Mode none constant.
#define KURO_ASSERT_MODE_NONE 0
//! Mode opt constant.
#define KURO_ASSERT_MODE_OPT 1
//! Mode test constant.
#define KURO_ASSERT_MODE_TEST 2
//! Mode safe constant.
#define KURO_ASSERT_MODE_SAFE 3

#ifndef KURO_ASSERT_ASSERTION_MODE
//! The current assetion mode.
#define KURO_ASSERT_ASSERTION_MODE KURO_ASSERT_MODE_TEST
#endif

#if KURO_ASSERT_ASSERTION_MODE >= KURO_ASSERT_MODE_OPT
//! Assert a contract if the assetion mode is opt or higher
#define kuro_contract_assert_opt(exp)                                                                    \
    if(!(exp))                                                                                \
    {                                                                                \
        kuro::handle_contract_violation({kuro::contract_assertion_mode::opt, #exp, __FILE__, __LINE__}); \
    }

//! Test that the given expression causes a contract violation in opt mode.
#define kuro_contract_assert_fail_opt(exp)                                                                     \
    [&]() {                                                                                \
        kuro::detail::set_contract_assert_unit_test_status(false);                                             \
        kuro::ext::scoped_contract_violation_handler h_{&kuro::detail::contract_assert_unit_test_opt_handler}; \
        (exp);                                                                                \
        return kuro::detail::get_contract_assert_unit_test_status();                                           \
    }()
#else
#define kuro_contract_assert_opt(exp) (void)0
#define kuro_contract_assert_fail_opt(exp) true
#endif

#if KURO_ASSERT_ASSERTION_MODE >= KURO_ASSERT_MODE_TEST
//! Assert a contract if the assetion mode is test or higher
#define kuro_contract_assert_test(exp)                                                                    \
    if(!(exp))                                                                                \
    {                                                                                \
        kuro::handle_contract_violation({kuro::contract_assertion_mode::test, #exp, __FILE__, __LINE__}); \
    }

//! Test that the given expression causes a contract violation in test mode.
#define kuro_contract_assert_fail_test(exp)                                                                     \
    [&]() {                                                                                \
        kuro::detail::set_contract_assert_unit_test_status(false);                                              \
        kuro::ext::scoped_contract_violation_handler h_{&kuro::detail::contract_assert_unit_test_test_handler}; \
        (exp);                                                                                \
        return kuro::detail::get_contract_assert_unit_test_status();                                            \
    }()
#else
#define kuro_contract_assert_test(exp) (void)0
#define kuro_contract_assert_fail_test(exp) true
#endif

#define kuro_contract_assert(exp) kuro_contract_assert_test(exp)
#define kuro_contract_assert_fail(exp) kuro_contract_assert_fail_test(exp)

#if KURO_ASSERT_ASSERTION_MODE >= KURO_ASSERT_MODE_SAFE
//! Assert a contract if the assetion mode is safe
#define kuro_contract_assert_safe(exp)                                                                    \
    if(!(exp))                                                                                \
    {                                                                                \
        kuro::handle_contract_violation({kuro::contract_assertion_mode::safe, #exp, __FILE__, __LINE__}); \
    }

//! Test that the given expression causes a contract violation in test mode.
#define kuro_contract_assert_fail_safe(exp)                                                                     \
    [&]() {                                                                                \
        kuro::detail::set_contract_assert_unit_test_status(false);                                              \
        kuro::ext::scoped_contract_violation_handler h_{&kuro::detail::contract_assert_unit_test_safe_handler}; \
        (exp);                                                                                \
        return kuro::detail::get_contract_assert_unit_test_status();                                            \
    }()
#else
#define kuro_contract_assert_safe(exp) (void)0
#define kuro_contract_assert_fail_safe(exp) true
#endif