Main function called by Node-RED
330123
function DocumentDBDatabase(config) {
        // Store node for further use
        node = this;
        var nodeConfig = config;

        // Create the Node-RED node
        RED.nodes.createNode(this, config);
        dbendpoint = node.credentials.endpoint;
        dbkey = node.credentials.authkey;

        this.on('input', function (msg) {
            client = new DocumentDBClient(dbendpoint, { "masterKey": dbkey });
            var messageJSON = null;
            if (typeof (msg.payload) != "string") {
                node.log("JSON");
                messageJSON = msg.payload;
            } else {
                node.log("String");
                //Converting string to JSON Object
                //Sample string: {"dbname": "name", "action": "C"}
                messageJSON = JSON.parse(msg.payload);
            }
            var action = messageJSON.action;
            if  (action != "L")
            {
                dbName = messageJSON.dbname;
                databaseUrl = `dbs/${dbName}`;
            }
            // Sending action to Azure DocumentDB
            setStatus(statusEnum.sending);
            switch (action) {
                case "C":
                    node.log('Trying to create database');
                    getDatabase().then((resolve) => { 
                        node.log('Completed successfully: -> ' + JSON.stringify(resolve));
                        setStatus(statusEnum.sent);
                        node.send(messageJSON.dbname); 
                    }).catch((error) => { 
                        setStatus(statusEnum.error);
                        node.error('Completed with error ' +JSON.stringify(error), msg);
                        node.log('Completed with error ' +JSON.stringify(error));
                    });
                    break;
                case "L":
                    node.log('Trying to list databases');
                    var listNames = [];
                    listDatabases(function (dbs) {
                        setStatus(statusEnum.sent);
                        if (dbs.length == 1) {
                            node.send(dbs[0].id)
                        } else {
                            for (var i = 0; i < dbs.length; i++) {
                                listNames.push(dbs[i].id);
                            }
                            node.send(JSON.stringify(listNames));
                        }
                    });
                    break;
                case "D":
                    node.log('Trying to delete database');
                    deleteDatabase().then((resolve) => { 
                        setStatus(statusEnum.sent);
                        node.log('Delete successfully: -> ' + JSON.stringify(resolve));
                     }).catch((error) => { 
                        setStatus(statusEnum.error);
                        node.error('Completed with error ' +JSON.stringify(error), msg);
                        node.log('Completed with error ' +JSON.stringify(error));
                    });
                    break;
                default:
                    node.log('action was not detected');
                    node.error('action was not detected', msg);
                    setStatus(statusEnum.error);
                    break;
            }
        });

        this.on('close', function () {
            disconnectFrom(this);
        });
    }
657668
function main() {
    var TIME_STEP_MS = 20;
    var frameCount = sozi.presentation.frames.length;
    var imageIndex = 0;

    document.querySelector(".sozi-blank-screen").style.display = "none";
    
    sozi.presentation.frames.forEach(function (currentFrame, currentFrameIndex) {
        console.log("Exporting frame: " + (currentFrameIndex + 1));

        sozi.player.jumpToFrame(currentFrameIndex);

        // Generate images for the duration of the current frame
        for (var timeMs = 0; timeMs < currentFrame.timeoutMs; timeMs += TIME_STEP_MS, imageIndex ++) {
            window.callPhantom(imageIndex);
        }

        // Generate images for the transition to the next frame.
        // If the last frame has a timeout enabled, transition to the first frame.
        if (currentFrameIndex < frameCount - 1 || currentFrame.timeoutEnable) {
            if (typeof sozi.player.nextFrameIndex === "number") {
                sozi.player.targetFrameIndex = sozi.player.nextFrameIndex; // Sozi < 18
            }
            else {
                sozi.player.targetFrame = sozi.player.nextFrame; // Sozi 18
            }

            sozi.viewport.cameras.forEach(function (camera) {
                var lp = sozi.player.targetFrame.layerProperties[camera.layer.index];
                sozi.player.setupTransition(camera, sozi.Timing[lp.transitionTimingFunction], lp.transitionRelativeZoom, lp.transitionPath, false);
            });

            for (timeMs = 0; timeMs < sozi.player.targetFrame.transitionDurationMs; timeMs += TIME_STEP_MS, imageIndex ++) {
                sozi.player.onAnimatorStep(timeMs / sozi.player.targetFrame.transitionDurationMs);
                window.callPhantom(imageIndex);
            }
        }
    });
}
155224
function main(content, callback) {
  parser(content, function(error, result) {
    if (error) {
      callback(error);
    } else {
      callback(null, result);
    }
  });
}
79422
function (node) {

    // Search first caller in chain.
    // Ex.:
    //
    // Models <- Identifier
    //   .User
    //   .find()
    //   .exec(function () {
    //   // function body
    // });
    //
    // Looks for 'Models'
    var calleeNode = node.parent; // FunctionExpression
    while (calleeNode.parent &&
           calleeNode.parent.type === 'CallExpression') {
      calleeNode = calleeNode.parent;
    }

    var indent;

    if (calleeNode.parent &&
        (calleeNode.parent.type === 'Property' ||
         calleeNode.parent.type === 'ArrayExpression')) {
      // If function is part of array or object, comma can be put at left
      indent = getNodeIndent(calleeNode, false, true);
    } else {
      // If function is standalone, simple calculate indent
      indent = getNodeIndent(calleeNode);
    }

    indent += indentSize;
    // If function content is not empty
    if (node.body.length > 0) {
      // Calculate left shift position don't require strict indent
      // allow function body allign to (indentSize * X)
      while (getNodeIndent(node.body[0]) > indent) {
        indent += indentSize;
      }
    }

    checkNodesIndent(node.body, indent);

    checkLastNodeLineIndent(node, indent - indentSize);
  }
