Command line client for lightflow. A lightweight, high performance pipeline
    system for synchrotrons.

    Lightflow is being developed at the Australian Synchrotron.
336225
def cli(ctx, config, no_color):
    
    ctx.obj = {
        'show_color': not no_color if no_color is not None else True,
        'config_path': config
    }
261611
def pipeline_lightcurve(d, l1=0, m1=0, segments=[], scan=-1):
    

    if scan == -1: scan = d['scan']
    if segments == []: segments = range(d['nsegments'])

    d = set_pipeline(d['filename'], scan, fileroot=d['fileroot'], dmarr=[0], dtarr=[1], savenoise=False, timesub='', logfile=False, nsegments=d['nsegments'])

    # define memory and numpy arrays
    data_mem = mps.Array(mps.ctypes.c_float, datasize(d)*2)
    data_read_mem = mps.Array(mps.ctypes.c_float, datasize(d)*2)
    data_resamp_mem = mps.Array(mps.ctypes.c_float, datasize(d)*2)
    u_read_mem = mps.Array(mps.ctypes.c_float, d['nbl'])
    u_mem = mps.Array(mps.ctypes.c_float, d['nbl'])
    v_read_mem = mps.Array(mps.ctypes.c_float, d['nbl'])
    v_mem = mps.Array(mps.ctypes.c_float, d['nbl'])
    w_read_mem = mps.Array(mps.ctypes.c_float, d['nbl'])
    w_mem = mps.Array(mps.ctypes.c_float, d['nbl'])
    data_read = numpyview(data_read_mem, 'complex64', datashape(d)) # optional
    u_read = numpyview(u_read_mem, 'float32', d['nbl'], raw=False)
    v_read = numpyview(v_read_mem, 'float32', d['nbl'], raw=False)
    w_read = numpyview(w_read_mem, 'float32', d['nbl'], raw=False)
    lightcurve = n.zeros(shape=(d['nints'], d['nchan'], d['npol']), dtype='complex64')

    phasecenters = []
    with closing(mp.Pool(1, initializer=initread, initargs=(data_read_mem, u_read_mem, v_read_mem, w_read_mem, data_mem, u_mem, v_mem, w_mem))) as readpool:  
        for segment in segments:
            logger.info('Reading data...')
            readpool.apply(pipeline_dataprep, (d, segment))

            # get image peak for rephasing
            if not any([l1, m1]):
                im = sample_image(d, data_read, u_read, v_read, w_read, i=-1, verbose=1, imager='xy')
                l2, m2 = calc_lm(d, im)
            else:
                l2 = l1
                m2 = m1

            logger.info('Rephasing data to (l, m)=(%.4f, %.4f).' % (l2, m2))
            rtlib.phaseshift_threaded(data_read, d, l2, m2, u_read, v_read)
            phasecenters.append( (l2,m2) )

            nskip = (24*3600*(d['segmenttimes'][segment,0] - d['starttime_mjd'])/d['inttime']).astype(int)   # insure that lc is set as what is read
            lightcurve[nskip: nskip+d['readints']] = data_read.mean(axis=1)

    return phasecenters, lightcurve
662556
def cli(ctx, stage):
    """"""

    if not ctx.bubble:
        ctx.say_yellow('There is no bubble present, will not listen')
        raise click.Abort()

    SRC = None
    if stage in STAGES:
        try:
            SRC = ctx.cfg.CFG[stage].SOURCE
        except KeyError:
            pass

    if not SRC:
        ctx.say_red('There is no SOURCE in stage:' + stage)
        ctx.say_yellow('please check configuration in ' +
                       ctx.home + '/config/config.yaml')
        raise click.Abort()

    if 'SERVER' not in SRC:
        ctx.say_red('There is no SOURCE.SERVER in stage:' + stage)
        raise click.Abort()

    src_server = get_server(SRC.SERVER, ctx.home)

    # connect storage / pipeline to target via transform
    # write state listening on port etc into
    def message_handler(**m):
        print(str(arrow.now), str(m))
        return True, 'handled'

    try:
        # TODO: bg &
        # src_listening = src_server.listen(cfg=SRC,
        src_server.listen(cfg=SRC,
                          push_handler=message_handler,
                          pull_handler=message_handler)
    except Exception as e:
        ctx.say_red(
            'cannot listen from source client bubble.clients.' + SRC.SERVER)
        ctx.say_red(str(e))
        raise click.Abort('cannot listen')
