auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> private List<String> getMatchedDCAgainstRegex(List<String> scopes, String regex) { <END> Set<String> DC = new HashSet<String>(); Matcher m; for(String currentScope: scopes) { m = Pattern.compile(regex).matcher(currentScope); while (m.find()) DC.add(m.group().substring(1, m.group().length() - 1).toUpperCase()); } if (DC.size() > 0) return new ArrayList<>(DC); else return null; }</code><technical_language>test case for this method? pass in a list of scopes if returns right DC</technical_language>

Target:
private List<String> getMatchedDCAgainstRegex(List<String> scopes, String regex) { Set<String> DC = new HashSet<String>(); Matcher m; for(String currentScope: scopes) { m = Pattern.compile(regex).matcher(currentScope); while (m.find()) DC.add(m.group().substring(1, m.group().length() - 1).toUpperCase()); } return new ArrayList<>(DC); }
Source:
<code>public void execute(TmfView view) { ITmfZoomToSelectionProvider provider = view.getAdapter(ITmfZoomToSelectionProvider.class); if (provider != null) { <START> TmfTraceManager manager = TmfTraceManager.getInstance(); <END> TmfTimeRange selection = manager.getCurrentTraceContext().getSelectionRange(); ITmfTrace activeTrace = manager.getActiveTrace(); if (activeTrace != null && !selection.getEndTime().equals(selection.getStartTime())) { activeTrace.broadcast(new TmfWindowRangeUpdatedSignal(this, selection)); } } }</code><technical_language>Pin&Clone, press 'Z' in a view shows trace1 active trace is trace2. a method in interface, view implement it</technical_language>

Target:
public void execute(TmfView view) { ITmfZoomToSelectionProvider provider = view.getAdapter(ITmfZoomToSelectionProvider.class); if (provider != null) { provider.zoomToSelection(); } }
Source:
<code>public void onEvent(BrokerEvent event) { if (!workspaceId.equals(event.getWorkspaceId())) { return; } switch (event.getStatus()) { case DONE: finishFuture.complete(event.getTooling()); break; case FAILED: InfrastructureException ex = <START> new InfrastructureException("Broker process failed with error: " + event.getError()); <END> startFuture.completeExceptionally(ex); finishFuture.completeExceptionally(ex); break; case STARTED: startFuture.complete(null); break; default: } }</code><technical_language>include workspace ID in message? in case</technical_language>

Target:
public void onEvent(BrokerEvent event) { if (!workspaceId.equals(event.getWorkspaceId())) { return; } switch (event.getStatus()) { case DONE: List<ChePlugin> tooling = event.getTooling(); if (tooling != null) { finishFuture.complete(tooling); } else { finishFuture.completeExceptionally( new InternalInfrastructureException( format( "Plugin brokering process for workspace `%s` is finished but plugins list is missing", workspaceId))); } break; case FAILED: finishFuture.completeExceptionally( new InfrastructureException( format( "Plugin broking process for workspace %s failed with error: %s", workspaceId, event.getError()))); break; case STARTED: default: } }
Source:
<code>public File gitPrefix() { Holder<File> p = gitPrefix; if (p == null) { <START> String overrideGitPrefio = System.getProperty("jgit.gitprefix"); <END> if (overrideGitPrefio != null) p = new Holder<File>(new File(overrideGitPrefio)); else p = new Holder<File>(discoverGitPrefix()); gitPrefix = p; } return p.value; }</code><technical_language>Typo name? this overrideGitPrefix? SystemReader.getInstance().getProperty() System.getProperty()</technical_language>

Target:
public File gitPrefix() { Holder<File> p = gitPrefix; if (p == null) { String overrideGitPrefix = System.getProperty("jgit.gitprefix"); if (overrideGitPrefix != null) p = new Holder<File>(new File(overrideGitPrefix)); else p = new Holder<File>(discoverGitPrefix()); gitPrefix = p; } return p.value; }
Source:
<code>private void scrollToTop_feedbackEditPage_scrolledCorrectly() { String duration = "400"; JavascriptExecutor javascriptExecutor = (JavascriptExecutor) browser.driver; <START> javascriptExecutor.executeScript(SCROLL_TO_POSITION_SCRIPT, 0, duration); <END> ThreadHelper.waitFor(400); assertEquals((long) 0, javascriptExecutor.executeScript(VERTICAL_SCROLL_VALUE)); }</code><technical_language>previous function variable int scrollPos=400, awhile realise scrollPos=0 in this case, define clearer</technical_language>

Target:
private void scrollToTop_feedbackEditPage_scrolledCorrectly() { int scrollPos = 0; String duration = "400"; JavascriptExecutor javascriptExecutor = (JavascriptExecutor) browser.driver; javascriptExecutor.executeScript(SCROLL_TO_POSITION_SCRIPT, scrollPos, duration); ThreadHelper.waitFor(400); assertEquals((long) 0, javascriptExecutor.executeScript(VERTICAL_SCROLL_VALUE)); }
Source:
<code>public void addInstructions(CodeWriter code) throws CodegenException { if (mth.contains(AType.JADX_ERROR) || mth.contains(AFlag.INCONSISTENT_CODE) || mth.getRegion() == null) { code.startLine(" "); code.startLine("throw new UnsupportedOperationException(\"Method not decompiled: ") <START> .add(mth.getParentClass().getPackage()) <END> .add(".") .add(mth.getAlias()) .add("(") .add(Utils.listToString(mth.getMethodInfo().getArgumentsTypes())) .add("):") .add(mth.getMethodInfo().getReturnType().toString()) .add("\");"); } else { RegionGen regionGen = new RegionGen(this); regionGen.makeRegion(code, mth.getRegion()); } }</code><technical_language>forgot parent class name aliased name</technical_language>

