Helper function for testing demo routines
427219
def section(title, bar=OVERLINE, strm=sys.stdout):
    
    width = utils.term.width
    printy(bold(title.center(width)))
    printy(bold((bar * width)[:width]))
520338
function(results, options) {
         failuresOnly = option('failuresOnly')
         print(color("\n Passes: ", 'bold') + color(results.stats.passes, 'green') + 
               color(" Failures: ", 'bold') + color(results.stats.failures, 'red') +
               color(" Duration: ", 'bold') + color(results.duration, 'green') + " ms \n")
              
         function indent(string) {
           return string.replace(/^(.)/gm, '  $1')
         }
         
         each(results.allSuites, function(suite) {
           var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran
            if (displaySuite && suite.hasSpecs()) {
              print(color(' ' + suite.description, 'bold'))
              each(suite.specs, function(spec){
                var assertionsGraph = inject(spec.assertions, '', function(graph, assertion){
                  return graph + color('.', assertion.passed ? 'green' : 'red')
                })
                if (spec.requiresImplementation())
                  print(color('  ' + spec.description, 'blue') + assertionsGraph)
                else if (spec.passed() && !failuresOnly)
                  print(color('  ' + spec.description, 'green') + assertionsGraph)
                else if (!spec.passed())
                  print(color('  ' + spec.description, 'red') + assertionsGraph + 
                        "\n" + indent(map(spec.failures(), function(a){ return a.message }).join("\n")) + "\n")
              })
              print("")
            }
         })
         
         quit(results.stats.failures)
       }
