auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean modifyEvent(String key, Construct value, BindableEvent e) { MCBlockBreakEvent event = (MCBlockBreakEvent)e; if (key.equals("drops")) { event.getBlock().setType(Material.AIR); if (value instanceof CArray) { CArray arr = (CArray)value; for(int i=0; i < arr.size(); i++) { CArray item = (CArray)arr.get(i); if(item.containsKey("type")){ ItemStack stk = new ItemStack(i, i); stk.setTypeId((int)((CInt)item.get("type")).getInt()); int amt; if(item.containsKey("amount")) { amt = (int)((CInt)item.get("amount")).getInt(); } else { amt = 1; } stk.setAmount(amt); if(item.containsKey("durability")) { short data = (short)((CInt)item.get("durability")).getInt(); stk.setDurability(data); } event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), stk); } } return true; } } return false; }

Target:
public boolean modifyEvent(String key, Construct value, BindableEvent e) { MCBlockBreakEvent event = (MCBlockBreakEvent)e; Block blk = event.getBlock(); if (key.equals("drops")) { blk.setType(Material.AIR); if (value instanceof CArray) { CArray arr = (CArray)value; for(int i=0; i < arr.size(); i++) { CArray item = (CArray)arr.get(i); MCItemStack stk = ObjectGenerator.GetGenerator().item(item, Target.UNKNOWN); blk.getWorld().dropItemNaturally(blk.getLocation(), (ItemStack)stk.getHandle()); } return true; } } return false; }
Source:
private void findChildren(CalledFunction node, int callStackQuark, ITmfStateSystem ss, int maxQuark) { fStore.add(node); long curTime = node.getStart(); long limit = node.getEnd(); ITmfStateInterval interval = null; while (curTime < limit) { try { if (callStackQuark + 1 <= maxQuark) { interval = ss.querySingleState(curTime, callStackQuark + 1); } else { return; } } catch (StateSystemDisposedException e) { e.printStackTrace(); } if (interval != null) { ITmfStateValue stateValue = interval.getStateValue(); if (!stateValue.isNull()) { long intervalStart = interval.getStartTime(); long intervalEnd = interval.getEndTime(); CalledFunction segment = new CalledFunction(intervalStart, intervalEnd + 1, stateValue.unboxLong()); segment.setDepth(node.getDepth() + 1); findChildren(segment, callStackQuark + 1, ss, maxQuark); node.addChild(segment); segmentStatics.calculateStatistics(segment); curTime = interval.getEndTime() + 1; } else { curTime = interval.getEndTime() + 1; } } } }

Target:
private void findChildren(CalledFunction node, int callStackQuark, ITmfStateSystem ss, int maxQuark) { fStore.add(node); long curTime = node.getStart(); long limit = node.getEnd(); ITmfStateInterval interval = null; while (curTime < limit) { try { if (callStackQuark + 1 <= maxQuark) { interval = ss.querySingleState(curTime, actualQuarks.get(callStackQuark + 1)); } else { return; } } catch (StateSystemDisposedException e) { e.printStackTrace(); } if (interval != null) { ITmfStateValue stateValue = interval.getStateValue(); if (!stateValue.isNull()) { long intervalStart = interval.getStartTime(); long intervalEnd = interval.getEndTime(); CalledFunction segment = new CalledFunction(intervalStart, intervalEnd + 1, stateValue.unboxLong()); segment.setDepth(node.getDepth() + 1); findChildren(segment, actualQuarks.get(callStackQuark + 1), ss, maxQuark); node.addChild(segment); fSegmentStatics.calculateStatistics(segment); curTime = interval.getEndTime() + 1; } else { curTime = interval.getEndTime() + 1; } } } }
Source:
public void getSuitablePnpm_tooNewVersionInstalledAndSkipVersionCheck_accepted() throws Exception { Assume.assumeFalse( tools.getNodeExecutable().isEmpty()); String originalPropertyValue = System .getProperty(FrontendUtils.PARAM_IGNORE_VERSION_CHECKS); createFakePnpm("5.5.0"); try { System.setProperty(FrontendUtils.PARAM_IGNORE_VERSION_CHECKS, "true"); List<String> pnpmCommand = tools.getSuitablePnpm(baseDir); Assert.assertNotEquals("expected pnpm version 5.5.0 accepted", 0, pnpmCommand.size()); } finally { if (originalPropertyValue != null) { System.setProperty(FrontendUtils.PARAM_IGNORE_VERSION_CHECKS, originalPropertyValue); } else { System.clearProperty(FrontendUtils.PARAM_IGNORE_VERSION_CHECKS); } } }

Target:
public void getSuitablePnpm_tooNewVersionInstalledAndSkipVersionCheck_accepted() throws Exception { tools = new FrontendTools(baseDir, () -> vaadinHomeDir, "v12.10.0", new File(baseDir).toURI(), true); Assume.assumeFalse( tools.getNodeExecutable().isEmpty()); createFakePnpm("5.5.0"); List<String> pnpmCommand = tools.getSuitablePnpm(baseDir); Assert.assertNotEquals("expected pnpm version 5.5.0 accepted", 0, pnpmCommand.size()); }
Source:
private static Stream<ImmutableList<String>> parseLine(String line, char separator) { if (line.length() == 0 || line.startsWith("#") || line.startsWith(";")) { return Stream.empty(); } ImmutableList.Builder<String> builder = ImmutableList.builder(); int start = 0; String terminated = line + separator; int nextComma = terminated.indexOf(separator, start); while (nextComma >= 0) { String possible = terminated.substring(start, nextComma).trim(); if (possible.startsWith("\"")) { while (true) { if (possible.substring(1).replace("\"\"", "").endsWith("\"")) { possible = possible.substring(1, possible.length() - 1).replace("\"\"", "\""); break; } else { nextComma = terminated.indexOf(separator, nextComma + 1); if (nextComma < 0) { throw new IllegalArgumentException("Mismatched quotes on line: " + line); } possible = terminated.substring(start, nextComma).trim(); } } } builder.add(possible); start = nextComma + 1; nextComma = terminated.indexOf(separator, start); } ImmutableList<String> fields = builder.build(); if (!hasContent(fields)) { return Stream.empty(); } return Stream.of(fields); }