1028120
function Flow(flowControlId) {
  Duplex.call(this, { objectMode: true });

  this._window = this._initialWindow = INITIAL_WINDOW_SIZE;
  this._flowControlId = flowControlId;
  this._queue = [];
  this._ended = false;
  this._received = 0;
  this._blocked = false;
}
722478
def dump_flows
      openflow_version = case @vsctl.openflow_version
                         when 1.0
                           :OpenFlow10
                         when 1.3
                           :OpenFlow13
                         else
                           raise "Unknown OpenFlow version: #{@vsctl.openflow_version}"
                         end
      sudo("ovs-ofctl dump-flows #{bridge} -O #{openflow_version}").
        split("\n").inject('') do |memo, each|
        memo + (/^(NXST|OFPST)_FLOW reply/ =~ each ? '' : each.lstrip + "\n")
      end
    end
1261197
def main():
    
    parser = argparse.ArgumentParser(
        description='A pipeline that generates analysis pipelines.')
    parser.add_argument('input', nargs='?',
                   help='A valid metapipe configuration file.')
    parser.add_argument('-o', '--output',
                   help='An output destination. If none is provided, the '
                   'results will be printed to stdout.',
                   default=sys.stdout)
    parser.add_argument('-t', '--temp',
                   help='A desired metapipe binary file. This is used to store '
                   'temp data between generation and execution. '
                   '(Default: "%(default)s")', default='.metapipe')
    parser.add_argument('-s', '--shell',
                   help='The path to the shell to be used when executing the '
                   'pipeline. (Default: "%(default)s)"',
                   default='/bin/bash')
    parser.add_argument('-r', '--run',
                   help='Run the pipeline as soon as it\'s ready.',
                   action='store_true')
    parser.add_argument('-n', '--name',
                   help='A name for the pipeline.',
                   default='')
    parser.add_argument('-j', '--job-type',
                   help='The destination for calculations (i.e. local, a PBS '
                   'queue on a cluster, etc).\nOptions: {}. '
                   '(Default: "%(default)s)"'.format(JOB_TYPES.keys()),
                   default='local')
    parser.add_argument('-p', '--max-jobs',
                   help='The maximum number of concurrent jobs allowed. '
                   'Defaults to maximum available cores.',
                   default=None)
    parser.add_argument('--report-type',
                   help='The output report type. By default metapipe will '
                   'print updates to the console. \nOptions: {}. '
                   '(Default: "%(default)s)"'.format(QUEUE_TYPES.keys()),
                   default='text')
    parser.add_argument('-v','--version',
                    help='Displays the current version of the application.',
                    action='store_true')
    args = parser.parse_args()

    if args.version:
        print('Version: {}'.format(__version__))
        sys.exit(0)

    try:
        with open(args.input) as f:
            config = f.read()
    except IOError:
        print('No valid config file found.')
        return -1

    run(config, args.max_jobs, args.output, args.job_type, args.report_type,
        args.shell, args.temp, args.run)