Target:
public void addInstructions(CodeWriter code) throws CodegenException { if (mth.contains(AType.JADX_ERROR) || mth.contains(AFlag.INCONSISTENT_CODE) || mth.getRegion() == null) { code.startLine(" "); ClassInfo clsAlias = mth.getParentClass().getAlias(); code.startLine("throw new UnsupportedOperationException(\"Method not decompiled: ") .add(clsAlias.makeFullClsName(clsAlias.getShortName(), true)) .add(".") .add(mth.getAlias()) .add("(") .add(Utils.listToString(mth.getMethodInfo().getArgumentsTypes())) .add("):") .add(mth.getMethodInfo().getReturnType().toString()) .add("\");"); } else { RegionGen regionGen = new RegionGen(this); regionGen.makeRegion(code, mth.getRegion()); } }
Source:
<code>protected CacheEntry<K, C> getNextFromIterator() { CacheEntry<K, V> returnedEntry = null; CacheEntry<K, V> entry; while (returnedEntry == null && !contextEntries.isEmpty() && (entry = contextEntries.remove(0)) != null) { seenContextKeys.add(entry.getKey()); if (!ctx.isEntryRemovedInContext(entry.getKey()) && !entry.isNull()) { returnedEntry = filterEntry(entry); } } if (returnedEntry == null) { while (realIterator.hasNext()) { CacheEntry<K, V> iteratedEntry = realIterator.next(); CacheEntry contextEntry; if ((contextEntry = ctx.lookupEntry(iteratedEntry.getKey())) != null) { if (seenContextKeys.add(contextEntry.getKey()) && !contextEntry.isRemoved() && (returnedEntry = filterEntry(contextEntry)) != null) { break; } } else { return (CacheEntry<K, C>) iteratedEntry; } } } if (returnedEntry == null) { for (CacheEntry lookedUpEntry : ctx.getLookedUpEntries().values()) { <START> if (seenContextKeys.add(lookedUpEntry.getKey()) && !lookedUpEntry.isRemoved() && !lookedUpEntry.isNull()) { <END> if (returnedEntry == null) { returnedEntry = lookedUpEntry; } else { contextEntries.add(lookedUpEntry); } } } } if (returnedEntry != null && converter != null) { C newValue = converter.convert(returnedEntry.getKey(), returnedEntry.getValue(), returnedEntry.getMetadata()); returnedEntry = entryFactory.create(returnedEntry); returnedEntry.setValue((V) newValue); } return (CacheEntry<K, C>) returnedEntry; }</code><technical_language>line 92 above, checking for isNull()</technical_language>

Target:
protected CacheEntry<K, C> getNextFromIterator() { CacheEntry<K, V> returnedEntry = null; CacheEntry<K, V> entry; while (returnedEntry == null && !contextEntries.isEmpty() && (entry = contextEntries.remove(0)) != null) { seenContextKeys.add(entry.getKey()); if (!ctx.isEntryRemovedInContext(entry.getKey()) && !entry.isNull()) { returnedEntry = filterEntry(entry); } } if (returnedEntry == null) { while (realIterator.hasNext()) { CacheEntry<K, V> iteratedEntry = realIterator.next(); CacheEntry contextEntry; if ((contextEntry = ctx.lookupEntry(iteratedEntry.getKey())) != null) { if (seenContextKeys.add(contextEntry.getKey()) && !contextEntry.isRemoved() && !contextEntry.isNull() && (returnedEntry = filterEntry(contextEntry)) != null) { break; } } else { return (CacheEntry<K, C>) iteratedEntry; } } } if (returnedEntry == null) { for (CacheEntry lookedUpEntry : ctx.getLookedUpEntries().values()) { if (seenContextKeys.add(lookedUpEntry.getKey()) && !lookedUpEntry.isRemoved() && !lookedUpEntry.isNull()) { if (returnedEntry == null) { returnedEntry = lookedUpEntry; } else { contextEntries.add(lookedUpEntry); } } } } if (returnedEntry != null && converter != null) { C newValue = converter.convert(returnedEntry.getKey(), returnedEntry.getValue(), returnedEntry.getMetadata()); returnedEntry = entryFactory.create(returnedEntry); returnedEntry.setValue((V) newValue); } return (CacheEntry<K, C>) returnedEntry; }
Source:
<code>private Resource handleFileProtocol(String fileURL) { File file; if (fileURL.startsWith(FileSystem.FILE_PROTOCOL_AND_CONF)) { file = new File(directoryProvider.getConfDirectory() + "/" + fileURL.substring(FileSystem.FILE_PROTOCOL_AND_CONF.length())); } else if (fileURL.startsWith(FileSystem.FILE_PROTOCOL_AND_VAR)) { file = new File(directoryProvider.getVarDirectory() + "/" + fileURL.substring(FileSystem.FILE_PROTOCOL_AND_VAR.length())); } else if (fileURL.startsWith(FileSystem.FILE_PROTOCOL_ABSOLUTE)) { <START> file = new File(directoryProvider.getAbsoluteDirectory() + fileURL.substring(FileSystem.FILE_PROTOCOL_ABSOLUTE.length())); <END> } else { file = new File(directoryProvider.getRootDirectory() + "/" + fileURL.substring(FileSystem.FILE_PROTOCOL.length())); } return new FileSystemResource(file); }</code><technical_language>IIRC FILE_PROTOCOL_ABSOLUTE includes trailing slashes</technical_language>

Target:
private Resource handleFileProtocol(String fileURL) { File file = interpretPath(fileURL); return new FileSystemResource(file); }
Source:
<code>public int getId(String value) { <START> if (value == null) { <END> return -1; } final Integer id = falseIds.get(value); return id == null ? -1 : id; }</code><technical_language>null values treated empty string</technical_language>

