Test method for inputAnalzeCallback

        This method loops over the passed number of files, 
        and optionally "delays" in each loop to simulate
        some analysis. The delay length is specified by
        the '--test <delay>' flag.
770571
def inputAnalyzeCallback(self, *args, **kwargs):
        
        b_status            = False
        filesRead           = 0
        filesAnalyzed       = 0

        for k, v in kwargs.items():
            if k == 'filesRead':    d_DCMRead   = v
            if k == 'path':         str_path    = v

        if len(args):
            at_data         = args[0]
            str_path        = at_data[0]
            d_read          = at_data[1]

        b_status        = True
        self.dp.qprint("analyzing:\n%s" % 
                                self.pp.pformat(d_read['l_file']), 
                                level = 5)
        if int(self.f_sleepLength):
            self.dp.qprint("sleeping for: %f" % self.f_sleepLength, level = 5)
            time.sleep(self.f_sleepLength)
        filesAnalyzed   = len(d_read['l_file'])

        return {
            'status':           b_status,
            'filesAnalyzed':    filesAnalyzed,
            'l_file':           d_read['l_file']
        }
1003794
def follow(self, delay=1.0):
        
        # TODO: Handle log file rotation
        self.trailing = True
        unchanged_stats = 0
        
        while not self.should_stop_follow:
            where = self.file.tell()
            line = self.file.readline()
            if line:    
                if self.trailing and line in self.line_terminators:
                    # This is just the line terminator added to the end of the file
                    # before a new line, ignore.
                    self.trailing = False
                    continue

                if line[-1] in self.line_terminators:
                    line = line[:-1]
                    if line[-1:] == '\r\n' and '\r\n' in self.line_terminators:
                        # found crlf
                        line = line[:-1]

                self.trailing = False
                unchanged_stats = 0
                yield line
            else:
                self.trailing = True
                self.seek(where)
                yield no_new_line
                # Try to catch up rotated log file
                unchanged_stats += 1
                if unchanged_stats >= self.MAX_UNCHANGED_STATS and \
                        where != os.stat(self.file.name).st_size:
                    logger.info('Reopen log file because file may has been rotated.')
                    self.reopen_file()

                time.sleep(delay)
369165
def _check_input_files(nspc, parser):
        """"""
        if not len(nspc.filenames) == 3:
            parser.print_help()
            msg = """
      3 Expected files; Expected content: study population association",
      {} Actual   files: {}""".format(len(nspc.filenames), ' '.join(nspc.filenames))
            raise Exception(msg)
        for fin in nspc.filenames:
            if not os.path.exists(fin):
                return "*{}* does not exist".format(fin)

        return False
141664
@Override
    public Method analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
        JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, descriptor.getClassDescriptor());
        Method[] methodList = jclass.getMethods();

        Method result = null;

        // As a side-effect, cache all of the Methods for this JavaClass
        for (Method method : methodList) {
            MethodDescriptor methodDescriptor = DescriptorFactory.instance().getMethodDescriptor(
                    descriptor.getSlashedClassName(), method.getName(), method.getSignature(), method.isStatic());

            // Put in cache eagerly
            analysisCache.eagerlyPutMethodAnalysis(Method.class, methodDescriptor, method);

            if (methodDescriptor.equals(descriptor)) {
                result = method;
            }
        }

        return result;
    }