Target:
private static Stream<ImmutableList<String>> parseLine(String line, char separator) { if (line.length() == 0 || line.startsWith("#") || line.startsWith(";")) { return Stream.empty(); } ImmutableList.Builder<String> builder = ImmutableList.builder(); int start = 0; String terminated = line + separator; int nextSeparator = terminated.indexOf(separator, start); while (nextSeparator >= 0) { String possible = terminated.substring(start, nextSeparator).trim(); if (possible.startsWith("\"")) { while (true) { if (possible.substring(1).replace("\"\"", "").endsWith("\"")) { possible = possible.substring(1, possible.length() - 1).replace("\"\"", "\""); break; } else { nextSeparator = terminated.indexOf(separator, nextSeparator + 1); if (nextSeparator < 0) { throw new IllegalArgumentException("Mismatched quotes on line: " + line); } possible = terminated.substring(start, nextSeparator).trim(); } } } builder.add(possible); start = nextSeparator + 1; nextSeparator = terminated.indexOf(separator, start); } ImmutableList<String> fields = builder.build(); if (!hasContent(fields)) { return Stream.empty(); } return Stream.of(fields); }
Source:
public SAMFileWriter makeBAMWriter(final SAMFileHeader header, final boolean presorted, final Path outputPath, final int compressionLevel) { try { final boolean createMd5File = this.createMd5File && IOUtil.isRegularPath(outputPath); if (this.createMd5File && !createMd5File) { log.warn("Cannot create MD5 file for BAM because output file is not a regular file: " + outputPath.toUri()); } OutputStream os = IOUtil.maybeBufferOutputStream(Files.newOutputStream(outputPath), bufferSize); if (createMd5File) os = new Md5CalculatingOutputStream(os, IOUtil.addExtension(outputPath,".md5")); final BAMFileWriter ret = new BAMFileWriter(os, outputPath.toUri().toString(), compressionLevel, deflaterFactory); final boolean createIndex = this.createIndex && IOUtil.isRegularPath(outputPath); if (this.createIndex && !createIndex) { log.warn("Cannot create index for BAM because output file is not a regular file: " + outputPath.toUri()); } initializeBAMWriter(ret, header, presorted, createIndex); if (this.useAsyncIo) return new AsyncSAMFileWriter(ret, this.asyncOutputBufferSize); else return ret; } catch (final IOException ioe) { throw new RuntimeIOException("Error opening file '" + outputPath.toUri() + "': " + ioe); } }

Target:
public SAMFileWriter makeBAMWriter(final SAMFileHeader header, final boolean presorted, final Path outputPath, final int compressionLevel) { try { final boolean createMd5File = this.createMd5File && IOUtil.isRegularPath(outputPath); if (this.createMd5File && !createMd5File) { log.warn("Cannot create MD5 file for BAM because output file is not a regular file: " + outputPath.toUri()); } OutputStream os = IOUtil.maybeBufferOutputStream(Files.newOutputStream(outputPath), bufferSize); if (createMd5File) os = new Md5CalculatingOutputStream(os, IOUtil.addExtension(outputPath,".md5")); final BAMFileWriter ret = new BAMFileWriter(os, outputPath.toUri().toString(), compressionLevel, deflaterFactory); final boolean createIndex = this.createIndex && IOUtil.isRegularPath(outputPath); if (this.createIndex && !createIndex) { log.warn("Cannot create index for BAM because output file is not a regular file: " + outputPath.toUri()); } initializeBAMWriter(ret, header, presorted, createIndex); if (this.useAsyncIo) return new AsyncSAMFileWriter(ret, this.asyncOutputBufferSize); else return ret; } catch (final IOException ioe) { throw new RuntimeIOException("Error opening file: " + outputPath.toUri(), ioe); } }
Source:
public ReferenceContext(final int serializableSequenceId) { this.serializableSequenceId = serializableSequenceId; switch (serializableSequenceId) { case INTERNAL_INT_MULTIPLE: this.type = ReferenceContextType.MULTI_REFERENCE; break; case INTERNAL_INT_UNMAPPED: this.type = ReferenceContextType.UNMAPPED_UNPLACED; break; default: if (serializableSequenceId >= 0) { this.type = ReferenceContextType.SINGLE_REFERENCE; } else { throw new CRAMException("Invalid Reference Sequence ID: " + serializableSequenceId); } } }

Target:
public ReferenceContext(final int serializableSequenceId) { this.serializableSequenceId = serializableSequenceId; switch (serializableSequenceId) { case MULTIPLE_REFERENCE_ID: this.type = ReferenceContextType.MULTIPLE_REFERENCE_TYPE; break; case UNMAPPED_UNPLACED_ID: this.type = ReferenceContextType.UNMAPPED_UNPLACED_TYPE; break; default: if (serializableSequenceId >= 0) { this.type = ReferenceContextType.SINGLE_REFERENCE_TYPE; } else { throw new CRAMException("Invalid Reference Sequence ID: " + serializableSequenceId); } } }
Source:
public QuickOutlinePageDescriptor(final IQuickOutlineCallback quickOutlineCallback, final IQuickOutlineLabelProvider labelProvider, final IContentProvider contentProvider, String pageDescription) { Preconditions.checkArgument(quickOutlineCallback != null); Preconditions.checkArgument(labelProvider != null); Preconditions.checkArgument(contentProvider != null); Preconditions.checkArgument(pageDescription != null); this.quickOutlineCallback = quickOutlineCallback; this.labelProvider = labelProvider; this.contentProvider = contentProvider; this.pageDescription = pageDescription; }