Target:
public int getId(String value) { if (value == null) { value = ""; } final Integer id = falseIds.get(value); return id == null ? -1 : id; }
Source:
<code>public GoGoDuck(Catalog catalog, String profile, String subset, String outputFile, String format, GoGoDuckConfig goGoDuckConfig) { this.profile = profile; this.subset = subset; this.outputFile = new File(outputFile).toPath(); this.format = format; this.limit = goGoDuckConfig.getFileLimit(); this.baseTmpDir = new File(System.getProperty("java.io.tmpdir")).toPath(); this.userLog = new UserLog(); this.indexReader = new FeatureSourceIndexReader(this.userLog, catalog); this.goGoDuckConfig = goGoDuckConfig; Map<String, String> urlMangling = new HashMap<>(); <START> urlMangling.put(goGoDuckConfig.getUrlSubstitutionKey(), goGoDuckConfig.getUrlSubstitutionValue()); <END> this.urlMangler = new URLMangler(urlMangling); }</code><technical_language>more</technical_language>

Target:
public GoGoDuck(Catalog catalog, String profile, String subset, String outputFile, String format, GoGoDuckConfig goGoDuckConfig) { this.profile = profile; this.subset = subset; this.outputFile = new File(outputFile).toPath(); this.format = format; this.limit = goGoDuckConfig.getFileLimit(); this.baseTmpDir = new File(System.getProperty("java.io.tmpdir")).toPath(); this.userLog = new UserLog(); this.indexReader = new FeatureSourceIndexReader(this.userLog, catalog); this.goGoDuckConfig = goGoDuckConfig; setUrlMangler(profile, goGoDuckConfig); }
Source:
<code>public void afterMethod() throws Exception { for (String db : _allDBs) { _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, db); } _allDBs.clear(); <START> Thread.sleep(100); <END> ZkHelixClusterVerifier _clusterVerifier = new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR) .setDeactivatedNodeAwareness(true).setResources(_allDBs) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); try { Assert.assertTrue(_clusterVerifier.verifyByPolling()); } finally { _clusterVerifier.close(); } Assert.assertEquals( _gSetupTool.getClusterManagementTool().getResourcesInCluster(CLUSTER_NAME).size(), 0); Assert.assertTrue(_assignmentMetadataStore.getBestPossibleAssignment().isEmpty()); Assert.assertTrue(_assignmentMetadataStore.getBaseline().isEmpty()); }</code><technical_language>This is necessary anymore</technical_language>

Target:
public void afterMethod() throws Exception { for (String db : _allDBs) { _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, db); } _allDBs.clear(); ZkHelixClusterVerifier _clusterVerifier = new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR) .setDeactivatedNodeAwareness(true).setResources(_allDBs) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); try { Assert.assertTrue(_clusterVerifier.verifyByPolling()); } finally { _clusterVerifier.close(); } Assert.assertEquals( _gSetupTool.getClusterManagementTool().getResourcesInCluster(CLUSTER_NAME).size(), 0); Assert.assertTrue(_assignmentMetadataStore.getBestPossibleAssignment().isEmpty()); Assert.assertTrue(_assignmentMetadataStore.getBaseline().isEmpty()); }
Source:
<code>protected void configureModule() { add( StatusAction.class, ApplyLicenseAction.class, PreviewAction.class, <START> EditionsWs.class, <END> UninstallAction.class); }</code><technical_language>good practice: actions WS injected grouped</technical_language>

Target:
protected void configureModule() { add( StatusAction.class, ApplyLicenseAction.class, PreviewAction.class, FormDataAction.class, UninstallAction.class, EditionsWs.class); }
Source:
<code>public long tryReserveForCacheOnUpdate(K key, Data keyData) { checkAvailable(); if (evictionDisabled && evictionChecker.isEvictionRequired() && !containsRecordKey(key)) { return NOT_RESERVED; } long reservationId = nextReservationId(); R reservedRecord = reserveForCacheOnUpdate(key, keyData, reservationId); <START> return reservedRecord == null ? NOT_RESERVED <END> : (reservedRecord.getReservationId() == reservationId ? reservationId : NOT_RESERVED); }</code><technical_language>check for null in tryReserveForUpdate</technical_language>

Target:
public long tryReserveForCacheOnUpdate(K key, Data keyData) { return tryReserve0(key, keyData, true); }
Source:
<code>public synchronized void forceNodeShutdown() { LOGGER.entering(); if (!isSupportedOnNode(NodeForceRestartServlet.class)) { LOGGER.exiting(); return; } stopNodeRecycleThread(); for (TestSlot slot : getTestSlots()) { if (slot.getSession() != null) { <START> totalSessionsCompleted++; <END> proxyLogger.info("Timing out session #" + totalSessionsCompleted + " (" + slot.getSession().toString() + ")"); getRegistry().forceRelease(slot, SessionTerminationReason.TIMEOUT); } } List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair(NodeForceRestartServlet.TOKEN_PARAMETER, NodeForceRestartServlet.CONFIGURED_TOKEN_VALUE)); HttpResponse response = sendToNodeServlet(NodeForceRestartServlet.class, nvps); if (response == null) { proxyLogger.warning("Node " + getId() + " failed to shutdown and returned a null response."); LOGGER.exiting(false); return; } final int responseStatusCode = response.getStatusLine().getStatusCode(); if (responseStatusCode != HttpStatus.SC_OK) { proxyLogger.info("Node " + getId() + " did not shutdown and returned HTTP " + responseStatusCode); LOGGER.exiting(false); return; } proxyLogger.info("Node " + getId() + " shutdown successfully."); getRegistry().removeIfPresent(this); LOGGER.exiting(); }</code><technical_language>incrementing this here</technical_language>