314623
def prep_fastq_inputs(in_files, data):
    
    if len(in_files) == 1 and _is_bam_input(in_files):
        out = _bgzip_from_bam(in_files[0], data["dirs"], data)
    elif len(in_files) == 1 and _is_cram_input(in_files):
        out = _bgzip_from_cram(in_files[0], data["dirs"], data)
    elif len(in_files) in [1, 2] and _ready_gzip_fastq(in_files, data):
        out = _symlink_in_files(in_files, data)
    else:
        if len(in_files) > 2:
            fpairs = fastq.combine_pairs(in_files)
            pair_types = set([len(xs) for xs in fpairs])
            assert len(pair_types) == 1
            fpairs.sort(key=lambda x: os.path.basename(x[0]))
            organized = [[xs[0] for xs in fpairs]]
            if len(fpairs[0]) > 1:
                organized.append([xs[1] for xs in fpairs])
            in_files = organized
        parallel = {"type": "local", "num_jobs": len(in_files),
                    "cores_per_job": max(1, data["config"]["algorithm"]["num_cores"] // len(in_files))}
        inputs = [{"in_file": x, "read_num": i, "dirs": data["dirs"], "config": data["config"],
                   "is_cwl": "cwl_keys" in data,
                   "rgnames": data["rgnames"]}
                  for i, x in enumerate(in_files) if x]
        out = run_multicore(_bgzip_from_fastq_parallel, [[d] for d in inputs], data["config"], parallel)
    return out
868232
def analyze(self, handle, filename):
        
        # multipart post files.
        files = {"sample_file": (filename, handle)}

        # ensure the handle is at offset 0.
        handle.seek(0)

        response = self._request("/sample/submit", method='POST', files=files, headers=self.headers)

        try:
            if response.status_code == 200 and not response.json()['data']['errors']:
                # only support single-file submissions; just grab the first one.
                return response.json()['data']['samples'][0]['sample_id']
            else:
                raise sandboxapi.SandboxError("api error in analyze ({u}): {r}".format(u=response.url, r=response.content))
        except (ValueError, KeyError, IndexError) as e:
            raise sandboxapi.SandboxError("error in analyze: {e}".format(e=e))
806287
def loop(self):
        """"""
        while True:
            sleep(1)
            new_file_list = self.walk(self.file_path, {})
            if new_file_list != self.file_list:
                if self.debug:
                    self.diff_list(new_file_list, self.file_list)
                self.run_tests()
                self.file_list = new_file_list
1255645
function interpret(rawArgs) {
		// Determine if we're using stdin or files
		var argv = require('minimist')(rawArgs.slice(2));

		// Construct mocha arguments
		// XXXX accept other mocha opts
		var mochaOpts = {
			// grep: '',
			// ui: '',
			// timeout: '',
			// bail: '',
			reporter: argv.R || argv.reporter
		};

		// File-based input
		if (argv._.length > 0) {
			for (var i = argv._.length - 1; i >= 0; i--) {
				var data = fs.readFileSync(argv._[i], 'utf8');
				testDocument(data, mochaOpts);
			}
		} else { // Attempt to use STDIN
			stdin(function(data) {
				testDocument(data, mochaOpts);
			});
		}
	}
714545
def analyse(file, length=None, *, _termination=False):
    """"""
    seekset = file.tell()
    if not _termination:
        # FTP analysis
        flag, ftp = _analyse_ftp(file, length, seekset=seekset)
        if flag:
            return ftp

        # HTTP/1.* analysis
        flag, http = _analyse_httpv1(file, length, seekset=seekset)
        if flag:
            return http

        # NOTE: due to format similarity of HTTP/2 and TLS/SSL, HTTP/2 won't be analysed before TLS/SSL is implemented.
        # NB: the NOTE above is deprecated, since validations are performed

        # HTTP/2 analysis
        flag, http = _analyse_httpv2(file, length, seekset=seekset)
        if flag:
            return http

        # backup file offset
        file.seek(seekset, os.SEEK_SET)

    # raw packet analysis
    return Raw(file, length)
875927
def feed(self):
        ""
        line = self.testload.sentences[self.index % len(self.testload.sentences)]
        if "%Delay:" in line:
            # Delay specified number of seconds
            delay = line.split()[1]
            time.sleep(int(delay))
        # self.write has to be set by the derived class
        self.write(line)
        if self.progress:
            self.progress("gpsfake: %s feeds %d=%s\n" % (self.testload.name, len(line), repr(line)))
        time.sleep(WRITE_PAD)
        self.index += 1
1169787
function processFile(filePath, callback) {
  /*jshint validthis:true */
  var processor = this;
  processor.emit('processing.start', {
    file: filePath
  });

  encoder.detectBom(filePath, function(err, bomName) {
    var status = 'good';

    if (err) {
      status = 'error';
      processor.emit('processing.error', {
        file: filePath,
        message: 'Skipping file with errors during encoding detection: ' + err
      });
      return callback(null, status);
    }
    else {
      var needsFixing = false;
      var lastByteSequenceWasCR = false;
      var bytesPerBom = encoder.getBytesPerBom(bomName);
      var bytesPerControlChar = encoder.getBytesPerControlChar(bomName);

      var transformBuffer = [];
      var tempBuffer = null;

      // Fast-forward past the BOM if present
      var onFirstReadable = function() {
        var bomBuffer = this.read(bytesPerBom);
        if (bomBuffer == null || bomBuffer.length !== bytesPerBom) {
          status = 'error';
          processor.emit('processing.error', {
            file: filePath,
            message: 'Skipping file with errors during read: Unable to read past the expected BOM'
          });
          return callback(null, status);
        }
      };
      var onReadable = function() {
        var data = this.read(),
            i = 0,
            len = data.length,
            cursor = i,
            buffer;
        for ( ; i < len; i += bytesPerControlChar) {
          buffer = slicer.call(data, i, i + bytesPerControlChar);

          // If we read less bytes than the minimum number necessary to register
          // as a complete character in this encoding, put them back on the front
          // of the read queue for the next read and then bail out.
          if (buffer.length < bytesPerControlChar) {
            if (!tempBuffer || !arraysMatch(buffer, tempBuffer)) {
              tempBuffer = buffer;
              // Save these rogue bytes to inspect on the next time around
              this.unshift(data.slice(i, i + buffer.length));
              // Break out of the loop
              break;
            }
            else {
              // This will prevent an infinite loop if the number of bytes in the file
              // is erroneous/irregular, e.g. a total of 7 bytes in a UTF-16 file.
              status = 'error';

              // Send a signal to cause early termination (i.e. trigger the 'end' event)
              this.push(null);
              // Break out of the loop
              break;
            }
          }
          tempBuffer = null;

          if (encoder.doesByteSequenceSuggestBinary(buffer, bomName)) {
            status = 'skip';
            processor.emit('processing.skip', {
              file: filePath,
              message: 'Skipping suspected binary file'
            });
            // Send a signal to cause early termination (i.e. trigger the 'end' event)
            this.push(null);
            // Break out of the loop
            break;
          }
          else {
            if (encoder.isByteSequenceCR(buffer, bomName)) {
              lastByteSequenceWasCR = true;
            }
            else {
              if (lastByteSequenceWasCR && encoder.isByteSequenceLF(buffer, bomName)) {
                needsFixing = true;

                // Push everything (except for CRs) into the outgoing buffer
                transformBuffer.splice.apply(transformBuffer, [transformBuffer.length, 0].concat(slicer.call(data, cursor, i - bytesPerControlChar)));
                cursor = i;
              }

              // If this is the last byte of the buffer, push the remaining data into the outgoing buffer
              if (i + bytesPerControlChar === len && needsFixing) {
                // Push everything (except for CRs) into the outgoing buffer
                transformBuffer.splice.apply(transformBuffer, [transformBuffer.length, 0].concat(slicer.call(data, cursor)));
              }

              // Reset
              lastByteSequenceWasCR = false;
            }
          }
        }
      };
      var onError = function(err) {
        status = 'error';
        processor.emit('processing.error', {
          file: filePath,
          message: 'Skipping file with errors during read: ' + err
        });
        return callback(null, status);
      };
      var onEnd = function() {
        if (status === 'good') {
          if (needsFixing) {
            status = 'bad';
            this.on('close', function() {
              // Overwrite the existing file with the fixed data
              process.nextTick(function() {
                processor.emit('convert.start', {
                  file: filePath
                });

                //
                // TODO: Is there a more optimal way to do this?
                //       e.g. TransformStream, write to temp then move, etc.
                //
                fs.writeFile(filePath, new Buffer(transformBuffer), function(err) {
                  if (err) {
                    status = 'error';
                    processor.emit('convert.error', {
                      file: filePath,
                      message: 'Unexpected error during conversion process: ' + err
                    });
                  }
                  else {
                    status = 'fix';
                    processor.emit('convert.end', {
                      file: filePath
                    });
                  }

                  processor.emit('processing.end', {
                    file: filePath
                  });
                  return callback(null, status);
                });
              });
            });
          }
          else {
            status = 'skip';
            processor.emit('processing.skip', {
              file: filePath,
              message: 'Skipping file with all correct line endings'
            });
          }
        }

        if (status === 'skip') {
          processor.emit('processing.end', {
            file: filePath
          });
        }
        if (status !== 'bad') {
          return callback(null, status);
        }
      };

      var reader = new Readable();
      reader.wrap(fs.createReadStream(filePath));

      if (bytesPerBom > 0) {
        reader.once('readable', onFirstReadable);
      }
      reader
        .on('readable', onReadable)
        .on('error', onError)
        .on('end', onEnd);
    }
  });
}
438672
function internalStop(test) {
  	test.semaphore += 1;
  	config.blocking = true;

  	// Set a recovery timeout, if so configured.
  	if (defined.setTimeout) {
  		var timeoutDuration = void 0;

  		if (typeof test.timeout === "number") {
  			timeoutDuration = test.timeout;
  		} else if (typeof config.testTimeout === "number") {
  			timeoutDuration = config.testTimeout;
  		}

  		if (typeof timeoutDuration === "number" && timeoutDuration > 0) {
  			clearTimeout(config.timeout);
  			config.timeout = setTimeout(function () {
  				pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2));
  				internalRecover(test);
  			}, timeoutDuration);
  		}
  	}

  	var released = false;
  	return function resume() {
  		if (released) {
  			return;
  		}

  		released = true;
  		test.semaphore -= 1;
  		internalStart(test);
  	};
  }