Target:
public QuickOutlinePageDescriptor(final IQuickOutlineCallback quickOutlineCallback, final IQuickOutlineLabelProvider labelProvider, final IContentProvider contentProvider, String pageDescription) { this.quickOutlineCallback = Preconditions.checkNotNull(quickOutlineCallback); this.labelProvider = Preconditions.checkNotNull(labelProvider); this.contentProvider = Preconditions.checkNotNull(contentProvider); this.pageDescription = Preconditions.checkNotNull(pageDescription); }
Source:
public boolean parseMib(File mibFile) { if (mibDirectory == null || !mibDirectory.isDirectory()) { errorHandler.addError("MIB directory has not been set."); return false; } missingDependencies.clear(); List<URL> queue = new ArrayList<URL>(); parser.getFileParserPhase().setInputUrls(queue); final Map<String,File> mibDirectoryFiles = new HashMap<String,File>(); for (final File file : mibDirectory.listFiles()) { mibDirectoryFiles.put(file.getName().toLowerCase(), file); } LOG.debug("Parsing {}", mibFile.getAbsolutePath()); SmiMib mib = null; addFileToQueue(queue, mibFile); while (true) { errorHandler.reset(); try { mib = parser.parse(); } catch (Exception e) { LOG.error("Can't compile " + mibFile, e); errorHandler.addError(e.getMessage()); return false; } if (errorHandler.isOk()) { break; } else { List<String> dependencies = errorHandler.getDependencies(); if (dependencies.isEmpty()) break; missingDependencies.addAll(dependencies); if (!addDependencyToQueue(queue, mibDirectoryFiles)) break; } } if (errorHandler.isNotOk()) return false; LOG.info("The MIB has been parsed successfully.", mibFile.getAbsolutePath()); module = getModule(mib, mibFile); return module != null; }

Target:
public boolean parseMib(File mibFile) { if (mibDirectory == null || !mibDirectory.isDirectory()) { errorHandler.addError("MIB directory has not been set."); return false; } missingDependencies.clear(); List<URL> queue = new ArrayList<URL>(); parser.getFileParserPhase().setInputUrls(queue); final Map<String,File> mibDirectoryFiles = new HashMap<String,File>(); for (final File file : mibDirectory.listFiles()) { mibDirectoryFiles.put(file.getName().toLowerCase(), file); } LOG.debug("Parsing {}", mibFile.getAbsolutePath()); SmiMib mib = null; addFileToQueue(queue, mibFile); while (true) { errorHandler.reset(); try { mib = parser.parse(); } catch (Exception e) { LOG.error("Can't compile {}", mibFile, e); errorHandler.addError(e.getMessage()); return false; } if (errorHandler.isOk()) { break; } else { List<String> dependencies = errorHandler.getDependencies(); if (dependencies.isEmpty()) break; missingDependencies.addAll(dependencies); if (!addDependencyToQueue(queue, mibDirectoryFiles)) break; } } if (errorHandler.isNotOk()) return false; LOG.info("The MIB has been parsed successfully.", mibFile.getAbsolutePath()); module = getModule(mib, mibFile); return module != null; }
Source:
public LocalApplicationRunner(SamzaApplication app, Config config) { this.appDesc = ApplicationDescriptorUtil.getAppDescriptor(app, config); Boolean isAppModeBatch = new ApplicationConfig(appDesc.getConfig()).getAppMode() == ApplicationConfig.ApplicationMode.BATCH; if(isAppModeBatch) { initializeCoordinationUtils(config); initializeRunId(); } this.planner = new LocalJobPlanner(appDesc, coordinationUtils, uid, runId); }

Target:
public LocalApplicationRunner(SamzaApplication app, Config config) { this.appDesc = ApplicationDescriptorUtil.getAppDescriptor(app, config); isAppModeBatch = new ApplicationConfig(config).getAppMode() == ApplicationConfig.ApplicationMode.BATCH; coordinationUtils = getCoordinationUtils(config); }
Source:
public void characters(char ch[], int start, int length) throws SAXException { for (int i = 0; i < length; i++) { cell += Character.toString(ch[i + start]); } String title = ""; if (isTitle) { title = cell; title = title.replaceAll("/", "_"); title = title.replaceAll(" ", "_"); if (title.equals("")) { title = "empty_title"; } try { RoughArtifact roughArtifact = new RoughArtifact(RoughArtifactKind.CONTAINER); roughArtifact.addAttribute(CoreAttributeTypes.Name, title.trim()); roughArtifact.setGuid(GUID.create()); roughArtifact.setSectionNumber("0"); collector.addRoughArtifact(roughArtifact); isTitle = false; } catch (OseeCoreException ex) { throw new SAXException(ex); } } }

Target:
public void characters(char ch[], int start, int length) { for (int i = 0; i < length; i++) { cell.append(Character.toString(ch[i + start])); } String title = ""; if (isTitle) { title = cell.toString(); title = title.replaceAll("/", "_"); title = title.replaceAll(" ", "_"); if (title.equals("")) { title = "empty_title"; } try { RoughArtifact roughArtifact = new RoughArtifact(RoughArtifactKind.CONTAINER); roughArtifact.addAttribute(CoreAttributeTypes.Name, title.trim()); roughArtifact.setGuid(GUID.create()); roughArtifact.setSectionNumber("0"); collector.addRoughArtifact(roughArtifact); isTitle = false; } catch (OseeCoreException ex) { } } }
Source:
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) throw new RepositoryNotFoundException(name); Repository db = repo.getRepository(); db.incrementOpen(); return db; }

Target:
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) { throw new RepositoryNotFoundException(name); } Repository db = repo.getRepository(); db.incrementOpen(); return db; }
Source:
private void loadTab(int position) { QuestionGroupTab tab = mQuestionGroupTabs.get(position); if (!tab.isLoaded()) { Timber.d("Loading Tab #%d", position); tab.load(); tab.loadState(); setupDependencies(); if (mOnTabLoadedListener != null) { mOnTabLoadedListener.OnTabLoaded(); } } }

Target:
private void loadTab(int position) { QuestionGroupTab tab = mQuestionGroupTabs.get(position); if (!tab.isLoaded()) { Timber.d("Loading Tab #%d", position); tab.load(); tab.loadState(); setupDependencies(); if (mOnTabLoadedListener != null) { mOnTabLoadedListener.onTabLoaded(); } } }
Source:
private void updatePositionInfo(final StreamInfo info) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); final boolean playbackResumeEnabled = prefs.getBoolean(activity.getString(R.string.enable_watch_history_key), true) && prefs.getBoolean(activity.getString(R.string.enable_playback_resume_key), true); if (!playbackResumeEnabled || info.getDuration() <= 0) { positionView.setVisibility(View.INVISIBLE); detailPositionView.setVisibility(View.GONE); return; } if (recordManager == null) { recordManager = new HistoryRecordManager(requireContext()); } disposables.add(recordManager.loadStreamState(info) .onErrorComplete() .subscribeOn(Schedulers.io()) .delaySubscription(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe( state -> { final int seconds = (int) (state.getProgressTime() / 1000.f); if (seconds > BasePlayer.PLAYBACK_SAVE_THRESHOLD_START_SECONDS && seconds < info.getDuration() - BasePlayer.PLAYBACK_SAVE_THRESHOLD_END_SECONDS) { positionView.setMax((int) info.getDuration()); positionView.setProgress(seconds); detailPositionView.setText(Localization.getDurationString(seconds)); animateView(positionView, true, 500); animateView(detailPositionView, true, 500); } else { animateView(positionView, false, 500); animateView(detailPositionView, false, 500); } }, error -> { Log.e(TAG, "Player resume failure: ", error); }, () -> { animateView(positionView, false, 500); animateView(detailPositionView, false, 500); } )); }