Target:
public synchronized void forceNodeShutdown() { LOGGER.entering(); stopNodeRecycleThread(); if (!isSupportedOnNode(NodeForceRestartServlet.class)) { LOGGER.exiting(); return; } for (TestSlot slot : getTestSlots()) { if (slot.getSession() != null) { totalSessionsCompleted++; proxyLogger.info("Timing out session #" + totalSessionsCompleted + " (" + slot.getSession().toString() + ")"); getRegistry().forceRelease(slot, SessionTerminationReason.TIMEOUT); } } List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair(NodeForceRestartServlet.TOKEN_PARAMETER, NodeForceRestartServlet.CONFIGURED_TOKEN_VALUE)); HttpResponse response = sendToNodeServlet(NodeForceRestartServlet.class, nvps); if (response == null) { proxyLogger.warning("Node " + getId() + " failed to shutdown and returned a null response."); LOGGER.exiting(false); return; } final int responseStatusCode = response.getStatusLine().getStatusCode(); if (responseStatusCode != HttpStatus.SC_OK) { proxyLogger.info("Node " + getId() + " did not shutdown and returned HTTP " + responseStatusCode); LOGGER.exiting(false); return; } proxyLogger.info("Node " + getId() + " shutdown successfully."); getRegistry().removeIfPresent(this); LOGGER.exiting(); }
Source:
<code>protected void writeObject(Object object, JsonGenerator generator) throws IOException { try (Data.TraverseCallback callback = createTraverseCallback(generator)) { Data.traverse(object, callback); <START> generator.flush(); <END> } }</code><technical_language>point is consistency codecs. Protobuf codec assumes callback handles flush, while this code call explicitly. consistent set expectation traverse callback handle flushing/closing generator. codec's close traverse callback</technical_language>

Target:
protected void writeObject(Object object, JsonGenerator generator) throws IOException { try (Data.TraverseCallback callback = createTraverseCallback(generator)) { Data.traverse(object, callback); } }
Source:
<code>public RemoteFile readFileWithMode(String uri, String ref, String path) throws GitAPIException, IOException { File dir = FileUtils.createTempDir("jgit_", ".git", null); try (Git git = Git.cloneRepository().setBare(true).setDirectory(dir) .setURI(uri).call()) { Repository repo = git.getRepository(); return <START> readFileWithMode(repo, ref, <END> path); } finally { FileUtils.delete(dir, FileUtils.RECURSIVE); } }</code><technical_language>inline this</technical_language>

Target:
public RemoteFile readFileWithMode(String uri, String ref, String path) throws GitAPIException, IOException { File dir = FileUtils.createTempDir("jgit_", ".git", null); try (Git git = Git.cloneRepository().setBare(true).setDirectory(dir) .setURI(uri).call()) { Repository repo = git.getRepository(); ObjectId refCommitId = sha1(uri, ref); if (refCommitId == null) { throw new InvalidRefNameException(MessageFormat .format(JGitText.get().refNotResolved, ref)); } RevCommit commit = repo.parseCommit(refCommitId); TreeWalk tw = TreeWalk.forPath(repo, path, commit.getTree()); return new RemoteFile( tw.getObjectReader().open(tw.getObjectId(0)) .getCachedBytes(Integer.MAX_VALUE), tw.getFileMode(0)); } finally { FileUtils.delete(dir, FileUtils.RECURSIVE); } }
Source:
<code>public void run(final List<EventListenerDescriptor> listeners, EventBundle bundle) { if (bundle instanceof ReconnectedEventBundleImpl) { EventBundle connectedBundle = new EventBundleImpl(); Map<String, CoreSession> sessions = new HashMap<String, CoreSession>(); <START> boolean txStarted = false; <END> if (TransactionHelper.isNoTransaction()) { txStarted = TransactionHelper.startTransaction(); } List<Event> events = ((ReconnectedEventBundleImpl)bundle).getReconnectedEvents(); for (Event event : events) { connectedBundle.push(event); CoreSession session = event.getContext().getCoreSession(); if (!(sessions.keySet().contains(session.getRepositoryName()))) { sessions.put(session.getRepositoryName(), session); } } if (txStarted) { TransactionHelper.commitOrRollbackTransaction(); sessions.values().forEach(CoreSession::close); } bundle = connectedBundle; } for (EventListenerDescriptor listener : listeners) { EventBundle filtered = listener.filterBundle(bundle); if (filtered.isEmpty()) { continue; } getWorkManager().schedule(new ListenerWork(listener, filtered), true); } }</code><technical_language>new TransactionHelper.runInTransaction methods properly deal this including exception management for rollback</technical_language>

Target:
public void run(final List<EventListenerDescriptor> listeners, EventBundle bundle) { if (!(bundle instanceof ReconnectedEventBundleImpl)) { scheduleListeners(listeners, bundle); } else { final EventBundle tmpBundle = bundle; TransactionHelper.runInTransaction(() -> { EventBundle connectedBundle = new EventBundleImpl(); Map<String, CoreSession> sessions = new HashMap<>(); List<Event> events = ((ReconnectedEventBundleImpl)tmpBundle).getReconnectedEvents(); for (Event event : events) { connectedBundle.push(event); CoreSession session = event.getContext().getCoreSession(); if (!(sessions.keySet().contains(session.getRepositoryName()))) { sessions.put(session.getRepositoryName(), session); } } sessions.values().forEach(CoreSession::close); scheduleListeners(listeners, connectedBundle); }); } }
Source:
<code>private static EventFiringWebDriver getChromeInstance() { String chromeBinaryName; String OSName = System.getProperty("os.name").toUpperCase(); if (OSName.contains("WINDOWS")) { chromeBinaryName = "chromedriver.exe"; File chromeBinary = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + chromeBinaryName ); System.setProperty("webdriver.chrome.driver", chromeBinary.getAbsolutePath()); } <START> else if (OSName.contains("MAC")) { <END> chromeBinaryName = "chromedriver"; File chromeBinary = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + "ChromeDriver_OSX" + File.separator + chromeBinaryName ); System.setProperty("webdriver.chrome.driver", chromeBinary.getAbsolutePath()); } if (browserName.equals("CHROMEMOBILE")) { ChromeOptions options = new ChromeOptions(); options.addArguments( "--user-agent="+ "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) " + "AppleWebKit/420+ (KHTML, like Gecko) " + "Version/3.0 Mobile/1A543a Safari/419.3" ); return new EventFiringWebDriver(new ChromeDriver(options)); } return new EventFiringWebDriver(new ChromeDriver(caps)); }</code><technical_language>is a lot of code is for "WINDOWS", try this: chormeBinaryName = (OSName.contains("MAC")) ? "chromedriver" : "chromedriver.exe"; reuse this code for systems: File chromeBinary = new File ( - "." + File.separator - + "src" + File.separator - + "test" + File.separator - + "resources" + File.separator - + "ChromeDriver" + File.separator - + chromeBinaryName - );</technical_language>