1081981
def configure_pipeline(p, dataset, model_dir, output_csv, output_bq_table):
  """"""

  data = _util.get_sources_from_dataset(p, dataset, 'predict')
  if len(dataset.schema) == 2:
    output_schema = [
        {'name': 'image_url', 'type': 'STRING'},
        {'name': 'target', 'type': 'STRING'},
        {'name': 'predicted', 'type': 'STRING'},
        {'name': 'target_prob', 'type': 'FLOAT'},
        {'name': 'predicted_prob', 'type': 'FLOAT'},
    ]
  else:
    output_schema = [
        {'name': 'image_url', 'type': 'STRING'},
        {'name': 'predicted', 'type': 'STRING'},
        {'name': 'predicted_prob', 'type': 'FLOAT'},
    ]
  results = (data |
             'Load Images' >> beam.ParDo(LoadImagesDoFn()) |
             'Batch Inputs' >> beam.ParDo(EmitAsBatchDoFn(20)) |
             'Batch Predict' >> beam.ParDo(PredictBatchDoFn(model_dir)) |
             'Unbatch' >> beam.ParDo(UnbatchDoFn()) |
             'Process Results' >> beam.ParDo(ProcessResultsDoFn()))

  if output_csv is not None:
    schema_file = output_csv + '.schema.json'
    results_save = (results |
                    'Prepare For Output' >> beam.ParDo(MakeCsvLineDoFn()) |
                    'Write Csv Results' >> beam.io.textio.WriteToText(output_csv,
                                                                      shard_name_template=''))
    (results_save |
     'Sample One' >> beam.transforms.combiners.Sample.FixedSizeGlobally(1) |
     'Serialize Schema' >> beam.Map(lambda path: json.dumps(output_schema)) |
     'Write Schema' >> beam.io.textio.WriteToText(schema_file, shard_name_template=''))

  if output_bq_table is not None:
    # BigQuery sink takes schema in the form of 'field1:type1,field2:type2...'
    bq_schema_string = ','.join(x['name'] + ':' + x['type'] for x in output_schema)
    sink = beam.io.BigQuerySink(output_bq_table, schema=bq_schema_string,
                                write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE)
    results | 'Write BQ Results' >> beam.io.Write(sink)
470730
def work(druid)
      LyberCore::Log.set_logfile($stdout) # let process manager(bluepill) handle logging
      LyberCore::Log.info "#{druid} processing"
      return if @check_queued_status && !item_queued?(druid)

      result = nil
      elapsed = Benchmark.realtime do
        result = perform druid # implemented in the mixed-in robot class
      end

      # this is the default note to pass back to workflow service, but it can be overriden by a robot that uses the Lybercore::Robot::ReturnState object to return a status
      note = Socket.gethostname

      # the final workflow state is determined by the return value of the perform step, if it is a ReturnState object,
      # we will use the defined status, otherwise default to completed
      # if a note is passed back, we will also use that instead of the default
      if result.class == LyberCore::Robot::ReturnState
        workflow_state = result.status
        note = result.note unless result.note.blank?
      else
        workflow_state = 'completed'
      end

      # update the workflow status from its current state to the state returned by perform (or 'completed' as the default)
      workflow_service.update_workflow_status(@repo, druid, @workflow_name, @step_name, workflow_state, elapsed: elapsed, note: note)
      LyberCore::Log.info "Finished #{druid} in #{sprintf('%0.4f', elapsed)}s"
    rescue StandardError => e
      Honeybadger.notify(e) if defined? Honeybadger
      begin
        LyberCore::Log.error e.message + "\n" + e.backtrace.join("\n")
        workflow_service.update_workflow_error_status(@repo, druid, @workflow_name, @step_name, e.message, error_text: Socket.gethostname)
      rescue StandardError => e2
        LyberCore::Log.error "Cannot set #{druid} to status='error'\n" + e2.message + "\n" + e2.backtrace.join("\n")
        raise e2 # send exception to Resque failed queue
      end
    end
810562
def pipeline(self, transaction=True, shard_hint=None):
        '''  '''
        args_dict = {
            'connection_pool': self.connection_pool,
            'response_callbacks': self.response_callbacks,
            'transaction': transaction,
            'shard_hint': shard_hint,
            'logger': self.logger,
        }

        return StonePipeline(**args_dict)