Target:
private void updatePositionInfo(final StreamInfo info) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); final boolean playbackResumeEnabled = prefs.getBoolean(activity.getString(R.string.enable_watch_history_key), true) && prefs.getBoolean(activity.getString(R.string.enable_playback_resume_key), true); if (!playbackResumeEnabled || info.getDuration() <= 0) { positionView.setVisibility(View.INVISIBLE); detailPositionView.setVisibility(View.GONE); return; } if (recordManager == null) { recordManager = new HistoryRecordManager(requireContext()); } disposables.add(recordManager.loadStreamState(info) .onErrorComplete() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( state -> { final int seconds = (int) (state.getProgressTime() / 1000.f); if (seconds > BasePlayer.PLAYBACK_SAVE_THRESHOLD_START_SECONDS && seconds < info.getDuration() - BasePlayer.PLAYBACK_SAVE_THRESHOLD_END_SECONDS) { positionView.setMax((int) info.getDuration()); positionView.setProgress(seconds); detailPositionView.setText(Localization.getDurationString(seconds)); animateView(positionView, true, 500); animateView(detailPositionView, true, 500); } else { animateView(positionView, false, 500); animateView(detailPositionView, false, 500); } }, error -> { if (DEBUG) Log.e(TAG, "Player resume failure: ", error); }, () -> { animateView(positionView, false, 500); animateView(detailPositionView, false, 500); } )); }
Source:
public String getDevicePassword(long id, String protocol, String defaultPassword) { String password = lookupAttributeString(id, Command.KEY_DEVICE_PASSWORD, null, false); if (password != null) { return password; } if (protocol != null) { password = Context.getConfig().getString(protocol + "." + Command.KEY_DEVICE_PASSWORD); if (password != null) { return password; } } return defaultPassword; }

Target:
public String getDevicePassword(long id, String protocol, String defaultPassword) { String password = lookupAttributeString(id, Command.KEY_DEVICE_PASSWORD, null, false, false); if (password != null) { return password; } if (protocol != null) { password = Context.getConfig().getString(protocol + "." + Command.KEY_DEVICE_PASSWORD); if (password != null) { return password; } } return defaultPassword; }
Source:
private boolean safeWaitForCompletion( Future future, long timeoutSeconds ) { try { future.get( timeoutSeconds, TimeUnit.SECONDS ); } catch ( TimeoutException te ) { System.out.println( "Thread timed out." ); return false; } catch ( InterruptedException | ExecutionException e ) { fail(); } return true; }

Target:
private boolean safeWaitForCompletion( Future future, long timeoutSeconds ) { try { future.get( timeoutSeconds, TimeUnit.SECONDS ); } catch ( TimeoutException te ) { return false; } catch ( InterruptedException | ExecutionException e ) { fail(); } return true; }
Source:
public boolean allowsStyleWithHash(@Nonnull HashAlgorithm algorithm, @Nonnull Base64Value hashValue) { if (this.allowsUnsafeInlineStyle()) { return true; } StyleSrcElemDirective styleSrcElemDirective = this.getDirectiveByType(StyleSrcElemDirective.class); if (styleSrcElemDirective == null) { StyleSrcDirective styleSrcDirective = this.getDirectiveByType(StyleSrcDirective.class); if (styleSrcDirective == null) { return this.defaultsAllowHash(algorithm, hashValue); } return styleSrcDirective.matchesHash(algorithm, hashValue); } return styleSrcElemDirective.matchesHash(algorithm, hashValue); }

Target:
public boolean allowsStyleWithHash(@Nonnull HashAlgorithm algorithm, @Nonnull Base64Value hashValue) { if (this.allowsUnsafeInlineStyle()) { return true; } StyleSrcElemDirective styleSrcElemDirective = this.getDirectiveByType(StyleSrcElemDirective.class); if (styleSrcElemDirective != null) { return styleSrcElemDirective.matchesHash(algorithm, hashValue); } StyleSrcDirective styleSrcDirective = this.getDirectiveByType(StyleSrcDirective.class); if (styleSrcDirective != null) { return styleSrcDirective.matchesHash(algorithm, hashValue); } return this.defaultsAllowHash(algorithm, hashValue); }
Source:
public ChangesResult changes(String selector, Object since, Integer limit) { Map<String, Object> options = getDefaultChangeFeedOptions(); if(selector != null) { options.put("filter", "_selector"); } if(since != null) { options.put("since", since); } if (limit != null) { options.put("limit", limit); } if(limit != null) { options.put("seq_interval", limit); } else { options.put("seq_interval", 1000); } return this.changes(selector, options); }

Target:
public ChangesResult changes(String selector, Object since, Integer limit) { Misc.checkNotNullOrEmpty(selector,null); Map<String, Object> options = getParametrizedChangeFeedOptions(since, limit); options.put("filter", "_selector"); URI changesFeedUri = uriHelper.changesUri(options); HttpConnection connection = Http.POST(changesFeedUri, "application/json"); connection.setRequestBody(selector); return executeToJsonObjectWithRetry(connection, ChangesResult.class); }
Source:
public void randomBigDecimalUsingRange() { RandomFunction random = new RandomFunction(BigDecimal.class, new Range(1, 1000)); BigDecimal bigDecimal = random.generateValue(); assertNotNull("Generated BigDecimal must not be null", bigDecimal); assertTrue("Generated value must be a BigDecimal", bigDecimal instanceof BigDecimal); assertTrue(new BigDecimal("1").compareTo(bigDecimal) != 1); assertTrue(new BigDecimal("1000").compareTo(bigDecimal) != -1); }