900911
@Nonnull
    private static File writeDataToTempFileOrDie(@Nonnull final OutputStreamCallback callback,
                                                 @Nonnull final File targetFile,
                                                 @Nonnull final Logger log) throws IOException {
        Preconditions.checkNotNull(callback, "callback argument is required!");
        Preconditions.checkNotNull(log, "log argument is required!");
        Preconditions.checkNotNull(targetFile, "targetFile argument is required!");

        FileOutputStream fileOut = null;
        FileChannel fileChannel = null;
        try {
            final String targetFinalName = targetFile.getName();
            final File targetDirectory = targetFile.getParentFile();

            // open temporary file
            final File tmpFile = File.createTempFile(targetFinalName, ".tmp", targetDirectory);

            fileOut = new FileOutputStream(tmpFile);
            fileChannel = fileOut.getChannel();

            // make sure to use an output stream that flows THROUGH the FileChannel, so that FileChannel.force(true)
            // can do what it's supposed to

            // write the data AND flush it
            callback.writeAndFlushData(Channels.newOutputStream(fileChannel));

            return tmpFile;
        } finally {
            try {
                // fsync to disk (both data AND length)
                if (fileChannel != null) {
                    fileChannel.force(true);
                }
            } finally {
                // close the open file (if during an EXC,
                if (fileOut != null) {
                    fileOut.close();
                }
            }
        }
    }
