auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { final Timer.Context timerCtx = rollupLocatorExecuteTimer.time(); try { getGranularity().finer(); } catch (Exception ex) { log.error("No finer granularity available than " + getGranularity()); return; } if (log.isTraceEnabled()) log.trace("Getting locators for @ {}", new Object[]{parentSlotKey, parentRange.toString(), scheduleCtx.getCurrentTimeMillis()}); long waitStart = System.currentTimeMillis(); int rollCount = 0; final RollupExecutionContext executionContext = createRollupExecutionContext(); final RollupBatchWriter rollupBatchWriter = createRollupBatchWriter(executionContext); Set<Locator> locators = getLocators(executionContext); <START> log.debug("locators retrieved: {}", locators.size()); <END> for (Locator locator : locators) { rollCount = processLocator(rollCount, executionContext, rollupBatchWriter, locator); } drainExecutionContext(waitStart, rollCount, executionContext, rollupBatchWriter); timerCtx.stop(); }</code><technical_language>set this trace level</technical_language>

Target:
public void run() { final Timer.Context timerCtx = rollupLocatorExecuteTimer.time(); try { getGranularity().finer(); } catch (Exception ex) { log.error("No finer granularity available than " + getGranularity()); return; } if (log.isTraceEnabled()) log.trace("Getting locators for @ {}", new Object[]{parentSlotKey, parentRange.toString(), scheduleCtx.getCurrentTimeMillis()}); long waitStart = System.currentTimeMillis(); int rollCount = 0; final RollupExecutionContext executionContext = createRollupExecutionContext(); final RollupBatchWriter rollupBatchWriter = createRollupBatchWriter(executionContext); Set<Locator> locators = getLocators(executionContext); if (log.isTraceEnabled()) log.trace("locators retrieved: {}", locators.size()); for (Locator locator : locators) { rollCount = processLocator(rollCount, executionContext, rollupBatchWriter, locator); } drainExecutionContext(waitStart, rollCount, executionContext, rollupBatchWriter); timerCtx.stop(); }
Source:
<code>public void receiveCommand(Item item, Command command, ZWaveNode node, ZWaveWakeUpCommandClass commandClass, int endpointId, Map<String, String> arguments) { ZWaveCommandConverter<?, ?> converter = this.getCommandConverter(command.getClass()); if (converter == null) { logger.warn("NODE {}: No converter found for item={}, type={}, endpoint={}, ignoring command.", node.getNodeId(), item.getName(), command.getClass().getSimpleName(), endpointId); return; } <START> ZWaveProductDatabase database = new ZWaveProductDatabase(); <END> if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == false) { logger.error("NODE {}: database can't find product.", node.getNodeId()); return; } SerialMessage serialMessage = commandClass .setInterval((Integer) converter.convertFromCommandToValue(item, command)); if (serialMessage == null) { logger.warn("NODE {}: Generating message failed for command class = {}, endpoint = {}", node.getNodeId(), commandClass.getCommandClass().getLabel(), endpointId); return; } this.getController().sendData(serialMessage); serialMessage = commandClass.getIntervalMessage(); this.getController().sendData(serialMessage); if (command instanceof State) { this.getEventPublisher().postUpdate(item.getName(), (State) command); } }</code><technical_language>This section deleted database is required</technical_language>