Target:
public void randomBigDecimalUsingRange() { RandomFunction random = new RandomFunction(BigDecimal.class, new Range(1, 1000)); BigDecimal bigDecimal = random.generateValue(); assertNotNull("Generated BigDecimal must not be null", bigDecimal); assertTrue("Generated value must be a BigDecimal", bigDecimal instanceof BigDecimal); assertTrue(bigDecimal.compareTo(new BigDecimal("1")) >= 0); assertTrue(bigDecimal.compareTo(new BigDecimal("1000")) <= 0); }
Source:
public Iterable<User> iterate() { return new RtPagination<User>( this.request, new RtPagination.Mapping<User, JsonObject>() { @Override public User map(final JsonObject object) { return new RtUser( RtCollaborators.this.owner.github(), RtCollaborators.this.entry, object.getString("login") ); } } ); }

Target:
public Iterable<User> iterate() { return new RtPagination<User>( this.request, new RtPagination.Mapping<User, JsonObject>() { @Override public User map(final JsonObject object) { return RtCollaborators.this.owner.github().users() .get(object.getString("login")); } } ); }
Source:
protected void executeInternal(ServiceHub hub) throws DockerAccessException, MojoExecutionException { if (skipBuild) { return; } List<ImageConfiguration> resolvedImages = getResolvedImages(); if(resolvedImages == null || resolvedImages.isEmpty()) { resolvedImages.add(ImageConfiguration.getDefaultImageConfiguration(project, imageName)); } for (ImageConfiguration imageConfig : resolvedImages) { BuildImageConfiguration buildConfig = imageConfig.getBuildConfiguration(); if (buildConfig != null) { if (buildConfig.skip()) { log.info("%s : Skipped building", imageConfig.getDescription()); } else { buildAndTag(hub, imageConfig); } } } }

Target:
protected void executeInternal(ServiceHub hub) throws DockerAccessException, MojoExecutionException { if (skipBuild) { return; } List<ImageConfiguration> resolvedImages = getResolvedImages(); if(resolvedImages.isEmpty()) { if(imageName == null) { imageName = project.getGroupId() + "/" + project.getArtifactId() + ":" + project.getVersion(); } ImageConfiguration aDefaultImageConfig = ImageConfiguration.getDefaultImageConfiguration(imageName, project.getBasedir().getAbsolutePath()); processImageConfig(hub, aDefaultImageConfig); return; } else { for (ImageConfiguration imageConfig : resolvedImages) { processImageConfig(hub, imageConfig); } } }
Source:
private void createButtons() { btnCancel = createButton( locale.buttonCancel(), "git-revert-cancel", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCancelClicked(); ; } }); addButtonToFooter(btnCancel); btnRevert = createButton( locale.buttonRevert(), "git-revert", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onRevertClicked(); } }); addButtonToFooter(btnRevert); }

Target:
private void createButtons() { btnCancel = createButton( locale.buttonCancel(), "git-revert-cancel", event -> { delegate.onCancelClicked(); }); addButtonToFooter(btnCancel); btnRevert = createButton( locale.buttonRevert(), "git-revert", event -> { delegate.onRevertClicked(); }); addButtonToFooter(btnRevert); }
Source:
public void emitTuples() { while ((!fileQueue.isEmpty()) && (fileCount < getMaxFilesPerWindow())) { Path newPath = fileQueue.peek(); String newPathString = newPath.toString(); pendingFiles.add(newPathString); synchronized (processedFiles.getClass()) { processedFiles.add(newPathString); } localProcessedFileCount.increment(); fileQueue.remove(); fileCount++; } super.emitTuples(); }

Target:
public void emitTuples() { getFilesFromQueue(); super.emitTuples(); }
Source:
public PrestoS3OutputStream( AmazonS3 s3, String host, String key, File tempFile, boolean sseEnabled, PrestoS3SseType sseType, String sseKmsKeyId, long multiPartUploadMinFileSize, long multiPartUploadMinPartSize, PrestoS3AclType aclType) throws IOException { super(new BufferedOutputStream(new FileOutputStream(requireNonNull(tempFile, "tempFile is null")))); transferManager = TransferManagerBuilder.standard() .withS3Client(requireNonNull(s3, "s3 is null")) .withMinimumUploadPartSize(multiPartUploadMinPartSize) .withMultipartUploadThreshold(multiPartUploadMinFileSize).build(); this.host = requireNonNull(host, "host is null"); this.key = requireNonNull(key, "key is null"); this.tempFile = tempFile; this.sseEnabled = sseEnabled; this.sseType = requireNonNull(sseType, "sseType is null"); this.sseKmsKeyId = sseKmsKeyId; this.aclType = aclType.getCannedACL(); log.debug("OutputStream for key '%s' using file: %s", key, tempFile); }

Target:
public PrestoS3OutputStream( AmazonS3 s3, String host, String key, File tempFile, boolean sseEnabled, PrestoS3SseType sseType, String sseKmsKeyId, long multiPartUploadMinFileSize, long multiPartUploadMinPartSize, PrestoS3AclType aclType) throws IOException { super(new BufferedOutputStream(new FileOutputStream(requireNonNull(tempFile, "tempFile is null")))); transferManager = TransferManagerBuilder.standard() .withS3Client(requireNonNull(s3, "s3 is null")) .withMinimumUploadPartSize(multiPartUploadMinPartSize) .withMultipartUploadThreshold(multiPartUploadMinFileSize).build(); requireNonNull(aclType, "aclType is null"); this.aclType = aclType.getCannedACL(); this.host = requireNonNull(host, "host is null"); this.key = requireNonNull(key, "key is null"); this.tempFile = tempFile; this.sseEnabled = sseEnabled; this.sseType = requireNonNull(sseType, "sseType is null"); this.sseKmsKeyId = sseKmsKeyId; log.debug("OutputStream for key '%s' using file: %s", key, tempFile); }
Source:
private static CqlClient create( TaggedMetricRegistry taggedMetricRegistry, Session session, int preparedStatementCacheSize) { QueryCache queryCache = QueryCache.create( key -> session.prepare(key.formatQueryString()).setConsistencyLevel(key.queryConsistency()), taggedMetricRegistry, preparedStatementCacheSize); return new CqlClientImpl(session, queryCache); }