126818
function showHelp(){
  var jshint_proc = fork(require.resolve('jshint/bin/jshint'), ['-h'], {silent: true});
  var ts = through(function write(chunk){
    this.queue(chunk.toString().replace(/(jshint)\b/g, 'jsxhint'));
  }, function end() {
    // This feels like a hack. There might be a better way to do this.
    this.queue('\nThe above options are native to JSHint, which JSXHint extends.\n');
    this.queue('\x1b[1m'); // bold
    this.queue('\nJSXHint Options:\n');
    this.queue('\x1b[0m');
    this.queue('      --jsx-only         Only transform files with the .jsx extension.\n' +
               '                         Will run somewhat faster.\n');
    this.queue('      --babel            Use babel (6to5) instead of react esprima.\n' +
               '                         Useful if you are using es6-module, etc. You must \n' +
               '                         install the module `babel` manually with npm.\n');
    this.queue('      --babel-experimental  Use babel with experimental support for ES7.\n' +
               '                            Useful if you are using es7-async, etc.\n');
    this.queue('      --harmony          Use react esprima with ES6 transformation support.\n' +
               '                         Useful if you are using both es6-class and react.\n');
    this.queue('      --es6module             Pass the --es6module flag to react tools.\n');
    this.queue('      --non-strict-es6module  Pass this flag to react tools.\n');
    this.queue('      --transform-errors STRING   Whether to fail on transform errors.\n' +
               '                                  Valid: always, jsx, never (default: jsx)');
  });
  jshint_proc.stderr.pipe(ts).pipe(process.stderr);
}
746203
function debug(name) {
  function disabled(){}
  disabled.enabled = false;

  var match = skips.some(function(re){
    return re.test(name);
  });

  if (match) return disabled;

  match = names.some(function(re){
    return re.test(name);
  });

  if (!match) return disabled;
  var c = color();

  function colored(fmt) {
    fmt = coerce(fmt);

    var curr = new Date;
    var ms = curr - (prev[name] || curr);
    prev[name] = curr;

    fmt = '  \u001b[9' + c + 'm' + name + ' '
      + '\u001b[3' + c + 'm\u001b[90m'
      + fmt + '\u001b[3' + c + 'm'
      + ' +' + humanize(ms) + '\u001b[0m';

    console.error.apply(this, arguments);
  }

  function plain(fmt) {
    fmt = coerce(fmt);

    fmt = new Date().toUTCString()
      + ' ' + name + ' ' + fmt;
    console.error.apply(this, arguments);
  }

  colored.enabled = plain.enabled = true;

  return isatty || process.env.DEBUG_COLORS
    ? colored
    : plain;
}
357145
def main():
    ''

    logging.basicConfig()

    type_choices = {'any': constants.PACKAGE_ANY,
                    'extension': constants.PACKAGE_EXTENSION,
                    'theme': constants.PACKAGE_THEME,
                    'dictionary': constants.PACKAGE_DICTIONARY,
                    'languagepack': constants.PACKAGE_LANGPACK,
                    'search': constants.PACKAGE_SEARCHPROV,
                    'multi': constants.PACKAGE_MULTI}

    # Parse the arguments that
    parser = argparse.ArgumentParser(
        description='Run tests on a Mozilla-type addon.')

    parser.add_argument('package',
                        help="The path of the package you're testing")
    parser.add_argument('-t',
                        '--type',
                        default='any',
                        choices=type_choices.keys(),
                        help="Type of addon you assume you're testing",
                        required=False)
    parser.add_argument('-o',
                        '--output',
                        default='text',
                        choices=('text', 'json'),
                        help='The output format that you expect',
                        required=False)
    parser.add_argument('-v',
                        '--verbose',
                        action='store_const',
                        const=True,
                        help="""If the output format supports it, makes
                        the analysis summary include extra info.""")
    parser.add_argument('--boring',
                        action='store_const',
                        const=True,
                        help="""Activating this flag will remove color
                        support from the terminal.""")
    parser.add_argument('--determined',
                        action='store_const',
                        const=True,
                        help="""This flag will continue running tests in
                        successive tests even if a lower tier fails.""")
    parser.add_argument('--selfhosted',
                        action='store_const',
                        const=True,
                        help="""Indicates that the addon will not be
                        hosted on addons.mozilla.org. This allows the
                        <em:updateURL> element to be set.""")
    parser.add_argument('--approved_applications',
                        help="""A JSON file containing acceptable applications
                        and their versions""",
                        required=False)
    parser.add_argument('--target-maxversion',
                        help="""JSON string to override the package's
                        targetapp_maxVersion for validation. The JSON object
                        should be a dict of versions keyed by application
                        GUID. For example, setting a package's max Firefox
                        version to 5.*:
                        {"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}": "5.*"}
                        """)
    parser.add_argument('--target-minversion',
                        help="""JSON string to override the package's
                        targetapp_minVersion for validation. The JSON object
                        should be a dict of versions keyed by application
                        GUID. For example, setting a package's min Firefox
                        version to 5.*:
                        {"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}": "5.*"}
                        """)
    parser.add_argument('--for-appversions',
                        help="""JSON string to run validation tests for
                        compatibility with a specific app/version. The JSON
                        object should be a dict of version lists keyed by
                        application GUID. For example, running Firefox 6.*
                        compatibility tests:
                        {"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}": ["6.*"]}
                        """)
    parser.add_argument('--timeout',
                        help='The amount of time before validation is '
                             'terminated with a timeout exception.',
                        default='60')

    args = parser.parse_args()

    # We want to make sure that the output is expected. Parse out the expected
    # type for the add-on and pass it in for validation.
    if args.type not in type_choices:
        # Fail if the user provided invalid input.
        print 'Given expectation (%s) not valid. See --help for details' % \
                args.type
        sys.exit(1)

    overrides = {}
    if args.target_minversion:
        overrides['targetapp_minVersion'] = json.loads(args.target_minversion)
    if args.target_maxversion:
        overrides['targetapp_maxVersion'] = json.loads(args.target_maxversion)

    for_appversions = None
    if args.for_appversions:
        for_appversions = json.loads(args.for_appversions)

    try:
        timeout = int(args.timeout)
    except ValueError:
        print 'Invalid timeout. Integer expected.'
        sys.exit(1)

    expectation = type_choices[args.type]
    error_bundle = validate(args.package,
                            format=None,
                            approved_applications=args.approved_applications,
                            determined=args.determined,
                            listed=not args.selfhosted,
                            overrides=overrides,
                            for_appversions=for_appversions,
                            expectation=expectation,
                            timeout=timeout)

    # Print the output of the tests based on the requested format.
    if args.output == 'text':
        print error_bundle.print_summary(verbose=args.verbose,
                                         no_color=args.boring).encode('utf-8')
    elif args.output == 'json':
        sys.stdout.write(error_bundle.render_json())

    if error_bundle.failed():
        sys.exit(1)
    else:
        sys.exit(0)