Target:
private static EventFiringWebDriver getChromeInstance() { String chromeBinaryName; String OSName = System.getProperty("os.name").toUpperCase(); chromeBinaryName = (OSName.contains("MAC")) ? "chromedriver" : "chromedriver.exe"; File chromeBinary = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + chromeBinaryName ); System.setProperty("webdriver.chrome.driver", chromeBinary.getAbsolutePath()); if (browserName.equals("CHROMEMOBILE")) { ChromeOptions options = new ChromeOptions(); options.addArguments( "--user-agent="+ "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) " + "AppleWebKit/420+ (KHTML, like Gecko) " + "Version/3.0 Mobile/1A543a Safari/419.3" ); return new EventFiringWebDriver(new ChromeDriver(options)); } return new EventFiringWebDriver(new ChromeDriver(caps)); }
Source:
<code>public TargetAnnotationCollection createTargetAnnotationCollection(final DataLine dataLine) { if (annotationSet.size() == 0) { return TargetAnnotationCollection.NO_ANNOTATION; } <START> return new TargetAnnotationCollection() { <END> @Override public int size() { return annotationSet.size(); } @Override public boolean hasAnnotation(final TargetAnnotation annotation) { return annotationToColumnIndex[annotation.ordinal()] >= 0; } @Override public double getDouble(final TargetAnnotation annotation) { if (hasAnnotation(annotation)) { return dataLine.getDouble(annotationToColumnIndex[annotation.ordinal()], formatAnnotationExceptionFactory.apply(dataLine)); } else { throw formatAnnotationExceptionFactory.apply(dataLine).apply( String.format("not found expected target annotation '%s' in input", annotation.column)); } } @Override public String get(final TargetAnnotation annotation) { if (hasAnnotation(annotation)) { return dataLine.get(annotationToColumnIndex[annotation.ordinal()]); } else { throw formatAnnotationExceptionFactory.apply(dataLine).apply( String.format("not found expected target annotation '%s' in input", annotation.column)); } } @Override public Set<TargetAnnotation> annotationSet() { return annotationSet; } }; }</code><technical_language>purpose of returning anonymous class instead of implementation of TargetAnnotationCollection</technical_language>

Target:
public TargetAnnotationCollection createTargetAnnotationCollection(final DataLine dataLine) { if (annotationSet.size() == 0) { return TargetAnnotationCollection.NO_ANNOTATION; } else { return new DataLineTargetAnnotationCollection(dataLine); } }
Source:
<code>private <START> List performVmCheckpointsOperation(VDSCommandType <END> vdsCommandType, VdsAndVmIDVDSParametersBase params) { VDSReturnValue vdsRetVal; try { vdsRetVal = runVdsCommand(vdsCommandType, params); if (!vdsRetVal.getSucceeded()) { EngineException engineException = new EngineException(); engineException.setVdsError(vdsRetVal.getVdsError()); throw engineException; } } catch (EngineException e) { log.error("Failed to execute '{}': {}", vdsCommandType, e); throw e; } return (List) vdsRetVal.getReturnValue(); }</code><technical_language>a List of specific objects, "List"</technical_language>

Target:
private List<Guid> performVmCheckpointsOperation(VDSCommandType vdsCommandType, VdsAndVmIDVDSParametersBase params) { VDSReturnValue vdsRetVal; try { vdsRetVal = runVdsCommand(vdsCommandType, params); if (!vdsRetVal.getSucceeded()) { EngineException engineException = new EngineException(); engineException.setVdsError(vdsRetVal.getVdsError()); throw engineException; } } catch (EngineException e) { log.error("Failed to execute '{}': {}", vdsCommandType, e); throw e; } return (List<Guid>) vdsRetVal.getReturnValue(); }
Source:
<code>@Nonnull protected Policy parsePolicy() { Policy policy = new Policy(this.origin); while (this.hasNext()) { if (this.hasNext(PolicySeparatorToken.class)) break; if (this.eat(DirectiveSeparatorToken.class)) continue; try { <START> policy.addDirective(this.parseDirective()); <END> } catch (IllegalArgumentException e) { this.warn(this.tokens[index - 1], e.getMessage()); } catch (DirectiveParseException ignored) { } } return policy; }</code><technical_language>need check adding directive policy a directive of type</technical_language>

Target:
@Nonnull protected Policy parsePolicy() { Policy policy = new Policy(this.origin); while (this.hasNext()) { if (this.hasNext(PolicySeparatorToken.class)) break; if (this.eat(DirectiveSeparatorToken.class)) continue; try { Directive<? extends DirectiveValue> directive = this.parseDirective(); if (policy.getDirectiveByType(directive.getClass()) == null) { policy.addDirective(directive); } else { this.warn(this.tokens[this.index - 2], "Policy contains more than one " + directive.name + " directive. All but the first instance will be ignored."); } } catch (DirectiveParseException ignored) { } } return policy; }
Source:
<code>public Response intercept(Chain chain) throws IOException { Tags.AttemptSpan attemptSpanTag = chain.request().tag(Tags.AttemptSpan.class); <START> if (attemptSpanTag == null) { <END> return chain.proceed(chain.request()); } try { return addHeaders.intercept(chain); } finally { DetachedSpan waitForBody = chain.request().tag(Tags.AttemptSpan.class) .attemptSpan() .childDetachedSpan("OkHttp: wait-for-body", SpanType.CLIENT_OUTGOING); chain.request().tag(Tags.SettableWaitForBodySpan.class).setWaitForBodySpan(waitForBody); } }</code><technical_language>Is invariant imagined author of this code is request AttemptSpan tag. I try restore this invariant minimally explain some requests a tag others don't</technical_language>