63305
function _runFlow(cmd, callback) {
  execFile(flow, cmd, {
    cwd: module.__dirname
  }, function (err, stdout, stderr) {
    if (err && stdout.length > 0) {
      return callback(new $.util.PluginError('flow', stdout));
    } else if (err) {
      $.util.log(stderr);
      return callback(err);
    } else { // eslint-disable-line
      callback();
    }
  });
}
1116725
function Worker(vfs) {
    Agent.call(this, {

        // Endpoints for writable streams at meta.stream (and meta.process.stdin)
        write: write,
        end: end,

        // Endpoint for readable stream at meta.stream (and meta.process.{stdout,stderr})
        destroy: destroy,

        // Endpoints for readable streams at options.stream
        onData: onData,
        onEnd: onEnd,

        // Endpoint for writable streams at options.stream
        onClose: onClose,

        // Endpoints for processes at meta.process
        kill: kill,

        // Endpoint for watchers at meta.watcher
        close: closeWatcher,

        // Endpoint for apis at meta.api
        call: call,

        // Endpoints for vfs itself
        subscribe: subscribe,
        unsubscribe: unsubscribe,
        emit: vfs.emit,

        // special vfs-socket api
        ping: ping,

        // Route other calls to the local vfs instance
        resolve:  route("resolve"),
        stat:     route("stat"),
        readfile: route("readfile"),
        readdir:  route("readdir"),
        mkfile:   route("mkfile"),
        mkdir:    route("mkdir"),
        rmfile:   route("rmfile"),
        rmdir:    route("rmdir"),
        rename:   route("rename"),
        copy:     route("copy"),
        symlink:  route("symlink"),
        watch:    route("watch"),
        connect:  route("connect"),
        spawn:    route("spawn"),
        execFile: route("execFile"),
        extend:   route("extend"),
        unextend: route("unextend"),
        use:      route("use")

    });

    var proxyStreams = {};
    var streams = {};
    var watchers = {};
    var processes = {};
    var apis = {};
    var handlers = {};
    var remote = this.remoteApi;

    function subscribe(name, callback) {
        handlers[name] = function (value) {
            remote.onEvent(name, value);
        };
        vfs.on(name, handlers[name], callback);
    }

    function unsubscribe(name, callback) {
        var handler = handlers[name];
        if (!handler) return;
        delete handlers[name];
        vfs.off(name, handler, callback);
    }

    // Resume readable streams that we paused when the channel drains
    // Forward drain events to all the writable proxy streams.
    this.on("drain", function () {
        Object.keys(streams).forEach(function (id) {
            var stream = streams[id];
            if (stream.readable && stream.resume) stream.resume();
        });
        Object.keys(proxyStreams).forEach(function (id) {
            var stream = proxyStreams[id];
            if (stream.writable) stream.emit("drain");
        });
    });

    // Cleanup streams, proxy streams, proxy processes, and proxy apis on disconnect.
    this.on("disconnect", function (err) {
        if (!err) {
            err = new Error("EDISCONNECT: vfs socket disconnected");
            err.code = "EDISCONNECT";
        }
        Object.keys(streams).forEach(function (id) {
            var stream = streams[id];
            stream.emit("close", err);
        });
        Object.keys(proxyStreams).forEach(onClose);
        Object.keys(processes).forEach(function (pid) {
            var process = processes[pid];
            process.kill();
            delete processes[pid];
        });
        Object.keys(watchers).forEach(function (id) {
            var watcher = watchers[id];
            delete watchers[id];
            watcher.close();
        });
    });
    
    function makeStreamProxy(token) {
        var stream = new Stream();
        var id = token.id;
        stream.id = id;
        proxyStreams[id] = stream;
        if (token.hasOwnProperty("readable")) stream.readable = token.readable;
        if (token.hasOwnProperty("writable")) stream.writable = token.writable;

        if (stream.writable) {
            stream.write = function (chunk) {
                return remote.write(id, chunk);
            };
            stream.end = function (chunk) {
                if (chunk) remote.end(id, chunk);
                else remote.end(id);
            };
        }
        if (stream.readable) {
            stream.destroy = function () {
                remote.destroy(id);
            };
        }

        return stream;
    }

    var nextStreamID = 1;
    function storeStream(stream) {
        nextStreamID = nextStreamID++ % 10000;
        while (streams.hasOwnProperty(nextStreamID)) { nextStreamID++ % 10000; }
        var id = nextStreamID;
        streams[id] = stream;
        stream.id = id;
        if (stream.readable) {
            stream.on("data", function (chunk) {
                if (remote.onData(id, chunk) === false) {
                    stream.pause && stream.pause();
                }
            });
            stream.on("end", function () {
                delete streams[id];
                remote.onEnd(id);
            });
        }
        stream.on("close", function () {
            delete streams[id];
            remote.onClose(id);
        });
        var token = {id: id};
        if (stream.hasOwnProperty("readable")) token.readable = stream.readable;
        if (stream.hasOwnProperty("writable")) token.writable = stream.writable;
        return token;
    }

    function storeProcess(process) {
        var pid = process.pid;
        processes[pid] = process;
        process.on("exit", function (code, signal) {
            delete processes[pid];
            remote.onExit(pid, code, signal);
        });
        process.on("close", function () {
            delete processes[pid];
            delete streams[process.stdout.id];
            delete streams[process.stderr.id];
            delete streams[process.stdin.id];
            remote.onProcessClose(pid);
        });

        process.kill = function(code) {
            killtree(pid, code);
        };

        var token = {pid: pid};
        token.stdin = storeStream(process.stdin);
        token.stdout = storeStream(process.stdout);
        token.stderr = storeStream(process.stderr);
        return token;
    }

    function killtree(pid, code) {
        childrenOfPid(pid, function(err, pidlist){
            if (err) {
                console.error(err.stack);
                return;
            }
            pidlist.forEach(function (pid) {
                try {
                    process.kill(pid, code || "SIGKILL");
                } catch(e) {
                    // kill may throw if the pid does not exist.
                }
            });
        });
    }

    function childrenOfPid(pid, callback) {
        execFile("ps", ["-A", "-oppid,pid"], function(code, stdout, stderr) {
            if (code)
                return callback(code + ":" + stderr);

            var parents = {};
            stdout.split("\n").slice(1).forEach(function(line) {
                var col = line.trim().split(/\s+/g);
                (parents[col[0]] || (parents[col[0]] = [])).push(col[1]);
            });

            function search(roots) {
            var res = roots.concat();
            for (var c, i = 0; i < roots.length; i++) {
                if ((c = parents[roots[i]]) && c.length)
                    res.push.apply(res, search(c));
                }
                return res;
            }
            callback(null, search([pid]));
        });
    }

    var nextWatcherID = 1;
    function storeWatcher(watcher) {
        while (watchers.hasOwnProperty(nextWatcherID)) { nextWatcherID++; }
        var id = nextWatcherID;
        watchers[id] = watcher;
        watcher.id = id;
        watcher.on("change", function (event, filename) {
            remote.onChange(id, event, filename);
        });
        var token = {id: id};
        return token;
    }

    function storeApi(api) {
        var name = api.name;
        apis[name] = api;
        var token = { name: name, names: api.names };
        return token;
    }

    // Remote side writing to our local writable streams
    function write(id, chunk) {
        // They want to write to our real stream
        var stream = streams[id];
        if (!stream) return;
        stream.write(chunk);
    }
    function destroy(id) {
        var stream = streams[id];
        if (!stream) return;
        delete streams[id];
        stream.destroy();
        nextStreamID = id;
    }
    function end(id, chunk) {
        var stream = streams[id];
        if (!stream) return;
        delete streams[id];
        if (chunk) stream.end(chunk);
        else stream.end();
        nextStreamID = id;
    }

    function kill(pid, code) {
        var process = processes[pid];
        if (!process) return;
        process.kill(code);
    }

    function closeWatcher(id) {
        var watcher = watchers[id];
        if (!watcher) return;
        delete watchers[id];
        watcher.close();
        nextWatcherID = id;
    }

    function call(name, fnName, args) {
        var api = apis[name];
        if (!api) return;

        // If the last arg is a function, assume it's a callback and process it.
        if (typeof args[args.length - 1] == "function") {
            var callback = args[args.length - 1];
            args[args.length - 1] = function (err, meta) {
                if (err || (meta && typeof meta === "object")) {
                    return processCallback(err, meta, callback);
                }
                callback(err, meta);
            };
        }

        api[fnName].apply(api, args);
    }

    function onData(id, chunk) {
        var stream = proxyStreams[id];
        if (!stream) return;
        stream.emit("data", chunk);
    }
    function onEnd(id) {
        var stream = proxyStreams[id];
        if (!stream) return;
        // TODO: not delete proxy if close is going to be called later.
        // but somehow do delete proxy if close won't be called later.
        delete proxyStreams[id];
        stream.emit("end");
    }
    function onClose(id) {
        var stream = proxyStreams[id];
        if (!stream) return;
        delete proxyStreams[id];
        stream.emit("close");
    }

    // Can be used for keepalive checks.
    function ping(callback) {
        callback();
    }

    function processCallback(err, meta, callback) {
        // Make error objects serializable
        if (err) {
            var nerr = {
                stack: process.pid + ": " + err.stack
            };
            if (err.hasOwnProperty("code")) nerr.code = err.code;
            if (err.hasOwnProperty("message")) nerr.message = err.message;
            return callback(nerr);
        }
        var token = {};
        var keys = Object.keys(meta);
        for (var i = 0, l = keys.length; i < l; i++) {
            var key = keys[i];
            switch (key) {
                case "stream": token.stream = storeStream(meta.stream); break;
                case "process": token.process = storeProcess(meta.process); break;
                case "watcher": token.watcher = storeWatcher(meta.watcher); break;
                case "api": token.api = storeApi(meta.api); break;
                default: token[key] = meta[key]; break;
            }
        }
        // Call the remote callback with the result
        callback(null, token);
    }

    function route(name) {
        return function wrapped(path, options, callback) {
            if (typeof callback !== "function") {
                throw new Error(name + ": callback must be function");
            }
            // Call the real local function, but intercept the callback
            if (options.stream) {
                options.stream = makeStreamProxy(options.stream);
            }
            vfs[name](path, options, function (err, meta) {
                processCallback(err, meta, callback);
            });
        };
    }
}
995473
function Client(transport, fastPathTransport) {
	Sec.call(this, transport, fastPathTransport);
	// for basic RDP layer (in futur)
	this.enableSecureCheckSum = false;
	var self = this;
	this.transport.on('connect', function(gccClient, gccServer, userId, channels) {
		self.connect(gccClient, gccServer, userId, channels);
	}).on('close', function() {
		self.emit('close');
	}).on('error', function (err) {
		self.emit('error', err);
	});
}
953781
def CallFlow(self,
               flow_name=None,
               next_state=None,
               request_data=None,
               client_id=None,
               **kwargs):
    """"""
    base_session_id = None
    if client_id:
      # The flow is stored in the hunt namespace,
      base_session_id = self.urn.Add(client_id.Basename())

    # Actually start the new flow.
    child_urn = self.runner.CallFlow(
        flow_name=flow_name,
        next_state=next_state,
        base_session_id=base_session_id,
        client_id=client_id,
        request_data=request_data,
        **kwargs)

    if client_id:
      # But we also create a symlink to it from the client's namespace.
      hunt_link_urn = client_id.Add("flows").Add("%s:hunt" %
                                                 (self.urn.Basename()))

      hunt_link = aff4.FACTORY.Create(
          hunt_link_urn, aff4.AFF4Symlink, token=self.token)

      hunt_link.Set(hunt_link.Schema.SYMLINK_TARGET(child_urn))
      hunt_link.Close()

    return child_urn