1356243
function assertThrows(test) {
    var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error;
    var contains = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];


    if (!Array.isArray(contains)) contains = [contains];

    var shouldErrorName = typeof error === 'string' ? error : error.name;

    var nonThrown = new Error('util.assertThrowsAsync(): Missing rejection' + (error ? ' with ' + error.name : ''));
    var ensureErrorMatches = function ensureErrorMatches(error) {
        // wrong type
        if (error.constructor.name != shouldErrorName) {
            return new Error('\n             util.assertThrowsAsync(): Wrong Error-type\n             - is    : ' + error.constructor.name + '\n             - should: ' + shouldErrorName + '\n             - error: ' + error.toString() + '\n             ');
        }
        // check if contains
        var errorString = error.toString();
        if (contains.length > 0 && (0, _utils.oneOfArrayNotInString)(contains, errorString)) {
            return new Error('\n               util.assertThrowsAsync(): Error does not contain\n               - should contain: ' + contains + '\n               - is string: ' + error.toString() + '\n             ');
        }
        return false;
    };

    return new Promise(function (res, rej) {
        var val = void 0;
        try {
            val = test();
        } catch (err) {
            var wrong = ensureErrorMatches(err);
            if (wrong) rej(wrong);else res(err);
            return;
        }
        if ((0, _isPromise2['default'])(val)) {
            val.then(function () {
                // has not thrown
                rej(nonThrown);
            })['catch'](function (err) {
                var wrong = ensureErrorMatches(err);
                if (wrong) rej(wrong);else res(err);
            });
        } else rej(nonThrown);
    });
}
26152
function checkCompile (dir) {
  return function  (mode, callback) {
    var exercise = this

    if (!exercise.passed)
      return callback(null, true) // shortcut if we've already had a failure

    gyp.rebuild(dir, function (err) {
      if (err) {
        exercise.emit('fail', err.message)
        return callback(null, false)
      }

      callback(null, true)
    })
  }
}
1120041
def main(cl_args=None):
    

    if cl_args is None and len(sys.argv) > 1:
        cl_args = sys.argv[1:]
    args = options.parse_args(cl_args)

    print("-------------------------------------------------------------------")
    print("                      __   _____   ___   ____    _ __     ")
    print("                     / /  /  _/ | / / | / / /__ (_) /_    ")
    print("                    / /___/ / | |/ /| |/ /  '_// / __/    ")
    print("                   /____/___/ |___/ |___/_/\_\/_/\__/     ")
    print("")
    print("                   Land Ice Verification & Validation     ")
    print("-------------------------------------------------------------------")
    print("")
    print("  Current run: " + livvkit.timestamp)
    print("  User: " + livvkit.user)
    print("  OS Type: " + livvkit.os_type)
    print("  Machine: " + livvkit.machine)
    print("  " + livvkit.comment)

    from livvkit.components import numerics
    from livvkit.components import verification
    from livvkit.components import performance
    from livvkit.components import validation
    from livvkit import scheduler
    from livvkit.util import functions
    from livvkit.util import elements

    summary_elements = []

    if livvkit.verify or livvkit.validate:
        functions.setup_output()

    if livvkit.verify:
        summary_elements.append(scheduler.run("numerics", numerics,
                                              functions.read_json(livvkit.numerics_model_config)))
        summary_elements.append(scheduler.run("verification", verification,
                                              functions.read_json(livvkit.verification_model_config)))
        summary_elements.append(scheduler.run("performance", performance,
                                              functions.read_json(livvkit.performance_model_config)))
    if livvkit.validate:
        print(" -----------------------------------------------------------------")
        print("   Beginning the validation test suite ")
        print(" -----------------------------------------------------------------")
        print("")
        validation_config = {}
        for conf in livvkit.validation_model_configs:
            validation_config = functions.merge_dicts(validation_config,
                                                      functions.read_json(conf))
        summary_elements.extend(scheduler.run_quiet(validation, validation_config,
                                                    group=False))
        print(" -----------------------------------------------------------------")
        print("   Validation test suite complete ")
        print(" -----------------------------------------------------------------")
        print("")

    if livvkit.verify or livvkit.validate:
        result = elements.page("Summary", "", element_list=summary_elements)
        functions.write_json(result, livvkit.output_dir, "index.json")
        print("-------------------------------------------------------------------")
        print(" Done!  Results can be seen in a web browser at:")
        print("  " + os.path.join(livvkit.output_dir, 'index.html'))
        print("-------------------------------------------------------------------")

    if args.serve:
        try:
            # Python 3
            import http.server as server
            import socketserver as socket
        except ImportError:
            # Python 2
            # noinspection PyPep8Naming
            import SimpleHTTPServer as server
            # noinspection PyPep8Naming
            import SocketServer as socket

        httpd = socket.TCPServer(('', args.serve), server.SimpleHTTPRequestHandler)

        sa = httpd.socket.getsockname()
        print('\nServing HTTP on {host} port {port} (http://{host}:{port}/)'.format(host=sa[0], port=sa[1]))
        print('\nView the generated website by navigating to:')
        print('\n    http://{host}:{port}/{path}/index.html'.format(host=sa[0], port=sa[1],
                                                                    path=os.path.relpath(livvkit.output_dir)
                                                                    ))
        print('\nExit by pressing `ctrl+c` to send a keyboard interrupt.\n')
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print('\nKeyboard interrupt received, exiting.\n')
            sys.exit(0)