459298
def loop_input(self, on_quit=None):
        
        # Start the init script
        self._run_script(
            self.__session, self._context.get_property(PROP_INIT_FILE)
        )

        # Run the script
        script_file = self._context.get_property(PROP_RUN_FILE)
        if script_file:
            self._run_script(self.__session, script_file)
        else:
            # No script: run the main loop (blocking)
            self._run_loop(self.__session)

        # Nothing more to do
        self._stop_event.set()
        sys.stdout.write("Bye !\n")
        sys.stdout.flush()
        if on_quit is not None:
            # Call a handler if needed
            on_quit()
1129927
function internalStart(test) {

  	// If semaphore is non-numeric, throw error
  	if (isNaN(test.semaphore)) {
  		test.semaphore = 0;

  		pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2));
  		return;
  	}

  	// Don't start until equal number of stop-calls
  	if (test.semaphore > 0) {
  		return;
  	}

  	// Throw an Error if start is called more often than stop
  	if (test.semaphore < 0) {
  		test.semaphore = 0;

  		pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2));
  		return;
  	}

  	// Add a slight delay to allow more assertions etc.
  	if (defined.setTimeout) {
  		if (config.timeout) {
  			clearTimeout(config.timeout);
  		}
  		config.timeout = setTimeout(function () {
  			if (test.semaphore > 0) {
  				return;
  			}

  			if (config.timeout) {
  				clearTimeout(config.timeout);
  			}

  			begin();
  		}, 13);
  	} else {
  		begin();
  	}
  }