1188129
function main() {
    this.prior = this.current;
    this.current = this.current.apply(this, arguments) || this.current;
    // Call user transition function, if defined
    if (this.transition) {
        this.transition.apply(this, arguments);
    }
}
651031
function main(onStart) {
    const conf = config.read();

    initLogging(conf);
    initFsStorage(conf);

    logger.debug('Default configuration file: %s', conf.path);
    logger.debug('Configuration parameters: %s', JSON.stringify(conf));

    runWebServer(conf, onStart);
}
553309
def main():
    
    args = parser.parse_args()
    try:
        function = args.func
    except AttributeError:
        parser.print_usage()
        parser.exit(1)
    function(vars(args))
1082074
def main():
    """"""
    util.create_dir(os.path.join(CONF_DIR, "templates"))
    util.create_dir(os.path.join(CONF_DIR, "colorschemes/light/"))
    util.create_dir(os.path.join(CONF_DIR, "colorschemes/dark/"))

    util.setup_logging()
    parser = get_args()

    parse_args_exit(parser)
    parse_args(parser)
201609
function main() {
    const options = queryOptions();
    switch (options.porting) {
        case 'build':
            runBuild(options)
            .catch((reason) => {
                console.error(reason);
                process.exit(1);
            });
            break;
        case 'arrange':
            runArrange(options);
            break;
        case 'rebase':
            runRebase(options);
            break;
        case 'clean':
            runClean(options);
            break;
    }
}
1034731
async function main() {
  // Initialize the application.
  process.title = 'Which.js';

  // Parse the command line arguments.
  program.name('which')
    .description('Find the instances of an executable in the system path.')
    .version(packageVersion, '-v, --version')
    .option('-a, --all', 'list all instances of executables found (instead of just the first one)')
    .option('-s, --silent', 'silence the output, just return the exit code (0 if any executable is found, otherwise 1)')
    .arguments('<command>').action(command => program.executable = command)
    .parse(process.argv);

  if (!program.executable) {
    program.outputHelp();
    process.exitCode = 64;
    return;
  }

  // Run the program.
  let executables = await which(program.executable, {all: program.all});
  if (!program.silent) {
    if (!Array.isArray(executables)) executables = [executables];
    for (const path of executables) console.log(path);
  }
}
497079
function (aNode, sourceBuffer, owner) {

        // output main if
        var ifDirective = aNode.directives['if']; // eslint-disable-line dot-notation
        sourceBuffer.addRaw('if (' + compileExprSource.expr(ifDirective.value) + ') {');
        sourceBuffer.addRaw(
            aNodeCompiler.compile(
                aNode.ifRinsed,
                sourceBuffer,
                owner
            )
        );
        sourceBuffer.addRaw('}');

        // output elif and else
        each(aNode.elses, function (elseANode) {
            var elifDirective = elseANode.directives.elif;
            if (elifDirective) {
                sourceBuffer.addRaw('else if (' + compileExprSource.expr(elifDirective.value) + ') {');
            }
            else {
                sourceBuffer.addRaw('else {');
            }

            sourceBuffer.addRaw(
                aNodeCompiler.compile(
                    elseANode,
                    sourceBuffer,
                    owner
                )
            );
            sourceBuffer.addRaw('}');
        });
    }