550053
function helpCli() {
	console.log('');
	console.log('usage: node <script> [--version] [--help] <command> [<args>]');
	console.log('usage with demo: node demo/index.js [--version] [--help] <command> [<args>]');
	console.log('');
	console.log('node-mock-server commands:');
	console.log('    --version            print node-mock-server version');
	console.log('    swagger-import       run a swagger import');
	console.log('    validate             run a validation for all mock data');
	console.log('    collections          lists all available collections');
	console.log('    collections <id>     activate collection');
	console.log('');
}
659286
function showHelp(specifiedScripts) {
    if (parsedArgv.help) {
      // if --help was specified, then yargs will show the default help
      log.info(help(psConfig))
      return true
    }
    const helpStyle = String(psConfig.options['help-style'])
    const hasDefaultScript = Boolean(psConfig.scripts.default)
    const noScriptSpecifiedAndNoDefault =
      !specifiedScripts.length && !hasDefaultScript
    const hasHelpScript = Boolean(psConfig.scripts.help)
    const commandIsHelp =
      isEqual(specifiedScripts[0], 'help') && !hasHelpScript
    const shouldShowSpecificScriptHelp =
      commandIsHelp && specifiedScripts.length > 1
    if (shouldShowSpecificScriptHelp) {
      log.info(specificHelpScript(psConfig, specifiedScripts[1]))
      return true
    } else if (commandIsHelp || noScriptSpecifiedAndNoDefault) {
      // Can't achieve 100% branch coverage without refactoring this showHelp()
      // function into ./index.js and re-working existing tests and such. Branch
      // options aren't relevant here either, so telling Istanbul to ignore.
      /* istanbul ignore next */
      if (helpStyle === 'all') {
        parser.showHelp('log')
      }
      log.info(help(psConfig))
      return true
    }

    return false
  }
24657
def main():
    
    try:
        demo()
    except dialog.error, exc_instance:
        sys.stderr.write("Error:\n\n%s\n" % exc_instance.complete_message())
        sys.exit(1)
        
    sys.exit(0)
568851
function check(result, test) {

  const CHECKERS = [ _checkExitCode, _checkOutput, _checkStdout, _checkStderr ];
  var errors = [];

  CHECKERS.forEach(function (checker) {
    var error = checker(result, test);
    if (error) {
      errors.push(error);
    }
  });
  
  return errors;
}
1294924
def demo():
    """"""
    A = poisson((100, 100), format='csr')  # 2D FD Poisson problem
    B = None                               # no near-null spaces guesses for SA
    b = sp.rand(A.shape[0], 1)          # a random right-hand side

    # use AMG based on Smoothed Aggregation (SA) and display info
    mls = smoothed_aggregation_solver(A, B=B)
    print(mls)

    # Solve Ax=b with no acceleration ('standalone' solver)
    standalone_residuals = []
    x = mls.solve(b, tol=1e-10, accel=None, residuals=standalone_residuals)

    # Solve Ax=b with Conjugate Gradient (AMG as a preconditioner to CG)
    accelerated_residuals = []
    x = mls.solve(b, tol=1e-10, accel='cg', residuals=accelerated_residuals)
    del x

    # Compute relative residuals
    standalone_residuals = \
        np.array(standalone_residuals) / standalone_residuals[0]
    accelerated_residuals = \
        np.array(accelerated_residuals) / accelerated_residuals[0]

    # Compute (geometric) convergence factors
    factor1 = standalone_residuals[-1]**(1.0/len(standalone_residuals))
    factor2 = accelerated_residuals[-1]**(1.0/len(accelerated_residuals))

    print("                     MG convergence factor: %g" % (factor1))
    print("MG with CG acceleration convergence factor: %g" % (factor2))

    # Plot convergence history
    try:
        import matplotlib.pyplot as plt
        plt.figure()
        plt.title('Convergence History')
        plt.xlabel('Iteration')
        plt.ylabel('Relative Residual')
        plt.semilogy(standalone_residuals, label='Standalone',
                     linestyle='-', marker='o')
        plt.semilogy(accelerated_residuals, label='Accelerated',
                     linestyle='-', marker='s')
        plt.legend()
        plt.show()
    except ImportError:
        print("\n\nNote: pylab not available on your system.")