Target:
private static CqlClient create( TaggedMetricRegistry taggedMetricRegistry, Session session, int preparedStatementCacheSize) { QueryCache queryCache = QueryCache.create( key -> session.prepare(key.formatQueryString()), taggedMetricRegistry, preparedStatementCacheSize); return new CqlClientImpl(session, queryCache); }
Source:
public void execute() throws BuildException { if (includes == null && includesFile == null) { return; } if (destDir == null) { throw new BuildException("Destination directory not defined"); } if (!destDir.exists()) { try { destDir.mkdir(); } catch (SecurityException e) { throw new BuildException("Destination directory " + destDir + " does not exist and could not be created."); } } try { final FileUtils fileUtils = FileUtils.newFileUtils(); final List<String> incs = getIncludes(); if (relativePaths == null) { for (final String inc: incs) { final File srcFile = new File(inc); if (srcFile.exists()) { final File destFile = new File(destDir, srcFile.getName()); fileUtils.copyFile(srcFile, destFile); } } } else { for (final String inc: incs) { final File srcFile = new File(inc); File destFile = null; for (final String rel: relativePaths.split(COMMA)) { final File temp = new File(destDir, rel); if (temp.getName().equalsIgnoreCase(srcFile.getName())) { destFile = temp; break; } } if (srcFile.exists() && destFile != null) { fileUtils.copyFile(srcFile, destFile); } } } } catch (final IOException e) { throw new BuildException(e.getMessage(), e); } }

Target:
public void execute() throws BuildException { if (includes == null && includesFile == null) { return; } if (destDir == null) { throw new BuildException("Destination directory not defined"); } if (!destDir.exists() && !destDir.mkdirs()) { throw new BuildException(new IOException("Destination directory " + destDir + " cannot be created")); } try { final FileUtils fileUtils = FileUtils.newFileUtils(); final List<String> incs = getIncludes(); if (relativePaths == null) { for (final String inc: incs) { final File srcFile = new File(inc); if (srcFile.exists()) { final File destFile = new File(destDir, srcFile.getName()); fileUtils.copyFile(srcFile, destFile); } } } else { for (final String inc: incs) { final File srcFile = new File(inc); File destFile = null; for (final String rel: relativePaths.split(COMMA)) { final File temp = new File(destDir, rel); if (temp.getName().equalsIgnoreCase(srcFile.getName())) { destFile = temp; break; } } if (srcFile.exists() && destFile != null) { fileUtils.copyFile(srcFile, destFile); } } } } catch (final IOException e) { throw new BuildException(e.getMessage(), e); } }
Source:
public void triggerMisfired(Trigger trigger) { if (trigger.getKey().getGroup() == Scheduler.DEFAULT_GROUP) { long misfireDeltaMs = System.currentTimeMillis() - trigger.getNextFireTime().getTime(); registry.timer("triggers.cronMisfires").record(misfireDeltaMs, TimeUnit.MILLISECONDS); } }

Target:
public void triggerMisfired(Trigger trigger) { if (trigger.getKey().getGroup() == Scheduler.DEFAULT_GROUP) { long misfireDeltaMs = System.currentTimeMillis() - trigger.getNextFireTime().getTime(); registry.timer("echo.triggers.quartz.misfires").record(misfireDeltaMs, TimeUnit.MILLISECONDS); } }
Source:
public void close() throws IOException { txnLog.close(); txnLog = null; snapLog.close(); snapLog = null; }

Target:
public void close() throws IOException { if (txnLog != null) { txnLog.close(); txnLog = null; } if (snapLog != null) { snapLog.close(); snapLog = null; } }
Source:
@Test public void doNotOverrideWrapperEnvVar() throws Exception { FreeStyleProject p = setupProjectWithDefaultEnvValue(); p.getBuildWrappersList().add(new ContributingWrapper("DISPLAY", "BUILD_VAL")); validate(p); }

Target:
public void doNotOverrideWrapperEnvVar() throws Exception { FreeStyleProject p = setupProjectWithDefaultEnvValue(); p.getBuildWrappersList().add(new ContributingWrapper("DISPLAY", "BUILD_VAL")); assertValueInjected(p); }
Source:
public AccessToken getNewAccessToken(ByteBuffer username) { long stamp = lock.tryOptimisticRead(); checkArgument(isExistingUsername0(username) && isEnabledUsername(username)); if(!lock.validate(stamp)) { lock.readLock(); try { checkArgument(isExistingUsername0(username)); } finally { lock.unlockRead(stamp); } } return tokenManager.addToken(ByteBuffers.encodeAsHex(username)); }

Target:
public AccessToken getNewAccessToken(ByteBuffer username) { long stamp = lock.tryOptimisticRead(); checkArgument(isEnabledUsername(username)); if(!lock.validate(stamp)) { lock.readLock(); try { checkArgument(isEnabledUsername0(username)); } finally { lock.unlockRead(stamp); } } return tokenManager.addToken(ByteBuffers.encodeAsHex(username)); }
Source:
public void validatePaths(String[] paths) { validateZkVersion(); for (String path : paths) { if (!zkClient.exists(path)) { zkClient.createPersistent(path, true); } } }

Target:
public void validatePaths(String[] paths) { for (String path : paths) { if (!zkClient.exists(path)) { zkClient.createPersistent(path, true); } } }
Source:
public boolean put(final K key, final V val, final CacheEntryPredicate filter) throws IgniteCheckedException { boolean statsEnabled = ctx.statisticsEnabled(); boolean performanceStatsEnabled = ctx.kernalContext().performanceStatistics().statisticsEnabled(); long start = statsEnabled || performanceStatsEnabled ? System.nanoTime() : 0L; A.notNull(key, "key", val, "val"); if (keyCheck) validateCacheKey(key); boolean stored = put0(key, val, filter); if (statsEnabled && stored) metrics0().addPutTimeNanos(System.nanoTime() - start); if (performanceStatsEnabled) writeStatistics(CacheOperationType.PUT, start); return stored; }