1051171
function main() {
  var uri = url.parse(process.env.REDISCLOUD_URL || '');
  var store = process.env.REDISCLOUD_URL && new RedisStore({
    host: uri.hostname,
    port: +uri.port,
    ttl: 365*24*60*60,
    pass: uri.auth && uri.auth.split(':')[1]
  });

  var app = express();
  app.engine('jade', jade.__express);
  app.use(bodyParser.urlencoded())
  app.use(bodyParser.json())
  app.use(session({name: 'gn', secret: 'gonogo', store: store}));
  app.use('/res', express.static(__dirname + '/public'));
  app.use(passport.initialize());
  app.use(passport.session());

  passport.serializeUser(function (user, done) {
    if (!user) return done();
    return done(null, JSON.stringify(user));
  });

  passport.deserializeUser(function (data, done) { return done(null, JSON.parse(data)); });
  passport.use(new GoogleStrategy({
    clientID: process.env.GAPI_KEY, 
    clientSecret: process.env.GAPI_SECRET, 
    callbackURL: process.env.GAPI_CB_URL
  }, function (accessToken, refreshToken, profile, done) {
    return done(null, {profile: profile, accessToken: accessToken, refreshToken: refreshToken});
  }));

  var scope = {scope: 'https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/googletalk email'};
  scope.accessType =  'offline';
  app.get('/auth/google', passport.authenticate('google', scope));
  app.get('/auth/google/cb', passport.authenticate('google', {failureRedirect: '/'}), authed);
  app.get('/logout', function (req, res) { req.logout(); res.redirect('/'); });
  app.get(/.*/, render);
  app.set('views', __dirname + '/views');
  var server = app.listen(+(process.env.PORT || 4444), function () {
    console.log('Listening on', server.address().port);
  });
}
111772
function run(options, callback) {
  var settings = {}
  var stdin = new PassThrough()
  var tree
  var detectConfig
  var hasConfig
  var detectIgnore
  var hasIgnore

  try {
    stdin = process.stdin
  } catch (error) {
    /* Obscure bug in Node (seen on windows):
     * - https://github.com/nodejs/node/blob/f856234/lib/internal/
     *   process/stdio.js#L82;
     * - https://github.com/AtomLinter/linter-markdown/pull/85.
     */
  }

  if (!callback) {
    throw new Error('Missing `callback`')
  }

  if (!options || !options.processor) {
    return next(new Error('Missing `processor`'))
  }

  /* Processor. */
  settings.processor = options.processor

  /* Path to run as. */
  settings.cwd = options.cwd || process.cwd()

  /* Input. */
  settings.files = options.files || []
  settings.extensions = (options.extensions || []).map(extension)

  settings.filePath = options.filePath || null
  settings.streamIn = options.streamIn || stdin

  /* Output. */
  settings.streamOut = options.streamOut || process.stdout
  settings.streamError = options.streamError || process.stderr
  settings.alwaysStringify = options.alwaysStringify
  settings.output = options.output
  settings.out = options.out

  /* Null overwrites config settings, `undefined` doesn’t. */
  if (settings.output === null || settings.output === undefined) {
    settings.output = undefined
  }

  if (settings.output && settings.out) {
    return next(new Error('Cannot accept both `output` and `out`'))
  }

  /* Process phase management. */
  tree = options.tree || false

  settings.treeIn = options.treeIn
  settings.treeOut = options.treeOut
  settings.inspect = options.inspect

  if (settings.treeIn === null || settings.treeIn === undefined) {
    settings.treeIn = tree
  }

  if (settings.treeOut === null || settings.treeOut === undefined) {
    settings.treeOut = tree
  }

  /* Configuration. */
  detectConfig = options.detectConfig
  hasConfig = Boolean(options.rcName || options.packageField)

  if (detectConfig && !hasConfig) {
    return next(
      new Error('Missing `rcName` or `packageField` with `detectConfig`')
    )
  }

  settings.detectConfig =
    detectConfig === null || detectConfig === undefined
      ? hasConfig
      : detectConfig
  settings.rcName = options.rcName || null
  settings.rcPath = options.rcPath || null
  settings.packageField = options.packageField || null
  settings.settings = options.settings || {}
  settings.configTransform = options.configTransform
  settings.defaultConfig = options.defaultConfig

  /* Ignore. */
  detectIgnore = options.detectIgnore
  hasIgnore = Boolean(options.ignoreName)

  settings.detectIgnore =
    detectIgnore === null || detectIgnore === undefined
      ? hasIgnore
      : detectIgnore
  settings.ignoreName = options.ignoreName || null
  settings.ignorePath = options.ignorePath || null
  settings.silentlyIgnore = Boolean(options.silentlyIgnore)

  if (detectIgnore && !hasIgnore) {
    return next(new Error('Missing `ignoreName` with `detectIgnore`'))
  }

  /* Plug-ins. */
  settings.pluginPrefix = options.pluginPrefix || null
  settings.plugins = options.plugins || {}

  /* Reporting. */
  settings.reporter = options.reporter || null
  settings.reporterOptions = options.reporterOptions || null
  settings.color = options.color || false
  settings.silent = options.silent || false
  settings.quiet = options.quiet || false
  settings.frail = options.frail || false

  /* Process. */
  fileSetPipeline.run({files: options.files || []}, settings, next)

  function next(error, context) {
    var stats = statistics((context || {}).files)
    var failed = Boolean(
      settings.frail ? stats.fatal || stats.warn : stats.fatal
    )

    if (error) {
      callback(error)
    } else {
      callback(null, failed ? 1 : 0, context)
    }
  }
}
925411
async def main():
    
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)
    tasks = []

    # Get the node summary infos by dedicated method (with json schema validation)
    print("\nCall bma.node.summary:")
    task = asyncio.ensure_future(client(bma.node.summary))
    tasks.append(task)

    # Get the money parameters located in the first block
    print("\nCall bma.blockchain.parameters:")
    task = asyncio.ensure_future(client(bma.blockchain.parameters))
    tasks.append(task)

    responses = await asyncio.gather(*tasks)
    # you now have all response bodies in this variable
    print("\nResponses:")
    print(responses)

    # Close client aiohttp session
    await client.close()