Target:
public Response intercept(Chain chain) throws IOException { Tags.AttemptSpan attemptSpanTag = chain.request().tag(Tags.AttemptSpan.class); if (attemptSpanTag == null) { return chain.proceed(chain.request()); } try { return addHeaders.intercept(chain); } finally { DetachedSpan waitForBody = attemptSpanTag .attemptSpan() .childDetachedSpan("OkHttp: wait-for-body", SpanType.CLIENT_OUTGOING); chain.request().tag(Tags.SettableWaitForBodySpan.class).setWaitForBodySpan(waitForBody); } }
Source:
<code>public List<Timeline> getTimelines(final String eventTypeName) throws AccessDeniedException, UnableProcessException, TimelineException, NotFoundException { if (!adminService.isAdmin(AuthorizationService.Operation.READ)) { throw new AccessDeniedException(AuthorizationService.Operation.ADMIN, new ResourceImpl<EventType>(eventTypeName, ResourceImpl.EVENT_TYPE_RESOURCE, null, null)); } try { final EventType eventType = eventTypeCache.getEventType(eventTypeName); <START> authorizationValidator.authorizeEventTypeView(eventType); <END> return timelineDbRepository.listTimelinesOrdered(eventType.getName()); } catch (final NoSuchEventTypeException e) { throw new NotFoundException("EventType \"" + eventTypeName + "\" does not exist"); } catch (final InternalNakadiException e) { throw new TimelineException("Could not get event type: " + eventTypeName, e); } }</code><technical_language>get-timelines well. allowed Nakadi admins, I sense check if event-type-view is allowed</technical_language>

Target:
public List<Timeline> getTimelines(final String eventTypeName) throws AccessDeniedException, UnableProcessException, TimelineException, NotFoundException { if (!adminService.isAdmin(AuthorizationService.Operation.READ)) { throw new AccessDeniedException(AuthorizationService.Operation.ADMIN, new ResourceImpl<EventType>(eventTypeName, ResourceImpl.EVENT_TYPE_RESOURCE, null, null)); } try { final EventType eventType = eventTypeCache.getEventType(eventTypeName); return timelineDbRepository.listTimelinesOrdered(eventType.getName()); } catch (final NoSuchEventTypeException e) { throw new NotFoundException("EventType \"" + eventTypeName + "\" does not exist"); } catch (final InternalNakadiException e) { throw new TimelineException("Could not get event type: " + eventTypeName, e); } }
Source:
<code>protected String localizeText(String key) { String result = ""; <START> if (this.i18nProvider != null && this.locale != null && I18nUtil.isConstant(key)) { <END> result = this.i18nProvider.getText(this.bundleContext.getBundle(), I18nUtil.stripConstant(key), "", this.locale); } return result; }</code><technical_language>null? a "1..1" relation, rely them</technical_language>

Target:
protected String localizeText(String key) { String result = ""; if (I18nUtil.isConstant(key)) { result = this.i18nProvider.getText(this.bundleContext.getBundle(), I18nUtil.stripConstant(key), "", this.localeProvider.getLocale()); } return result; }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); <START> InitialContext ctx = null; <END> if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryParametersBase parameters = new VdcQueryParametersBase(); parameters.setSessionId(engineSession); VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, parameters); if (!returnValue.getSucceeded()) { httpSession.removeAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); } else { httpSession.setAttribute(FiltersHelper.Constants.SESSSION_USER_KEY, returnValue.getReturnValue()); } } finally { ctx.close(); } } } chain.doFilter(request, response); } catch (Exception ex) { String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }</code><technical_language>is this ^ here</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean exceptionOccurred = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryParametersBase parameters = new VdcQueryParametersBase(); parameters.setSessionId(engineSession); VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, parameters); if (!returnValue.getSucceeded()) { httpSession.removeAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); } else { request.setAttribute(FiltersHelper.Constants.REQUEST_USER_KEY, returnValue.getReturnValue()); } } finally { ctx.close(); } } } } catch (Exception ex) { exceptionOccurred = true; String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (!exceptionOccurred) { chain.doFilter(request, response); } }
Source:
<code>public SolrClientAdapter(String core, Creator creator) { Validate.notNull(core, "invalid null core"); Validate.notNull(creator, "invalid null creator"); LOGGER.debug("Solr({}): Creating a Solr client adapter", core); this.core = core; this.creator = creator; try { setClient(new UnavailableSolrClient("initializing '" + core + "' core"), true); <START> } catch (IOException e) { END> } }</code><technical_language>question: this happen, put a log in case code is changed happen</technical_language>

Target:
public SolrClientAdapter(String core, Creator creator) { this(core, creator, Failsafe::with, Failsafe::with); }
Source:
<code>public boolean isAutosizingConfig(String configParam) { switch (configParam) { <START> case JOB_AUTOSIZING_CONTAINER_COUNT: case JOB_AUTOSIZING_CONTAINER_MAX_CORES: case JOB_AUTOSIZING_CONTAINER_MAX_HEAP_MB: case JOB_AUTOSIZING_CONTAINER_MEMORY_MB: case JOB_AUTOSIZING_CONTAINER_THREAD_POOL_SIZE: <END> return true; default: return false; } }</code><technical_language>If adds a new autosizing config, obvious remember update this method, especially is a couple lines config key declaration. a couple suggestions help: 1. Create a new enum class in autosizing config is a in enum. Then, Enum.values() create a set of autosizing configs. This is nice, needs add enum value, code automatically picks up. 2. Create a static Set of autosizing keys, declare set a static variable right next declare autosizing constants. is a chance of forgetting update set, close in proximity declarations. 3. Change implementation of this method check config key matches a prefix (e.g. job.autosizing). "convention"-y, need update this implementation long follow prefix pattern</technical_language>