Target:
public boolean put(final K key, final V val, final CacheEntryPredicate filter) throws IgniteCheckedException { boolean statsEnabled = ctx.statisticsEnabled(); boolean performanceStatsEnabled = ctx.kernalContext().performanceStatistics().enabled(); long start = statsEnabled || performanceStatsEnabled ? System.nanoTime() : 0L; A.notNull(key, "key", val, "val"); if (keyCheck) validateCacheKey(key); boolean stored = put0(key, val, filter); if (statsEnabled && stored) metrics0().addPutTimeNanos(System.nanoTime() - start); if (performanceStatsEnabled) writeStatistics(OperationType.CACHE_PUT, start); return stored; }
Source:
private void checkTasks() { if (storeOnlyTasks != null) { checkStoreTasks(); } if (stored >= minimalStore && replicated >= minimalReplicated && paged >= minimalPage) { checkGenericTasks(); } }

Target:
private void checkTasks() { if (storeOnlyTasks != null) { checkStoreTasks(); } if (stored >= minimalStore && replicated >= minimalReplicated && paged >= minimalPage) { checkCompleteContext(); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { GitHistoryPage page = getPage(); Repository repo = getRepository(event); IWizard wiz = null; List<Ref> branches = getBranchesExcludingCurrent(page, repo); if (branches.isEmpty()) { PlotCommit commit = (PlotCommit) getSelection(page) .getFirstElement(); wiz = new CreateBranchWizard(repo, commit.name()); } else { Collections.sort(branches, new Comparator<Ref>() { public int compare(Ref o1, Ref o2) { String refName1 = o1.getName(); String refName2 = o2.getName(); if (refName1.startsWith(Constants.R_REMOTES)) { if (refName2.startsWith(Constants.R_HEADS)) return -1; else return refName1.compareTo(refName2); } else { if (refName2.startsWith(Constants.R_REMOTES)) return 1; else return refName1.compareTo(refName2); } } }); Ref branch = branches.get(0).getLeaf(); wiz = new CreateBranchWizard(repo, branch.getName()); } WizardDialog dlg = new WizardDialog( HandlerUtil.getActiveShellChecked(event), wiz); dlg.setHelpAvailable(false); dlg.open(); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { GitHistoryPage page = getPage(); Repository repo = getRepository(event); IWizard wiz = null; List<Ref> branches = getBranches(page, repo); if (branches.isEmpty()) { PlotCommit commit = (PlotCommit) getSelection(page) .getFirstElement(); wiz = new CreateBranchWizard(repo, commit.name()); } else { Collections.sort(branches, new Comparator<Ref>() { public int compare(Ref o1, Ref o2) { String refName1 = o1.getName(); String refName2 = o2.getName(); if (refName1.startsWith(Constants.R_REMOTES)) { if (refName2.startsWith(Constants.R_HEADS)) return -1; else return refName1.compareTo(refName2); } else { if (refName2.startsWith(Constants.R_REMOTES)) return 1; else return refName1.compareTo(refName2); } } }); Ref branch = branches.get(0).getLeaf(); wiz = new CreateBranchWizard(repo, branch.getName()); } WizardDialog dlg = new WizardDialog( HandlerUtil.getActiveShellChecked(event), wiz); dlg.setHelpAvailable(false); dlg.open(); return null; }
Source:
default Map<String, Object> getEventStyle(ITimeEvent event) { StateItem stateItem = null; int index = getStateTableIndex(event); StateItem[] stateTable = getStateTable(); if (index >= 0 && index < stateTable.length) { stateItem = stateTable[index]; } Map<String, Object> styleMap = stateItem == null ? Collections.emptyMap() : stateItem.getStyleMap(); Map<String, Object> specificEventStyles = getSpecificEventStyle(event); if (specificEventStyles.isEmpty()) { return styleMap; } if (styleMap.isEmpty()) { return specificEventStyles; } styleMap = new HashMap<>(styleMap); styleMap.putAll(specificEventStyles); return styleMap; }

Target:
default Map<String, Object> getEventStyle(ITimeEvent event) { StateItem stateItem = null; int index = getStateTableIndex(event); StateItem[] stateTable = getStateTable(); if (index >= 0 && index < stateTable.length) { stateItem = stateTable[index]; } Map<String, Object> styleMap = stateItem == null ? Collections.EMPTY_MAP : stateItem.getStyleMap(); Map<String, Object> specificEventStyles = getSpecificEventStyle(event); if (specificEventStyles.isEmpty()) { return styleMap; } if (styleMap.isEmpty()) { return specificEventStyles; } styleMap = new HashMap<>(styleMap); styleMap.putAll(specificEventStyles); return styleMap; }
Source:
private static IllegalStateException prepareNotFoundException(Guid macPoolId) { final String msg = String.format(INEXISTENT_POOL_EXCEPTION_MESSAGE, macPoolId); return new IllegalStateException(msg); }

Target:
private IllegalStateException prepareNotFoundException(Guid macPoolId) { final String msg = String.format(INEXISTENT_POOL_EXCEPTION_MESSAGE, macPoolId); return new IllegalStateException(msg); }
Source:
private RemotePreviewLogicHelper.RemotePreviewHelperFunctions getEditPostActivityStrategyFunctions() { return new RemotePreviewLogicHelper.RemotePreviewHelperFunctions() { @Override public boolean isNewPost() { return EditPostActivity.this.isNewPost(); } @Override public void notifyNoNetwork() { UploadUtils.showSnackbar(findViewById(R.id.editor_activity), R.string.no_network_message); } @Override public boolean notifyUploadInProgress(PostModel post) { if (UploadService.hasInProgressMediaUploadsForPost(post)) { ToastUtils.showToast(EditPostActivity.this, getString(R.string.editor_toast_uploading_please_wait), Duration.SHORT); return true; } else { return false; } } @Nullable @Override public PostModel updatePostIfNeeded() { updatePostObject(); return mPost; } @Override public boolean canDiscard() { return isDiscardable(); } @Override public void notifyEmptyDraft() { ToastUtils.showToast(EditPostActivity.this, getString(R.string.error_preview_empty_draft), Duration.SHORT); } @Override public void startUploading(boolean isRemoteAutoSave, @Nullable PostModel post) { if (isRemoteAutoSave) { updatePostLoadingAndDialogState(PostLoadingState.REMOTE_AUTO_SAVING_FOR_PREVIEW, post); savePostAndOptionallyFinish(false, true); } else { updatePostLoadingAndDialogState(PostLoadingState.UPLOADING_FOR_PREVIEW, post); savePostAndOptionallyFinish(false); } } @Override public void notifyEmptyPost() { String message = getString( mIsPage ? R.string.error_preview_empty_page : R.string.error_preview_empty_post ); ToastUtils.showToast(EditPostActivity.this, message, Duration.SHORT); } }; }

Target:
private RemotePreviewLogicHelper.RemotePreviewHelperFunctions getEditPostActivityStrategyFunctions() { return new RemotePreviewLogicHelper.RemotePreviewHelperFunctions() { @Override public boolean notifyUploadInProgress(PostModel post) { if (UploadService.hasInProgressMediaUploadsForPost(post)) { ToastUtils.showToast(EditPostActivity.this, getString(R.string.editor_toast_uploading_please_wait), Duration.SHORT); return true; } else { return false; } } @Nullable @Override public PostModel updatePostIfNeeded() { updatePostObject(); return mPost; } @Override public void notifyEmptyDraft() { ToastUtils.showToast(EditPostActivity.this, getString(R.string.error_preview_empty_draft), Duration.SHORT); } @Override public void startUploading(boolean isRemoteAutoSave, @Nullable PostModel post) { if (isRemoteAutoSave) { updatePostLoadingAndDialogState(PostLoadingState.REMOTE_AUTO_SAVING_FOR_PREVIEW, post); savePostAndOptionallyFinish(false, true); } else { updatePostLoadingAndDialogState(PostLoadingState.UPLOADING_FOR_PREVIEW, post); savePostAndOptionallyFinish(false); } } @Override public void notifyEmptyPost() { String message = getString( mIsPage ? R.string.error_preview_empty_page : R.string.error_preview_empty_post ); ToastUtils.showToast(EditPostActivity.this, message, Duration.SHORT); } }; }
Source:
protected void subAppend(LoggingEvent event) { Level level = event.getLevel(); if (level.equals(Level.INFO)) { super.subAppend(event); } else { this.qw.write(getColour(event.getLevel())); this.qw.write(event.getLevel().toString() + ": "); this.qw.write(END_COLOUR); super.subAppend(event); if (this.immediateFlush) { this.qw.flush(); } } }

Target:
protected void subAppend(LoggingEvent event) { if (!Level.INFO.equals(event.getLevel())) { this.qw.write(getColour(event.getLevel())); this.qw.write(event.getLevel().toString() + ": "); this.qw.write(END_COLOUR); } super.subAppend(event); }
Source:
public void draw(GameDrawer drawer, SolGame game) { float x = position.x; float y = position.y; if (level.depth != 1) { Vector2 camPosition = game.getCam().getPosition(); x = (x - camPosition.x) / level.depth + camPosition.x; y = (y - camPosition.y) / level.depth + camPosition.y; } if (isAdditive) { drawer.drawAdditive(getTexture(), textureSizeX, textureSizeY, originalX, originalY, x, y, angle, tint); } else { drawer.draw(getTexture(), textureSizeX, textureSizeY, originalX, originalY, x, y, angle, tint); } }

Target:
public void draw(GameDrawer drawer, SolGame game) { float x = position.x; float y = position.y; if (level.depth != 1) { Vector2 camPosition = game.getCam().getPosition(); x = (x - camPosition.x) / level.depth + camPosition.x; y = (y - camPosition.y) / level.depth + camPosition.y; } if (isAdditive) { drawer.drawAdditive(texture, textureSizeX, textureSizeY, originalX, originalY, x, y, angle, tint); } else { drawer.draw(texture, textureSizeX, textureSizeY, originalX, originalY, x, y, angle, tint); } }
Source:
public static String[] call(String rootCommand, String[] args, File vagrantDir, Map<String, String> env, int timeout) throws IOException, TimeoutException { String[] envp = (env == null ? null : convertEnvironment(env)); List<String> cmd = new ArrayList<>(); cmd.add(rootCommand); cmd.addAll(Arrays.asList(args)); final Process p = Runtime.getRuntime().exec(cmd.toArray(new String[0]), envp, vagrantDir); InputStream errStream = p.getErrorStream(); InputStream inStream = p.getInputStream(); StreamGobbler inGobbler = new StreamGobbler(inStream); StreamGobbler errGobbler = new StreamGobbler(errStream); new Thread(inGobbler).start(); new Thread(errGobbler).start(); Integer exitCode = ThreadUtils.runWithTimeout(timeout, new Callable<Integer>() { @Override public Integer call() throws Exception { return p.waitFor(); } }); try { if( exitCode == null ) { inGobbler.cancel(); errGobbler.cancel(); throw new TimeoutException(getTimeoutError(inGobbler.getLines(), errGobbler.getLines())); } return inGobbler.getLines(); } finally { inGobbler.cleanup(); errGobbler.cleanup(); } }

Target:
public static String[] call(String rootCommand, String[] args, File vagrantDir, Map<String, String> env, int timeout) throws IOException, TimeoutException { String[] envp = (env == null ? null : convertEnvironment(env)); List<String> cmd = new ArrayList<>(); cmd.add(rootCommand); cmd.addAll(Arrays.asList(args)); final Process p = Runtime.getRuntime().exec(cmd.toArray(new String[0]), envp, vagrantDir); InputStream errStream = p.getErrorStream(); InputStream inStream = p.getInputStream(); Integer exitCode = ThreadUtils.runWithTimeout(timeout, new Callable<Integer>() { @Override public Integer call() throws Exception { return p.waitFor(); } }); try ( StreamGobbler inGobbler = new StreamGobbler(inStream); StreamGobbler errGobbler = new StreamGobbler(errStream)) { new Thread(inGobbler).start(); new Thread(errGobbler).start(); if( exitCode == null ) { inGobbler.cancel(); errGobbler.cancel(); p.destroyForcibly(); throw new TimeoutException(getTimeoutError(inGobbler.getLines(), errGobbler.getLines())); } List<String> ret = inGobbler.getLines(); return (String[]) ret.toArray(new String[ret.size()]); } }