303863
function start(callback) {

  let {arc} = readArc()
  let close = x=> !x

  // if .arc has events and we're not clobbering with ARC_LOCAL flag
  if (arc.events || arc.queues) {
    // start a little web server
    let server = http.createServer(function listener(req, res) {
      let body = ''
      req.on('data', chunk => {
        body += chunk.toString()
      })
      req.on('end', () => {
        let message = JSON.parse(body)
        if (req.url === '/queues') {
          message.arcType = 'queue'
        } else if (req.url === '/events' || req.url === '/') {
          message.arcType = 'event'
        } else {
          res.statusCode = 404
          res.end('not found')
          console.log(chalk.red.dim('event bus 404 for URL ' + req.url))
          return
        }
        console.log(chalk.grey.dim('@' + message.arcType), chalk.green.dim(JSON.stringify(JSON.parse(body), null, 2)))
        // spawn a fork of the node process
        let subprocess = fork(path.join(__dirname, '_subprocess.js'))
        subprocess.send(message)
        subprocess.on('message', function _message(msg) {
          console.log(chalk.grey.dim(msg.text))
        })
        res.statusCode = 200
        res.end('ok')
      })
    })
    // ends our little web server
    close = function _closer() {
      try {
        server.close()
      }
      catch(e) {
        console.log('swallowing server.close error in sandbox events', e)
      }
    }
    // start listening on 3334
    server.listen(3334, callback ? callback: x=>!x)
  }
  else {
    callback()
  }
  return {close}
}
547916
def main(self):
        
        self.loop = urwid.MainLoop(self.top, self.palettes[self.palette_names[0]], screen=self.tui,
                                   handle_mouse=False, input_filter=self.handle_keys,
                                   unhandled_input=self.unhandled)
        self.loop.run()
204985
function main() {
	var project = parseSource( errBuf );

	if ( project && writeDictionary( project, errBuf ) ) {
		console.log( 'localization database correctly built' );
	} // if

	if ( errBuf.length ) {
		commons.outputErrors( errBuf, console.error );
		process.exit( 1 );
	} // if

	process.exit( 0 );
}