Target:
public boolean isAutosizingConfig(String configParam) { return configParam.startsWith(JOB_AUTOSIZING_CONFIG_PREFIX); }
Source:
<code>protected void onInit() throws ServletException { Client client = getClient(); Publisher<RequestEvent> eventPublisher = getConfig().getInstance(EVENT_PUBLISHER); AccountStoreResolver accountStoreResolver = getConfig().getInstance(ACCOUNT_STORE_RESOLVER); VerifyController controller = new VerifyController(); controller.setNextUri(getConfig().getVerifyNextUrl()); controller.setLogoutUri(getConfig().getLogoutUrl()); controller.setLoginUri(getConfig().getLoginUrl()); controller.setAccountStoreResolver(accountStoreResolver); controller.setView("stormpath/verify"); <START> controller.setNextUri("stormpath/verifyComplete"); <END> controller.setAutoLogin(getConfig().getRegisterAutoLogin()); controller.setClient(client); controller.setEventPublisher(eventPublisher); controller.init(); setController(controller); super.onInit(); }</code><technical_language>nextUri configurable</technical_language>

Target:
protected void onInit() throws ServletException { Client client = getClient(); Publisher<RequestEvent> eventPublisher = getConfig().getInstance(EVENT_PUBLISHER); Saver<AuthenticationResult> authenticationResultSaver = getConfig().getInstance(ACCOUNT_SAVER_PROP); AccountStoreResolver accountStoreResolver = getConfig().getInstance(ACCOUNT_STORE_RESOLVER); MessageSource messageSource = getConfig().getInstance(MESSAGE_SOURCE); Resolver<Locale> localeResolver = getConfig().getInstance(LOCALE_RESOLVER); VerifyController controller = new VerifyController(); controller.setUri(getConfig().getVerifyUrl()); controller.setNextUri(getConfig().getVerifyNextUrl()); controller.setLogoutUri(getConfig().getLogoutUrl()); controller.setLoginUri(getConfig().getLoginUrl()); controller.setAccountStoreResolver(accountStoreResolver); controller.setView("stormpath/verify"); controller.setAutoLogin(getConfig().getRegisterAutoLogin()); controller.setClient(client); controller.setEventPublisher(eventPublisher); controller.setAuthenticationResultSaver(authenticationResultSaver); controller.setMessageSource(messageSource); controller.setLocaleResolver(localeResolver); controller.init(); setController(controller); super.onInit(); }
Source:
<code>public static void ingest(AccumuloClient c, Opts opts, BatchWriterOpts batchWriterOpts) throws MutationsRejectedException, IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException { <START> ingest(c, FileSystem.get(new Configuration()), opts, batchWriterOpts); <END> }</code><technical_language>possibly cast AccumloClient a context get hadoopConfig</technical_language>

Target:
public static void ingest(AccumuloClient c, Opts opts, BatchWriterOpts batchWriterOpts) throws MutationsRejectedException, IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException { ClientContext cc = (ClientContext) c; ingest(c, FileSystem.get(cc.getHadoopConf()), opts, batchWriterOpts); }
Source:
<code>private void generateXpath() { if (tree.getLastSelectedPathComponent() instanceof DetailAST) { try { final FileText fileText = new FileText(file, StandardCharsets.UTF_8.name()); final DetailAST rootAST = (DetailAST) tree.getModel().getRoot(); final DetailAST ast = (DetailAST) tree.getLastSelectedPathComponent(); final int defaultTabWidth = 4; final XpathQueryGenerator queryGenerator = new XpathQueryGenerator(rootAST, ast.getLineNo(), ast.getColumnNo(), fileText, defaultTabWidth); xpathEditor.setText(queryGenerator.generateXpathQuery(ast)); } catch (IOException ex) { xpathEditor.setText(ex.getMessage()); } } else { <START> xpathEditor.setText("Xpath is not supported yet forr javadoc nodes"); <END> } }</code><technical_language>fix typo, Travis complain this</technical_language>

Target:
private void generateXpath() { if (tree.getLastSelectedPathComponent() instanceof DetailAST) { final DetailAST ast = (DetailAST) tree.getLastSelectedPathComponent(); final int beginPos = 4; String xpath = XpathQueryGenerator.generateXpathQuery(ast); final int length = xpath.length(); xpath = xpath.substring(beginPos, length); xpathEditor.setText(xpath); } else { xpathEditor.setText("Xpath is not supported yet for javadoc nodes"); } }
Source:
<code>protected Object resolve(Object unresolved) { if (unresolved == null) { return null; } else if (unresolved == INTERRUPTED) { return new AltResult(new InterruptedException(invocation.op.getClass().getSimpleName() + " was interrupted. " + invocation)); } else if (unresolved == CALL_TIMEOUT) { return newOperationTimeoutException(false); } else if (unresolved == HEARTBEAT_TIMEOUT) { return newOperationTimeoutException(true); } else if (unresolved.getClass() == Packet.class) { unresolved = invocation.context.serializationService.toObject(unresolved); <START> if (unresolved instanceof NormalResponse) { <END> unresolved = ((NormalResponse) unresolved).getValue(); } } Object value = unresolved; if (deserialize && value instanceof Data) { value = invocation.context.serializationService.toObject(value); if (value == null) { return null; } } if (isErroneousState(value)) { Throwable throwable = ((ErrorResponse) value).getCause(); if (invocation.shouldFailOnIndeterminateOperationState() && (throwable instanceof MemberLeftException)) { String message = invocation + " failed because the target has left the cluster before response is received"; throwable = new IndeterminateOperationStateException(message, throwable); } fixAsyncStackTrace(throwable, Thread.currentThread().getStackTrace()); return exceptionally(throwable); } return value; }</code><technical_language>In case unresolved is instance of NormalResponse ? this condition hold</technical_language>