549410
function() {

        var fileIndex;

        if (stop_loop) {
          return false;
        }

        // Check to see if are in queue mode
        if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {
          return pause(opts.queuewait);
        } else {
          // Take first thing off work queue
          fileIndex = workQueue[0];
          workQueue.splice(0, 1);

          // Add to processing queue
          processingQueue.push(fileIndex);
        }

        try {
          if (beforeEach(files[fileIndex]) !== false) {
            if (fileIndex === files_count) {
              return;
            }
            var reader = new FileReader(),
                max_file_size = 1048576 * opts.maxfilesize;

            reader.index = fileIndex;
            if (files[fileIndex].size > max_file_size) {
              opts.error(errors[2], files[fileIndex], fileIndex);
              // Remove from queue
              processingQueue.forEach(function(value, key) {
                if (value === fileIndex) {
                  processingQueue.splice(key, 1);
                }
              });
              filesRejected++;
              return true;
            }

            reader.onloadend = !opts.beforeSend ? send : function (e) {
              opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); });
            };

            reader.readAsBinaryString(files[fileIndex]);

          } else {
            filesRejected++;
          }
        } catch (err) {
          // Remove from queue
          processingQueue.forEach(function(value, key) {
            if (value === fileIndex) {
              processingQueue.splice(key, 1);
            }
          });
          opts.error(errors[0]);
          return false;
        }

        // If we still have work to do,
        if (workQueue.length > 0) {
          process();
        }
      }
1054911
def _inputhook_tk(inputhook_context):
    
    # Get the current TK application.
    import _tkinter  # Keep this imports inline!
    from six.moves import tkinter
    root = tkinter._default_root

    def wait_using_filehandler():
        """
        Run the TK eventloop until the file handler that we got from the
        inputhook becomes readable.
        """
        # Add a handler that sets the stop flag when `prompt-toolkit` has input
        # to process.
        stop = [False]
        def done(*a):
            stop[0] = True

        root.createfilehandler(inputhook_context.fileno(), _tkinter.READABLE, done)

        # Run the TK event loop as long as we don't receive input.
        while root.dooneevent(_tkinter.ALL_EVENTS):
            if stop[0]:
                break

        root.deletefilehandler(inputhook_context.fileno())

    def wait_using_polling():
        """
        Windows TK doesn't support 'createfilehandler'.
        So, run the TK eventloop and poll until input is ready.
        """
        while not inputhook_context.input_is_ready():
            while root.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
                 pass
            # Sleep to make the CPU idle, but not too long, so that the UI
            # stays responsive.
            time.sleep(.01)

    if root is not None:
        if hasattr(root, 'createfilehandler'):
            wait_using_filehandler()
        else:
            wait_using_polling()