1047101
protected float findFlow( int cx , int cy , T curr , ImageFlow.D flow ) {
		float bestScore = Float.MAX_VALUE;
		int bestFlowX=0,bestFlowY=0;

		// ensure the search region is contained entirely inside the image
		int startY = cy-searchRadius-regionRadius < 0 ? Math.max(regionRadius - cy, 0) : -searchRadius;
		int startX = cx-searchRadius-regionRadius < 0 ? Math.max(regionRadius-cx,0) : -searchRadius;
		int endY = cy+searchRadius+regionRadius >= curr.height ? curr.height-cy-regionRadius-1 : searchRadius;
		int endX = cx+searchRadius+regionRadius >= curr.width ? curr.width-cx-regionRadius-1 : searchRadius;

		// search around the template's center
		for( int i = startY; i <= endY; i++ ) {
			int y = cy+i;
			for( int j = startX; j <= endX; j++ ) {
				int x = cx+j;
				float error = computeError(x,y,curr);
				if( error < bestScore ) {
					bestScore = error;
					bestFlowX = j;
					bestFlowY = i;
				} else if ( error == bestScore ) {
					// Pick solution with the least motion when ambiguous
					float m0 = j*j + i*i;
					float m1 = bestFlowX*bestFlowX + bestFlowY*bestFlowY;
					if( m0 < m1 ) {
						bestFlowX = j;
						bestFlowY = i;
					}
				}
			}
		}

		if( bestScore <= maxError ) {
			flow.x = bestFlowX;
			flow.y = bestFlowY;
			return bestScore;
		} else {
			flow.markInvalid();
			return Float.NaN;
		}
	}