Target:
protected Object resolve(Object unresolved) { if (unresolved == null) { return null; } else if (unresolved == INTERRUPTED) { return new AltResult(new InterruptedException(invocation.op.getClass().getSimpleName() + " was interrupted. " + invocation)); } else if (unresolved == CALL_TIMEOUT) { return newOperationTimeoutException(false); } else if (unresolved == HEARTBEAT_TIMEOUT) { return newOperationTimeoutException(true); } else if (unresolved.getClass() == Packet.class) { unresolved = invocation.context.serializationService.toObject(unresolved); if (unresolved instanceof NormalResponse) { unresolved = ((NormalResponse) unresolved).getValue(); } } Object value = unresolved; if (deserialize && value instanceof Data) { value = invocation.context.serializationService.toObject(value); if (value == null) { return null; } } if (isErroneousState(value)) { Throwable throwable = ((ErrorResponse) value).getCause(); if (invocation.shouldFailOnIndeterminateOperationState() && (throwable instanceof MemberLeftException)) { String message = invocation + " failed because the target has left the cluster before response is received"; throwable = new IndeterminateOperationStateException(message, throwable); } fixAsyncStackTrace(throwable, Thread.currentThread().getStackTrace()); return new AltResult(throwable); } return value; }
Source:
<code>private void setValue(final DTCellValue52 cell, final DataType.DataTypes dataType) { switch (dataType) { case STRING: if (isTheRealCellValueString(sourceColumnIndex) && cell.getStringValue() != null) { if (cell.getStringValue() != null && !cell.getStringValue().isEmpty()) { xlsRow.createCell(targetColumnIndex) .setCellValue(String.format("\"%s\"", fixStringValue(cell))); } } else { if (Objects.equals(DataType.DataTypes.STRING, cell.getDataType())) { xlsRow.createCell(targetColumnIndex) .setCellValue(cell.getStringValue()); } else { setValue(cell, cell.getDataType()); } } break; case NUMERIC: case NUMERIC_BIGDECIMAL: case NUMERIC_BIGINTEGER: case NUMERIC_BYTE: case NUMERIC_DOUBLE: case NUMERIC_FLOAT: case NUMERIC_INTEGER: case NUMERIC_LONG: case NUMERIC_SHORT: final Number numericValue = cell.getNumericValue(); if (numericValue != null) { xlsRow.createCell(targetColumnIndex) .setCellValue(numericValue.toString()); } break; case DATE: final Date dateValue = cell.getDateValue(); if (dateValue != null) { final SimpleDateFormat formatter = new SimpleDateFormat(getDateFormat()); xlsRow.createCell(targetColumnIndex) <START> .setCellValue(formatter.format(dateValue)); <END> } break; case BOOLEAN: final Boolean booleanValue = cell.getBooleanValue(); if (booleanValue != null) { xlsRow.createCell(targetColumnIndex) .setCellValue(booleanValue); } break; } }</code><technical_language>need .setCellValue(String.format("\"%s\"", formatter.format(dateValue))); validation of converted fails</technical_language>

Target:
private void setValue(final DTCellValue52 cell, final DataType.DataTypes dataType) { switch (dataType) { case STRING: setStringValue(cell); break; case NUMERIC: case NUMERIC_BIGDECIMAL: case NUMERIC_BIGINTEGER: case NUMERIC_BYTE: case NUMERIC_DOUBLE: case NUMERIC_FLOAT: case NUMERIC_INTEGER: case NUMERIC_LONG: case NUMERIC_SHORT: setNumericValue(cell); break; case DATE: setDateValue(cell); break; case BOOLEAN: setBooleanValue(cell); break; } }
Source:
<code>private String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { return commitMessage; } if (amending) return previousCommitMessage; StringBuilder calculatedCommitMessage = new StringBuilder(); Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } if (resources.size() == 0 && repository != null) { resources .addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } try { List<ICommitMessageProvider> messageProviders = getCommitMessageProviders(); IResource[] resourcesArray = resources .toArray(new IResource[0]); String providedMessageSeparator = "\n\n"; <START> <END> for (ICommitMessageProvider messageProvider : messageProviders) { String message = null; try { message = messageProvider.getMessage(resourcesArray); } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } if (message != null && !"".equals(message.trim())) { if (calculatedCommitMessage.length() > 0) { calculatedCommitMessage .append(providedMessageSeparator); } calculatedCommitMessage.append(providedMessageSeparator) .append((message.trim())); } } } catch (CoreException coreException) { Activator.logError(coreException.getLocalizedMessage(), coreException); } return calculatedCommitMessage.toString(); }</code><technical_language>Strange... JDT UI settings in projects remove trailing whitespace. Please remove</technical_language>

Target:
String calculateCommitMessage(Collection<String> paths) { if (commitMessage != null) { return commitMessage; } if (amending) return previousCommitMessage; StringBuilder calculatedCommitMessage = new StringBuilder(); Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = findFile(path); if (file != null) resources.add(file.getProject()); } if (resources.size() == 0 && repository != null) { resources .addAll(Arrays.asList(ProjectUtil.getProjects(repository))); } try { List<ICommitMessageProvider> messageProviders = getCommitMessageProviders(); IResource[] resourcesArray = resources .toArray(new IResource[0]); String providedMessageSeparator = "\n\n"; for (ICommitMessageProvider messageProvider : messageProviders) { String message = null; try { message = messageProvider.getMessage(resourcesArray); } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } if (message != null && !"".equals(message.trim())) { if (calculatedCommitMessage.length() > 0) { calculatedCommitMessage .append(providedMessageSeparator); } calculatedCommitMessage.append((message.trim())); } } } catch (CoreException coreException) { Activator.logError(coreException.getLocalizedMessage(), coreException); } return calculatedCommitMessage.toString(); }