942346
function checkJs (mode, callback) {
  var exercise = this

  if (!exercise.passed)
    return callback(null, true) // shortcut if we've already had a failure

  gyp.rebuild(copyFauxTempDir, function (err) {
    if (err) {
      exercise.emit('fail', 'Compile mock C++ to test JavaScript: ' + err.message)
      return callback(null, false)
    }

    childProcess.exec(
          '"'
        + process.execPath
        + '" "'
        + copyFauxTempDir
        + '" "FAUX"'
      , function (err, stdout, stderr) {
          if (err) {
            process.stderr.write(stderr)
            process.stdout.write(stdout)
            return callback(err)
          }

          var pass = stdout.toString().replace('\r', '') == 'FAUX\n'
          if (!pass) {
            process.stderr.write(stderr)
            process.stdout.write(stdout)
          }
          exercise.emit(pass ? 'pass' : 'fail', 'JavaScript code loads addon and invokes `print(str)` method')

          callback(null, pass)
        }
    )
  })
}
481898
def run_demo():
    
    module_dir = dirname(dirname(os.path.realpath(__file__)))
    demo_file = os.path.join(module_dir, 'examples/data/exp.txt')

    if not os.path.isfile(demo_file):
        sys.stderr.write("demo input file not found!\n")
        sys.stderr.write("run the downloaddata.sh script in the example first\n")
        sys.exit(1)

    # plotting a histogram
    print("plotting a basic histogram")
    print("plot_hist('%s')" % demo_file)
    print("hist -f %s" % demo_file)
    print("cat %s | hist" % demo_file)
    plot_hist(demo_file)
    print("*" * 80)

    # with colours
    print("histogram with colours")
    print("plot_hist('%s', colour='blue')" % demo_file)
    print("hist -f %s -c blue" % demo_file)
    plot_hist(demo_file, colour='blue')
    print("*" * 80)

    # changing the shape of the point
    print("changing the shape of the bars")
    print("plot_hist('%s', pch='.')" % demo_file)
    print("hist -f %s -p ." % demo_file)
    plot_hist(demo_file, pch='.')
    print("*" * 80)

    # changing the size of the plot
    print("changing the size of the plot")
    print("plot_hist('%s', height=35.0, bincount=40)" % demo_file)
    print("hist -f %s -s 35.0 -b 40" % demo_file)
    plot_hist(demo_file, height=35.0, bincount=40)
39598
def validate():
    """"""

    errors = dict()
    for test in (test_architecture,
                 test_pyqt_availability,
                 test_pyblish_availability,
                 test_qtconf_availability,
                 test_qtconf_correctness,
                 test_qt_availability):
        try:
            test()
        except Exception as e:
            errors[test] = e

    if not errors:
        print("=" * 78)
        print()
        print(""" - Success!

{exe} is well suited to run Pyblish QML""".format(exe=sys.executable))
        print()
        print("=" * 78)

        return True

    print("=" * 78)
    print()
    print(" - Failed")
    print()
    for test, error in errors.iteritems():
        print(test.__name__)
        print("    %s" % error)
    print()
    print("=" * 78)

    return False
159135
function demoPlay(){
    Object.keys(KMMotorOneUSBSerial.motors).forEach((key)=>{
        cmdTest(KMMotorOneUSBSerial.motors[key]);
    });
}