537468
def skypipe_input_stream(endpoint, name=None):
    """"""
    name = name or ''
    class context_manager(object):
        def __enter__(self):
            self.socket = ctx.socket(zmq.DEALER)
            self.socket.connect(endpoint)
            return self

        def send(self, data):
            data_msg = sp_msg(SP_CMD_DATA, name, data)
            self.socket.send_multipart(data_msg)

        def __exit__(self, *args, **kwargs):
            eof_msg = sp_msg(SP_CMD_DATA, name, SP_DATA_EOF)
            self.socket.send_multipart(eof_msg)
            self.socket.close()

    return context_manager()
187372
function flowType(src, dst) {
  var srcPath = [src+'/**/*.js',
    '!'+src+'/**/__tests__/**', '!'+src+'/**/__mocks__/**'];
  return gulp
    .src(srcPath)
    .pipe(rename({extname: '.js.flow'}))
    .pipe(gulp.dest(dst));
}
1187054
function Main() {
  const lerna = requireLerna();
  const useYarn = shouldUseYarn();

  if (!lerna) {
    if (useYarn) {
      logger.error(
        'Lerna cannot not be found. Please run `yarn --check-files`.'
      );
    } else {
      logger.error('Lerna cannot not be found.');
      logger.hint('Remove `node_modules` and run `npm install` again.');
    }

    process.exit(1);
  }

  const args = ['bootstrap'];

  if (useYarn) {
    args.push('--npm-client=yarn');
    // yarn doesn't support concurrency
    args.push('--concurrency=1');
  } else {
    // windows doesn't handle concurrency too well
    if (isWindows || !shouldUseNpmWithConcurrency()) {
      args.push('--concurrency=1');
    }
  }

  child = spawn(lerna, args, { stdio: 'inherit' });
  child.on('close', code => process.exit(code));
}