Target:
public void receiveCommand(Item item, Command command, ZWaveNode node, ZWaveWakeUpCommandClass commandClass, int endpointId, Map<String, String> arguments) { ZWaveCommandConverter<?, ?> converter = this.getCommandConverter(command.getClass()); if (converter == null) { logger.warn("NODE {}: No converter found for item={}, type={}, endpoint={}, ignoring command.", node.getNodeId(), item.getName(), command.getClass().getSimpleName(), endpointId); return; } SerialMessage serialMessage = commandClass .setInterval((Integer) converter.convertFromCommandToValue(item, command)); if (serialMessage == null) { logger.warn("NODE {}: Generating message failed for command class = {}, endpoint = {}", node.getNodeId(), commandClass.getCommandClass().getLabel(), endpointId); return; } this.getController().sendData(serialMessage); serialMessage = commandClass.getIntervalMessage(); this.getController().sendData(serialMessage); if (command instanceof State) { this.getEventPublisher().postUpdate(item.getName(), (State) command); } }
Source:
<code>protected void render0(FunctionRenderContext context) { <START> Object[] jsonPathElements = new Object[context.getArgumentsSize()]; <END> jsonPathElements[0] = "val"; for (int i = 1; i < context.getArgumentsSize(); i++) { try { jsonPathElements[i] = Integer.parseInt(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } catch (NumberFormatException e) { jsonPathElements[i] = JpqlFunctionUtil.unquoteDoubleQuotes(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } } String jsonPath = AbstractJsonGetFunction.toJsonPath(jsonPathElements, jsonPathElements.length, false); context.addChunk("json_query(concat('{\"val\":', concat("); context.addArgument(0); context.addChunk(", '}'))"); context.addChunk(",'"); context.addChunk(jsonPath); context.addChunk("' OMIT QUOTES)"); }</code><technical_language>this utility function I mentioned well</technical_language>

Target:
protected void render0(FunctionRenderContext context) { List<Object> jsonPathElements = AbstractJsonGetFunction.retrieveJsonPathElements(context, 1); jsonPathElements.add(0, "val"); String jsonPath = AbstractJsonGetFunction.toJsonPath(jsonPathElements, jsonPathElements.size(), false); context.addChunk("json_query(concat('{\"val\":', concat("); context.addArgument(0); context.addChunk(", '}'))"); context.addChunk(",'"); context.addChunk(jsonPath); context.addChunk("' OMIT QUOTES)"); }
Source:
<code>@Override protected void onResume() { super.onResume(); testSuite.setTestList((AbstractTest[]) null); testSuite.getTestList(getPreferenceManager()); Integer runTime = testSuite.getRuntime(getPreferenceManager()); if (runTime.equals(PreferenceManager.MAX_RUNTIME_DISABLED)) <START> runTime = 3600; <END> runtime.setText(getString(R.string.twoParam, testSuite.getDataUsage(), getString(R.string.Dashboard_Card_Seconds, runTime.toString()))); }</code><technical_language>setting runtime 3600? impact UI</technical_language>

Target:
@Override protected void onResume() { super.onResume(); testSuite.setTestList((AbstractTest[]) null); testSuite.getTestList(getPreferenceManager()); runtime.setText(getString(R.string.twoParam, testSuite.getDataUsage(), getString(R.string.Dashboard_Card_Seconds, testSuite.getRuntime(getPreferenceManager()).toString()))); }
Source:
<code>public ExtractedMetadata doParseWithTimeout(final InputStream is, final long timeoutInMs) throws IOException { final int parseNumber = nextParseNumber.getAndIncrement(); final Thread t = Thread.currentThread(); final TimerTask killTaskHard = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Killing parsing thread because it's taking too long", t.getId()); t.stop(); } } } }; final TimerTask killTaskSoftly = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Interrupting parsing thread because it's taking too long", t.getId()); t.interrupt(); <START> parserKillerTimer.schedule(killTaskHard, 2*timeoutInMs); <END> } } } }; synchronized (parseNumbersInProgress) { parseNumbersInProgress.add(parseNumber); } final ExtractedMetadata result; final boolean wasInterrupted; parserKillerTimer.schedule(killTaskSoftly, timeoutInMs); try { try { result = doParse(is); } catch(final ThreadDeath e) { throw new RuntimeException("Science-parse killer got impatient", e); } } finally { synchronized (parseNumbersInProgress) { parseNumbersInProgress.remove(parseNumber); } wasInterrupted = Thread.interrupted(); } if(wasInterrupted) logger.info("Overriding interruption of parsing thread because it finished before we could react", t.getId()); assert !Thread.interrupted(); return result; }</code><technical_language>I a flat structure schedule killers task easier read</technical_language>

Target:
public ExtractedMetadata doParseWithTimeout(final InputStream is, final long timeoutInMs) throws IOException { final int parseNumber = nextParseNumber.getAndIncrement(); final Thread t = Thread.currentThread(); final TimerTask killTaskHard = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Killing parsing thread because it's taking too long", t.getId()); t.stop(); } } } }; final TimerTask killTaskSoftly = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Interrupting parsing thread because it's taking too long", t.getId()); t.interrupt(); } } } }; synchronized (parseNumbersInProgress) { parseNumbersInProgress.add(parseNumber); } final ExtractedMetadata result; final boolean wasInterrupted; parserKillerTimer.schedule(killTaskSoftly, timeoutInMs); parserKillerTimer.schedule(killTaskHard, 3*timeoutInMs); try { try { result = doParse(is); } catch(final ThreadDeath e) { throw new RuntimeException("Science-parse killer got impatient", e); } } finally { synchronized (parseNumbersInProgress) { parseNumbersInProgress.remove(parseNumber); } wasInterrupted = Thread.interrupted(); } if(wasInterrupted) logger.info("Overriding interruption of parsing thread because it finished before we could react", t.getId()); assert !Thread.interrupted(); return result; }
Source:
<code>public Builder setTitle(String title) { this.title = title; ORDER.put(++orderIndex,"title"); <START> return this; <END> }</code><technical_language>do need ORDER for? matter in order elements in XML. simply define order of elements in toXML() serializing "source" first, artist, etc. (in order like). a reason preserve order in user values in builder</technical_language>

Target:
public Builder setTitle(String title) { this.title = title; return this; }
Source:
<code>public void testDisallowedOperations() { Disk disk = new DiskImage(); for (Map.Entry<VdcActionType, List<DiskContentType>> entry : DiskOperationsValidator.allowedCommandsOnTypes.entrySet()) { EnumSet<DiskContentType> allowedTypes = EnumSet.copyOf(entry.getValue()); EnumSet<DiskContentType> disallowedTypes = EnumSet.complementOf(allowedTypes); <START> if (allowedTypes.isEmpty()) { continue; } <END> disk.setContentType(disallowedTypes.iterator().next()); DiskOperationsValidator validator = new DiskOperationsValidator(disk); assertThat(validator.isOperationAllowedOnDisk(entry.getKey()), failsWith(EngineMessage.ACTION_TYPE_FAILED_DISK_CONTENT_TYPE_NOT_SUPPORTED_FOR_OPERATION, String.format("$diskContentType %s", disk.getContentType()))); } }</code><technical_language>redundant because: 1. Do a command run disk content type? 2. Currently empty list in map preparing surface for it? a test. 3. This if evaluated true empty list EnumSet.copyOf in line 34 get empty collection (it throw IllegalArgumentException)</technical_language>

Target:
public void testDisallowedOperations() { Disk disk = new DiskImage(); for (Map.Entry<VdcActionType, List<DiskContentType>> entry : DiskOperationsValidator.allowedCommandsOnTypes.entrySet()) { EnumSet<DiskContentType> allowedTypes = EnumSet.copyOf(entry.getValue()); EnumSet<DiskContentType> disallowedTypes = EnumSet.complementOf(allowedTypes); disk.setContentType(disallowedTypes.iterator().next()); DiskOperationsValidator validator = new DiskOperationsValidator(disk); assertThat(validator.isOperationAllowedOnDisk(entry.getKey()), failsWith(EngineMessage.ACTION_TYPE_FAILED_DISK_CONTENT_TYPE_NOT_SUPPORTED_FOR_OPERATION, String.format("$diskContentType %s", disk.getContentType()))); } }
Source:
<code>public void stop(final StopContext context) { if (!blockStart) { try { synchronized (waitObject) { <START> log.info("BlockService blocking in start"); <END> waitObject.wait(blockTime); } context.complete(); } catch (InterruptedException e) { log.info("BlockService interrupted"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } } else { synchronized (waitObject) { log.info("BlockService Stopping"); waitObject.notifyAll(); } } }</code><technical_language>s/start/stop</technical_language>

Target:
public void stop(final StopContext context) { if (!blockStart) { try { synchronized (waitObject) { log.info("BlockService blocking in stop"); waitObject.wait(blockTime); } context.complete(); } catch (InterruptedException e) { log.info("BlockService interrupted"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } } else { synchronized (waitObject) { log.info("BlockService Stopping"); waitObject.notifyAll(); } } }
Source:
<code>public void testOnJoinChannelButtonClicked() throws Exception { assertThat(instance.tabPane.getTabs(), is(empty())); Tab tab = new Tab(); tab.setId(TEST_CHANNEL_NAME); when(channelTabController.getRoot()).thenReturn(tab); when(userService.getUsername()).thenReturn(TEST_USER_NAME); doAnswer(invocation -> { MapChangeListener.Change<? extends String, ? extends Channel> change = mock(MapChangeListener.Change.class); when(change.wasAdded()).thenReturn(true); <START> doReturn(new Channel(invocation.getArgument(0))).when(change.getValueAdded()); <END> channelsListener.getValue().onChanged(change); return null; }).when(chatService).joinChannel(anyString()); instance.channelNameTextField.setText(TEST_CHANNEL_NAME); instance.onJoinChannelButtonClicked(); verify(chatService).joinChannel(TEST_CHANNEL_NAME); verify(chatService).addUsersListener(eq(TEST_CHANNEL_NAME), onUsersListenerCaptor.capture()); MapChangeListener.Change<? extends String, ? extends ChatChannelUser> change = mock(MapChangeListener.Change.class); when(change.wasAdded()).thenReturn(true); doReturn(new ChatChannelUser(TEST_USER_NAME, null, false)).when(change.getValueAdded()); onUsersListenerCaptor.getValue().onChanged(change); CountDownLatch tabAddedLatch = new CountDownLatch(1); instance.tabPane.getTabs().addListener((InvalidationListener) observable -> tabAddedLatch.countDown()); tabAddedLatch.await(2, TimeUnit.SECONDS); assertThat(instance.tabPane.getTabs(), hasSize(1)); assertThat(instance.tabPane.getTabs().get(0).getId(), is(TEST_CHANNEL_NAME)); }</code><technical_language>A test is failing of this. @axel1200</technical_language>

Target:
public void testOnJoinChannelButtonClicked() throws Exception { assertThat(instance.tabPane.getTabs(), is(empty())); Tab tab = new Tab(); tab.setId(TEST_CHANNEL_NAME); when(channelTabController.getRoot()).thenReturn(tab); when(userService.getUsername()).thenReturn(TEST_USER_NAME); doAnswer(invocation -> { MapChangeListener.Change<? extends String, ? extends Channel> change = mock(MapChangeListener.Change.class); when(change.wasAdded()).thenReturn(true); doReturn(new Channel(invocation.getArgument(0))).when(change).getValueAdded(); channelsListener.getValue().onChanged(change); return null; }).when(chatService).joinChannel(anyString()); instance.channelNameTextField.setText(TEST_CHANNEL_NAME); instance.onJoinChannelButtonClicked(); verify(chatService).joinChannel(TEST_CHANNEL_NAME); verify(chatService).addUsersListener(eq(TEST_CHANNEL_NAME), onUsersListenerCaptor.capture()); MapChangeListener.Change<? extends String, ? extends ChatChannelUser> change = mock(MapChangeListener.Change.class); when(change.wasAdded()).thenReturn(true); doReturn(new ChatChannelUser(TEST_USER_NAME, null, false)).when(change).getValueAdded(); onUsersListenerCaptor.getValue().onChanged(change); CountDownLatch tabAddedLatch = new CountDownLatch(1); instance.tabPane.getTabs().addListener((InvalidationListener) observable -> tabAddedLatch.countDown()); tabAddedLatch.await(2, TimeUnit.SECONDS); assertThat(instance.tabPane.getTabs(), hasSize(1)); assertThat(instance.tabPane.getTabs().get(0).getId(), is(TEST_CHANNEL_NAME)); }
Source:
<code>public boolean isCompactionCandidate(long retentionPeriod) { <START> return isDeleted() && deletionTime <= (System.currentTimeMillis() - retentionPeriod); <END> }</code><technical_language>This misses expired blobs</technical_language>

Target:
public boolean isCompactionCandidate(long retentionPeriod) { return (isDeleted() && deletionTime <= (System.currentTimeMillis() - retentionPeriod)) || (isExpired() && expirationTime <= (System.currentTimeMillis() - retentionPeriod)); }
Source:
<code>private List<Property> readProperties(Map<String, ExecutableElement> properties) { <START> List<Property> values = new LinkedList<Property>(); <END> for (Map.Entry<String, ExecutableElement> entry : properties.entrySet()) { values.add(new Property(entry.getKey(), entry.getValue())); } return values; }</code><technical_language>LinkedList?!</technical_language>

Target:
private ImmutableList<Property> readProperties(Map<String, ExecutableElement> properties) { ImmutableList.Builder<Property> values = ImmutableList.builder(); for (Map.Entry<String, ExecutableElement> entry : properties.entrySet()) { values.add(new Property(entry.getKey(), entry.getValue())); } return values.build(); }
Source:
<code>public Quote getBuyQuote(Money amount) throws IOException, CoinbaseException { String qtyParam; <START> if(amount.getCurrencyUnit().getCode().equals("BTC")) <END> qtyParam = "qty"; else qtyParam = "native_qty"; URL buyPriceUrl; try { buyPriceUrl = new URL( _baseApiUrl, "prices/buy?" + qtyParam +"=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") ); } catch (MalformedURLException ex) { throw new AssertionError(ex); } return deserialize(doHttp(buyPriceUrl, "GET", null), Quote.class); }</code><technical_language>curly braces for style strictly necessary</technical_language>

Target:
public Quote getBuyQuote(Money amount) throws IOException, CoinbaseException { String qtyParam; if(amount.getCurrencyUnit().getCode().equals("BTC")) { qtyParam = "qty"; } else { qtyParam = "native_qty"; } URL buyPriceUrl; try { buyPriceUrl = new URL( _baseApiUrl, "prices/buy?" + qtyParam +"=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") ); } catch (MalformedURLException ex) { throw new AssertionError(ex); } return deserialize(doHttp(buyPriceUrl, "GET", null), Quote.class); }
Source:
<code>public void testBadSyntax() throws Exception { InputStream badRDF = openTestDatasetStream(BAD_RDF_FILE_NAME); validator.checkSyntax(badRDF, BASE_URI, RDF_FORMAT); <START> badRDF.close(); <END> }</code><technical_language>close() in a finally block, try-with-resource</technical_language>

Target:
public void testBadSyntax() throws Exception { try (InputStream badRDF = openTestDatasetStream(BAD_RDF_FILE_NAME)) { validator.checkSyntax(badRDF, BASE_URI, RDF_FORMAT); } }
Source:
<code>private List<File> getFiles(Repository repo, final RevCommit unfilteredCommit) throws MissingObjectException, IOException, IncorrectObjectTypeException, CorruptObjectException { List<File> files = new ArrayList<File>(); TreeWalk tw = new TreeWalk(repo); tw.setRecursive(true); <START> final PlotWalk walk = new PlotWalk(repo); <END> try { for (RevCommit parent : unfilteredCommit.getParents()) walk.parseBody(parent); FileDiff[] diffs = FileDiff.compute(repo, tw, unfilteredCommit, TreeFilter.ALL); if (diffs != null && diffs.length > 0) { File repoDir = repo.getDirectory(); String repoPath = repoDir.getParentFile().getAbsolutePath(); for (FileDiff d : diffs) { String path = d.getPath(); File f = new File(repoPath + File.separator + path); files.add(f); } } } finally { tw.release(); walk.release(); } return files; }</code><technical_language>RevWalk PlotWalk</technical_language>

Target:
private List<File> getFiles(Repository repo, final RevCommit unfilteredCommit) throws MissingObjectException, IOException, IncorrectObjectTypeException, CorruptObjectException { List<File> files = new ArrayList<File>(); TreeWalk tw = new TreeWalk(repo); tw.setRecursive(true); final RevWalk walk = new RevWalk(repo); try { for (RevCommit parent : unfilteredCommit.getParents()) walk.parseBody(parent); FileDiff[] diffs = FileDiff.compute(repo, tw, unfilteredCommit, TreeFilter.ALL); if (diffs != null && diffs.length > 0) { File repoDir = repo.getDirectory(); String repoPath = repoDir.getParentFile().getAbsolutePath(); for (FileDiff d : diffs) { String path = d.getPath(); File f = new File(repoPath + File.separator + path); files.add(f); } } } finally { tw.release(); walk.release(); } return files; }
Source:
<code>public TypedElementBoundsRenderer(VControl vElement, ViewModelContext viewContext, ReportService reportService, EMFFormsDatabinding emfFormsDatabinding, EMFFormsLabelProvider emfFormsLabelProvider, VTViewTemplateProvider vtViewTemplateProvider) { super(vElement, viewContext, reportService, emfFormsDatabinding, emfFormsLabelProvider, vtViewTemplateProvider); <START> dbc = new EMFDataBindingContext(); <END> }</code><technical_language>databindingcontext super class</technical_language>

Target:
public TypedElementBoundsRenderer(VControl vElement, ViewModelContext viewContext, ReportService reportService, EMFFormsDatabinding emfFormsDatabinding, EMFFormsLabelProvider emfFormsLabelProvider, VTViewTemplateProvider vtViewTemplateProvider) { super(vElement, viewContext, reportService, emfFormsDatabinding, emfFormsLabelProvider, vtViewTemplateProvider); }
Source:
<code>public void fillAllFields(User newUser) { fillLoginNameField(newUser.getLogin()); fillFirstNameField(newUser.getFirstName()); fillLastNameField(newUser.getLastName()); fillPasswordField(newUser.getPassword()); fillConfirmPasswordField(newUser.getPassword() + "_"); fillEmailField(newUser.getEmail()); <START> Select regionSelect = new Select(driver.findElement(NewUserPageLocators.REGION_SELECT.getBy())); <END> regionSelect.selectByVisibleText(newUser.getRegionName()); driver.findElement(By.xpath( String.format(NewUserPageLocators.ROLE_SELECT, newUser.getRoleName()))).click(); }</code><technical_language>move out separate method selectRegion(RegionEnum)</technical_language>

Target:
public void fillAllFields(User newUser) { fillLoginNameField(newUser.getLogin()); fillFirstNameField(newUser.getFirstName()); fillLastNameField(newUser.getLastName()); fillPasswordField(newUser.getPassword()); fillConfirmPasswordField(newUser.getPassword()); fillEmailField(newUser.getEmail()); selectRegion(Regions.valueOf(newUser.getRegionName().toUpperCase())); clickRoleRadioButton(Roles.valueOf(newUser.getRoleName().toUpperCase())); }
Source:
<code>public IdpResponse build() { String providerId = mUser.getProviderId(); if (!AuthUI.SUPPORTED_PROVIDERS.contains(providerId)) { throw new IllegalStateException("Unknown provider: " + providerId); } if ((providerId.equals(GoogleAuthProvider.PROVIDER_ID) <START> || providerId.equals(FacebookAuthProvider.PROVIDER_ID) <END> || providerId.equals(TwitterAuthProvider.PROVIDER_ID)) && TextUtils.isEmpty(mToken)) { throw new IllegalStateException( "Token cannot be null when using a non-email provider."); } if (providerId.equals(TwitterAuthProvider.PROVIDER_ID) && TextUtils.isEmpty(mSecret)) { throw new IllegalStateException( "Secret cannot be null when using the Twitter provider."); } return new IdpResponse(mUser, mToken, mSecret, null); }</code><technical_language>AuthUI.SOCIAL_PROVIDERS this list in place in case grows in future</technical_language>

Target:
public IdpResponse build() { String providerId = mUser.getProviderId(); if (!AuthUI.SUPPORTED_PROVIDERS.contains(providerId)) { throw new IllegalStateException("Unknown provider: " + providerId); } if (AuthUI.SOCIAL_PROVIDERS.contains(providerId) && TextUtils.isEmpty(mToken)) { throw new IllegalStateException( "Token cannot be null when using a non-email provider."); } if (providerId.equals(TwitterAuthProvider.PROVIDER_ID) && TextUtils.isEmpty(mSecret)) { throw new IllegalStateException( "Secret cannot be null when using the Twitter provider."); } return new IdpResponse(mUser, mToken, mSecret); }
Source:
<code>protected static NettyHttpService.Builder createBaseNettyHttpServiceBuilder() { return NettyHttpService.builder("test") .setHttpHandlers(new TestHandler()) .setHttpChunkLimit(75 * 1024) .setExceptionHandler(EXCEPTION_HANDLER) .setAuthHandler(new AuthHandler() { @Override public boolean isAuthenticated(HttpRequest request) { return request.headers().contains(HttpHeaderNames.AUTHORIZATION.toString()); } @Override public boolean hasRoles(HttpRequest request, String[] roles) { for (String role : roles) { if (request.headers().contains(HttpHeaderNames.AUTHORIZATION)) { <START> if (!request.headers().get(HttpHeaderNames.AUTHORIZATION.toString()).contains(role)) { <END> return false; } } else { return false; } } return true; } @Override public String getWWWAuthenticateHeader() { return "roles list"; } }) .setChannelPipelineModifier(new ChannelPipelineModifier() { @Override public void modify(ChannelPipeline pipeline) { pipeline.addAfter("codec", "testhandler", new TestChannelHandler()); } }); }</code><technical_language>need call .toString()</technical_language>

Target:
protected static NettyHttpService.Builder createBaseNettyHttpServiceBuilder() { return NettyHttpService.builder("test") .setHttpHandlers(new TestHandler()) .setHttpChunkLimit(75 * 1024) .setExceptionHandler(EXCEPTION_HANDLER) .setAuthHandler(new AuthHandler() { @Override public boolean isAuthenticated(HttpRequest request) { return request.headers().contains(HttpHeaderNames.AUTHORIZATION); } @Override public boolean hasRoles(HttpRequest request, String[] roles) { for (String role : roles) { if (request.headers().contains(HttpHeaderNames.AUTHORIZATION)) { if (!request.headers().get(HttpHeaderNames.AUTHORIZATION).contains(role)) { return false; } } else { return false; } } return true; } @Override public String getWWWAuthenticateHeader() { return "roles list"; } }) .setChannelPipelineModifier(new ChannelPipelineModifier() { @Override public void modify(ChannelPipeline pipeline) { pipeline.addAfter("codec", "testhandler", new TestChannelHandler()); } }); }
Source:
<code>public void zeroSizeContentTest() throws Exception { NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null); List<HttpContent> httpContents = new ArrayList<HttpContent>(1); httpContents.add(new DefaultLastHttpContent()); <START> nettyRequest.addContent(httpContents.get(0)); <END> assertEquals("Reference count is not as expected", 2, httpContents.get(0).refCnt()); ByteBufferAsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel(); ReadIntoCallback callback = new ReadIntoCallback(); Future<Long> future = nettyRequest.readInto(writeChannel, callback); assertEquals("There should be no content", 0, writeChannel.getNextChunk().remaining()); writeChannel.resolveOldestChunk(null); closeRequestAndValidate(nettyRequest); writeChannel.close(); verifyRefCnts(httpContents); if (callback.exception != null) { throw callback.exception; } long futureBytesRead = future.get(); assertEquals("Total bytes read does not match (callback)", 0, callback.bytesRead); assertEquals("Total bytes read does not match (future)", 0, futureBytesRead); }</code><technical_language>do need list (httpContents) httpcontent list I guess</technical_language>

Target:
public void zeroSizeContentTest() throws Exception { NettyRequest nettyRequest = createNettyRequest(HttpMethod.POST, "/", null); HttpContent httpContent = new DefaultLastHttpContent(); nettyRequest.addContent(httpContent); assertEquals("Reference count is not as expected", 2, httpContent.refCnt()); ByteBufferAsyncWritableChannel writeChannel = new ByteBufferAsyncWritableChannel(); ReadIntoCallback callback = new ReadIntoCallback(); Future<Long> future = nettyRequest.readInto(writeChannel, callback); assertEquals("There should be no content", 0, writeChannel.getNextChunk().remaining()); writeChannel.resolveOldestChunk(null); closeRequestAndValidate(nettyRequest); writeChannel.close(); assertEquals("Reference count of http content has changed", 1, httpContent.refCnt()); if (callback.exception != null) { throw callback.exception; } long futureBytesRead = future.get(); assertEquals("Total bytes read does not match (callback)", 0, callback.bytesRead); assertEquals("Total bytes read does not match (future)", 0, futureBytesRead); }
Source:
<code>public void internalStop() throws Exception { server.stop(); if (webContexts != null) { File tmpdir = null; StringBuilder strBuilder = new StringBuilder(); boolean found = false; for (WebAppContext context : webContexts) { tmpdir = context.getTempDirectory(); if (tmpdir != null && tmpdir.exists() && !context.isPersistTempDirectory()) { FileUtil.deleteDirectory(tmpdir); if (tmpdir.exists()) { ActiveMQWebLogger.LOGGER.tmpFileNotDeleted(tmpdir); strBuilder.append(tmpdir); strBuilder.append(","); found = true; } } } if (found) { <START> String artemisHome = System.getProperty("artemis.home"); <END> String bootJar = artemisHome + File.separator + "lib" + File.separator + "artemis-boot.jar"; String[] command = {"java", "-cp", bootJar, "org.apache.activemq.artemis.boot.WebTmpCleaner", strBuilder.toString()}; ProcessBuilder pb = new ProcessBuilder(command); pb.start(); } webContexts.clear(); } }</code><technical_language>get property other means? Fileconfiguration for instance</technical_language>

Target:
public void internalStop() throws Exception { server.stop(); if (webContexts != null) { File tmpdir = null; StringBuilder strBuilder = new StringBuilder(); boolean found = false; for (WebAppContext context : webContexts) { tmpdir = context.getTempDirectory(); if (tmpdir != null && tmpdir.exists() && !context.isPersistTempDirectory()) { FileUtil.deleteDirectory(tmpdir); if (tmpdir.exists()) { ActiveMQWebLogger.LOGGER.tmpFileNotDeleted(tmpdir); strBuilder.append(tmpdir); strBuilder.append(","); found = true; } } } if (found) { String bootJar = artemisHome + File.separator + "lib" + File.separator + "artemis-boot.jar"; String[] command = {"java", "-cp", bootJar, "org.apache.activemq.artemis.boot.WebTmpCleaner", strBuilder.toString()}; ProcessBuilder pb = new ProcessBuilder(command); pb.start(); } webContexts.clear(); } }
Source:
<code>void generateGeneralReport(GeneralReportModule generalReportModule) throws IOException { if (generalReportModule != null) { <START> reportPathFormatString = createReportDirectory(generalReportModule, reportPathFormatString); <END> setupProgressPanel(generalReportModule); ReportWorker worker = new ReportWorker(() -> { generalReportModule.generateReport(reportPathFormatString, progressPanel); }); worker.execute(); displayProgressPanel(); } }</code><technical_language>overwrite format string field (member variable) formatted path returned new createDirectory method. This assumes format string once. reportPathFormatString a static final String REPORT_PATH_FMT_STR a local variable for return of createReportDirectory</technical_language>

Target:
void generateGeneralReport(GeneralReportModule generalReportModule) throws IOException { if (generalReportModule != null) { String reportDir = createReportDirectory(generalReportModule); setupProgressPanel(generalReportModule, reportDir); ReportWorker worker = new ReportWorker(() -> { generalReportModule.generateReport(reportDir, progressPanel); }); worker.execute(); displayProgressPanel(); } }
Source:
<code>public boolean isOpen() { if (this.delegate instanceof AutorecoveringConnection && !this.delegate.isOpen()) { <START> throw new AmqpException("Auto recovery connection is not currently open"); <END> } return this.delegate != null && (this.delegate.isOpen()); }</code><technical_language>SimpleConnection: throw exception in isOpen() if auto recovery connection is currently closed. Why? is explanation of reason? Thanks</technical_language>

Target:
public boolean isOpen() { if (!this.explicitlyClosed && this.delegate instanceof AutorecoveringConnection && !this.delegate.isOpen()) { throw new AutoRecoverConnectionNotCurrentlyOpenException("Auto recovery connection is not currently open"); } return this.delegate != null && (this.delegate.isOpen()); }
Source:
<code>public String getReplPolicy() { <START> if (dbName == null) { <END> return null; } else if (tableName == null) { return dbName.toLowerCase() + ".*"; } else { return dbName.toLowerCase() + "." + tableName.toLowerCase(); } }</code><technical_language>check for blank string well. StringUtils.isEmpty() used</technical_language>

Target:
public String getReplPolicy() { if ((dbName == null) || (dbName.isEmpty())) { return null; } else if ((tableName == null) || (tableName.isEmpty())) { return dbName.toLowerCase() + ".*"; } else { return dbName.toLowerCase() + "." + tableName.toLowerCase(); } }
Source:
<code>public Builder setSuffix(String suffix) throws IllegalArgumentException { <START> format = DateTimeFormatter.ofPattern(suffix.replaceAll("[\\/:*?\"<>|]", "_")).withZone(timeZone); <END> final int len = suffix.length(); period = Period.NEVER; for (int i = 0; i < len; i ++) { switch (suffix.charAt(i)) { case 'y': period = min(period, Period.YEAR); break; case 'M': period = min(period, Period.MONTH); break; case 'w': case 'W': period = min(period, Period.WEEK); break; case 'D': case 'd': case 'F': case 'E': period = min(period, Period.DAY); break; case 'a': period = min(period, Period.HALF_DAY); break; case 'H': case 'k': case 'K': case 'h': period = min(period, Period.HOUR); break; case 'm': period = min(period, Period.MINUTE); break; case '\'': while (suffix.charAt(++i) != '\''){} break; case 's': case 'S': throw audit.rotatingBySecondUnsupported(suffix); } } return this; }</code><technical_language>@dmlloyd do this? I kind of allow OS's allow for characters in paths</technical_language>

Target:
public Builder setSuffix(String suffix) throws IllegalArgumentException { format = DateTimeFormatter.ofPattern(suffix).withZone(timeZone); final int len = suffix.length(); period = Period.NEVER; for (int i = 0; i < len; i ++) { switch (suffix.charAt(i)) { case 'y': period = min(period, Period.YEAR); break; case 'M': period = min(period, Period.MONTH); break; case 'w': case 'W': period = min(period, Period.WEEK); break; case 'D': case 'd': case 'F': case 'E': period = min(period, Period.DAY); break; case 'a': period = min(period, Period.HALF_DAY); break; case 'H': case 'k': case 'K': case 'h': period = min(period, Period.HOUR); break; case 'm': period = min(period, Period.MINUTE); break; case '\'': while (suffix.charAt(++i) != '\''){} break; case 's': case 'S': throw audit.rotatingBySecondUnsupported(suffix); } } return this; }
Source:
<code>public InputColumn<?>[] getUpdatedInputColumns(InputColumn<?>[] allInputColumns, boolean exceptionOnMissing) { final String[] newInputColumnNames = getInputColumnNames(); final List<InputColumn<?>> newInputColumns = new ArrayList<>(newInputColumnNames.length); for (final String newInputColumnName : newInputColumnNames) { final InputColumn<?> updatedInputColumn = updateInputColumn(allInputColumns, newInputColumnName); if (updatedInputColumn == null) { <START> if(exceptionOnMissing) { <END> final List<String> names = Arrays.stream(allInputColumns).map(InputColumn::getName).collect(Collectors.toList()); throw new IllegalStateException( "Column '" + newInputColumnName + "' not found. Available columns: " + names); } } else { newInputColumns.add(updatedInputColumn); } } return newInputColumns.toArray(new InputColumn[newInputColumns.size()]); }</code><technical_language>Missing space "if"</technical_language>

Target:
public InputColumn<?>[] getUpdatedInputColumns(InputColumn<?>[] allInputColumns, boolean exceptionOnMissing) { final String[] newInputColumnNames = getInputColumnNames(); final List<InputColumn<?>> newInputColumns = new ArrayList<>(newInputColumnNames.length); for (final String newInputColumnName : newInputColumnNames) { final InputColumn<?> updatedInputColumn = findInputColumn(allInputColumns, newInputColumnName); if (updatedInputColumn == null) { if (exceptionOnMissing) { final List<String> names = Arrays.stream(allInputColumns).map(InputColumn::getName).collect(Collectors.toList()); throw new CoalesceUnitMissingColumnException(this, newInputColumnName, "Column '" + newInputColumnName + "' not found. Available columns: " + names); } } else { newInputColumns.add(updatedInputColumn); } } return newInputColumns.toArray(new InputColumn[newInputColumns.size()]); }
Source:
<code>private void initializeOutputSchema() { List<Schema.Field> fields = new ArrayList<>(); fields.add(Schema.Field.of(conf.getKeyField(), Schema.of(Schema.Type.STRING))); for (String outputField : outputFields) { fields.add(Schema.Field.of(outputField, Schema.nullableOf(Schema.of(Schema.Type.STRING)))); } <START> outputSchema = Schema.recordOf("group.key.schema", fields); <END> }</code><technical_language>this is a misleading record name. is group key's schema. is schema of output records</technical_language>

Target:
private Schema initializeOutputSchema() { List<Schema.Field> fields = new ArrayList<>(); fields.add(Schema.Field.of(conf.getKeyField(), Schema.of(Schema.Type.STRING))); for (String outputField : conf.getOutputSchemaFields()) { fields.add(Schema.Field.of(outputField, Schema.nullableOf(Schema.of(Schema.Type.STRING)))); } return Schema.recordOf("output.schema", fields); }
Source:
<code>public void replaceInput(int ordinalInParent, RelNode p) { if (ordinalInParent == 0) { Preconditions.checkArgument( p instanceof DruidRel, "RelNode[%s] is not a DruidRel", p.getClass().getCanonicalName() ); <START> this.left = (DruidRel<?>) p; <END> } else if (ordinalInParent == 1) { this.right = p; } else { throw new IndexOutOfBoundsException(StringUtils.format("Invalid ordinalInParent[%s]", ordinalInParent)); } }</code><technical_language>Left is input (it sort of "becomes" this rel). getInputs returns 1 element Calcite is concerned. this replace right</technical_language>

Target:
public void replaceInput(int ordinalInParent, RelNode p) { if (ordinalInParent != 0) { throw new IndexOutOfBoundsException(StringUtils.format("Invalid ordinalInParent[%s]", ordinalInParent)); } this.right = p; }
Source:
<code>public static boolean isIdentifierKeyword(CharSequence text) { int pos = 0; int valueLength = text.length(); if(valueLength == 0) { return false; } boolean keyword = false; switch (text.charAt(pos++)) { case '$': if (valueLength == 1) return false; while (pos < valueLength) { char c = text.charAt(pos++); if (! isDecimalDigit(c)) return false; } keyword = true; break; case 'f': <START> if (valueLength == 5 END> && text.charAt(pos++) == 'a' && text.charAt(pos++) == 'l' && text.charAt(pos++) == 's' && text.charAt(pos++) == 'e' ) { keyword = true; } break; case 'n': if (valueLength == 4 && text.charAt(pos++) == 'u' && text.charAt(pos++) == 'l' && text.charAt(pos++) == 'l' ) { keyword = true; } else if (valueLength == 3 && text.charAt(pos++) == 'a' && text.charAt(pos++) == 'n' ) { keyword = true; } break; case 't': if (valueLength == 4 && text.charAt(pos++) == 'r' && text.charAt(pos++) == 'u' && text.charAt(pos++) == 'e' ) { keyword = true; } break; } return keyword; }</code><technical_language>variable renamed, 'f' in column 'alse' follow. Please fix leave rename for a separate style-related PR</technical_language>

Target:
public static boolean isIdentifierKeyword(CharSequence text) { int pos = 0; int valuelen = text.length(); if(valuelen == 0) { return false; } boolean keyword = false; switch (text.charAt(pos++)) { case '$': if (valuelen == 1) return false; while (pos < valuelen) { char c = text.charAt(pos++); if (! isDecimalDigit(c)) return false; } return true; case 'f': if (valuelen == 5 && text.charAt(pos++) == 'a' && text.charAt(pos++) == 'l' && text.charAt(pos++) == 's' && text.charAt(pos++) == 'e' ) { keyword = true; } break; case 'n': if (valuelen == 4 && text.charAt(pos++) == 'u' && text.charAt(pos++) == 'l' && text.charAt(pos++) == 'l' ) { keyword = true; } else if (valuelen == 3 && text.charAt(pos++) == 'a' && text.charAt(pos++) == 'n' ) { keyword = true; } break; case 't': if (valuelen == 4 && text.charAt(pos++) == 'r' && text.charAt(pos++) == 'u' && text.charAt(pos++) == 'e' ) { keyword = true; } break; } return keyword; }
Source:
<code><START> public static File checkJarFileForApplicationMode(Configuration configuration) { <END> final List<File> pipelineJars = configuration.get(PipelineOptions.JARS).stream().map( FunctionUtils.uncheckedFunction( uri -> { final URI jarURI = PackagedProgramUtils.resolveURI(uri); if (jarURI.getScheme().equals("local") && jarURI.isAbsolute()) { return new File(jarURI.getPath()); } throw new IllegalArgumentException("Only support local schema for application mode. \"local\" means the " + "jar is located in the image, not Flink client. e.g. local:/ }) ).collect(Collectors.toList()); Preconditions.checkArgument(pipelineJars.size() == 1, "Should only have one jar"); return pipelineJars.get(0); }</code><technical_language>I return list, check for size later, in KubernetesApplicationClusterEntrypoint.getPackagedProgramRetriever() is relevant place for check. this method remain general enough. this become: public static List<File> checkJarFileForApplicationMode(Configuration configuration) { return configuration.get(PipelineOptions.JARS).stream().map( FunctionUtils.uncheckedFunction( uri -> { final URI jarURI = PackagedProgramUtils.resolveURI(uri); if (jarURI.getScheme().equals("local") && jarURI.isAbsolute()) { return new File(jarURI.getPath()); } throw new IllegalArgumentException("Only support local schema for application mode. \"local\" means " + "jar is located in image, Flink client. e.g. local:///opt/flink/examples/streaming/WindowJoin.jar"); }) ).collect(Collectors.toList()); } in entrypoint have: final List<File> pipelineJars = KubernetesUtils.checkJarFileForApplicationMode(configuration); Preconditions.checkArgument(pipelineJars.size() == 1, "Should jar");</technical_language>

Target:
public static List<File> checkJarFileForApplicationMode(Configuration configuration) { return configuration.get(PipelineOptions.JARS).stream().map( FunctionUtils.uncheckedFunction( uri -> { final URI jarURI = PackagedProgramUtils.resolveURI(uri); if (jarURI.getScheme().equals("local") && jarURI.isAbsolute()) { return new File(jarURI.getPath()); } throw new IllegalArgumentException("Only \"local\" is supported as schema for application mode." + " This assumes that the jar is located in the image, not the Flink client." + " An example of such path is: local:/ }) ).collect(Collectors.toList()); }
Source:
<code>private File searchEnclosingProjectInWorkDir(File startFolder, String workingTreeRootPath) { File projectFile = null; File currentPath = startFolder; while (currentPath.toString().startsWith(workingTreeRootPath)) { projectFile = new File( currentPath.toString() + File.separator + ".project"); <START> if (projectFile.isFile()) { <END> break; } projectFile = null; currentPath = currentPath.getParentFile(); } return projectFile; }</code><technical_language>unrelated change</technical_language>

Target:
private File searchEnclosingProjectInWorkDir(File startFolder, String workingTreeRootPath) { File projectFile = null; File currentPath = startFolder; while (currentPath.toString().startsWith(workingTreeRootPath)) { projectFile = new File( currentPath.toString() + File.separator + ".project"); if (projectFile.isFile()) break; projectFile = null; currentPath = currentPath.getParentFile(); } return projectFile; }
Source:
<code>DropwizardTestResourceConfig(ResourceTestJerseyConfiguration configuration) { super(); property(TestProperties.CONTAINER_PORT, "0"); if (configuration.registerDefaultExceptionMappers) { register(new ExceptionMapperBinder(false)); } for (Class<?> provider : configuration.providers) { register(provider); } property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true"); for (Map.Entry<String, Object> property : configuration.properties.entrySet()) { property(property.getKey(), property.getValue()); } register(new JacksonFeature(configuration.mapper)); register(new HibernateValidationBinder(configuration.validator)); for (Supplier<?> singleton : configuration.singletons) { <START> register(singleton.get().getClass()); <END> } }</code><technical_language>this work PeopleResourceTest/PersonResourceTest</technical_language>

Target:
DropwizardTestResourceConfig(ResourceTestJerseyConfiguration configuration) { super(); property(TestProperties.CONTAINER_PORT, "0"); if (configuration.registerDefaultExceptionMappers) { register(new ExceptionMapperBinder(false)); } for (Class<?> provider : configuration.providers) { register(provider); } property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true"); for (Map.Entry<String, Object> property : configuration.properties.entrySet()) { property(property.getKey(), property.getValue()); } register(new JacksonFeature(configuration.mapper)); register(new HibernateValidationBinder(configuration.validator)); for (Supplier<?> singleton : configuration.singletons) { register(singleton.get()); } }
Source:
<code>public void configure(HttpSecurity http) throws Exception { String[] unsecuredResources = new String[] { "/login", "/security/**", "/services/rest/login", "/services/rest/logout" }; http .authenticationProvider(this.authenticationProvider) .authorizeRequests().antMatchers(unsecuredResources).permitAll().anyRequest().authenticated().and() .csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher()).and() .formLogin().successHandler(new SimpleUrlAuthenticationSuccessHandler()).defaultSuccessUrl("/") .failureUrl("/login.html?error").loginProcessingUrl("/j_spring_security_login").usernameParameter("username") .passwordParameter("password").and() .logout().logoutSuccessUrl("/login.html").and() <START> .addFilterBefore(basicAuthenticationFilter(), BasicAuthenticationFilter.class) <END> .addFilterAfter(getSimpleRestAuthenticationFilter(), BasicAuthenticationFilter.class) .addFilterAfter(getSimpleRestLogoutFilter(), LogoutFilter.class); if (this.corsEnabled) { http.addFilterBefore(getCorsFilter(), CsrfFilter.class); } }</code><technical_language>This is a nice solution tests work easily. However, discuss proceed. this enabled in test mode? revisit entire authentication mechanism for OASP I accept this is file issue for general rework of OASP authentication</technical_language>

Target:
public void configure(HttpSecurity http) throws Exception { String[] unsecuredResources = new String[] { "/login", "/security/**", "/services/rest/login", "/services/rest/logout" }; http .authenticationProvider(this.authenticationProvider) .authorizeRequests().antMatchers(unsecuredResources).permitAll().anyRequest().authenticated().and() .csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher()).and() .formLogin().successHandler(new SimpleUrlAuthenticationSuccessHandler()).defaultSuccessUrl("/") .failureUrl("/login.html?error").loginProcessingUrl("/j_spring_security_login").usernameParameter("username") .passwordParameter("password").and() .logout().logoutSuccessUrl("/login.html").and() .addFilterAfter(getSimpleRestAuthenticationFilter(), BasicAuthenticationFilter.class) .addFilterAfter(getSimpleRestLogoutFilter(), LogoutFilter.class); if (this.corsEnabled) { http.addFilterBefore(getCorsFilter(), CsrfFilter.class); } }