auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void validateConfiguredOptions() { int selendroidServerPort = Config.getIntConfigProperty(ConfigProperty.SELENDROID_SERVER_PORT); <START> if (PortProber.pollPort(selendroidServerPort)) { <END> throw new IllegalArgumentException("Specified SELENDROID_SERVER_PORT is already in use."); } try { checkAndValidateParameters(ConfigProperty.SELENDROID_EMULATOR_START_TIMEOUT); checkAndValidateParameters(ConfigProperty.SELENDROID_SERVER_START_TIMEOUT); checkAndValidateParameters(ConfigProperty.MOBILE_DRIVER_SESSION_TIMEOUT); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } }</code><technical_language>pollPort method is incorrectly returning a (or) missing a ! condition here. Please this fixed. Currently implementation is pollPort returns a true if establish a socket bind a port. port is in free used</technical_language>

Target:
private void validateConfiguredOptions() { int selendroidServerPort = Config.getIntConfigProperty(ConfigProperty.SELENDROID_SERVER_PORT); String portInUseError = String.format("Port %d is already in use. Please shutdown the service " + "listening on this port or configure a different selendroid server port.", selendroidServerPort); boolean free = false; try { free = PortProber.pollPort(selendroidServerPort); } catch (RuntimeException e) { throw new IllegalArgumentException(portInUseError, e); } finally { if (!free) { throw new IllegalArgumentException(portInUseError); } } try { checkAndValidateParameters(ConfigProperty.SELENDROID_EMULATOR_START_TIMEOUT); checkAndValidateParameters(ConfigProperty.SELENDROID_SERVER_START_TIMEOUT); checkAndValidateParameters(ConfigProperty.MOBILE_DRIVER_SESSION_TIMEOUT); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } }
Source:
<code>public final void print(final PJsonObject spec, final Configuration config, final File configDir, final File taskDirectory, final OutputStream outputStream) throws Exception { final String templateName = spec.getString(Constants.JSON_LAYOUT_KEY); <START> final Template template = config.getTemplate(templateName); <END> final Values values = new Values(spec, template, this.parser, taskDirectory, this.httpRequestFactory, null, this.fileSuffix); final ForkJoinTask<Values> taskFuture = this.forkJoinPool.submit(template.getProcessorGraph().createTask(values)); try { taskFuture.get(); } catch (InterruptedException exc) { taskFuture.cancel(true); Thread.currentThread().interrupt(); throw new CancellationException(); } String mapSubReport = values.getString(getMapSubReportVariable(template)); try { mapSubReport = new File(new URI(mapSubReport)).getAbsolutePath(); } catch (URISyntaxException e) { throw new IllegalStateException(e); } FileInputStream is = new FileInputStream(mapSubReport); try { IOUtils.copy(is, outputStream); } finally { is.close(); } }</code><technical_language>[AbstractJasperReportOutputFormat](<LINK_0>, template null. This if common parts AbstractJasperReportOutputFormat this class moved a class GenericOutputFormat? do think</technical_language>

Target:
public final void print(final PJsonObject spec, final Configuration config, final File configDir, final File taskDirectory, final OutputStream outputStream) throws Exception { final String templateName = spec.getString(Constants.JSON_LAYOUT_KEY); final Template template = config.getTemplate(templateName); if (template == null) { final String possibleTemplates = config.getTemplates().keySet().toString(); throw new IllegalArgumentException("\nThere is no template with the name: " + templateName + ".\nAvailable templates: " + possibleTemplates); } final Values values = new Values(spec, template, this.parser, taskDirectory, this.httpRequestFactory, null, this.fileSuffix); final ForkJoinTask<Values> taskFuture = this.forkJoinPool.submit(template.getProcessorGraph().createTask(values)); try { taskFuture.get(); } catch (InterruptedException exc) { taskFuture.cancel(true); Thread.currentThread().interrupt(); throw new CancellationException(); } String mapSubReport = values.getString(getMapSubReportVariable(template)); try { mapSubReport = new File(new URI(mapSubReport)).getAbsolutePath(); } catch (URISyntaxException e) { throw new IllegalStateException(e); } FileInputStream is = new FileInputStream(mapSubReport); try { IOUtils.copy(is, outputStream); } finally { is.close(); } }
Source:
<code>private int lastIndexOf(int fromIndex, int toIndex, byte value) { fromIndex = Math.min(fromIndex, capacity()); <START> if (fromIndex < 0 || capacity() == 0) { <END> return -1; } for (int i = fromIndex - 1; i >= toIndex; i --) { if (_getByte(i) == value) { return i; } } return -1; }</code><technical_language>replace if checkIndex(toIndex)</technical_language>

Target:
private int lastIndexOf(int fromIndex, int toIndex, byte value) { fromIndex = Math.min(fromIndex, capacity()); if (fromIndex < 0 || capacity() == 0) { return -1; } checkIndex(toIndex, fromIndex - toIndex); for (int i = fromIndex - 1; i >= toIndex; i --) { if (_getByte(i) == value) { return i; } } return -1; }
Source:
<code><START> public void testCreateLiteralLangCaseInsensitive() throws Exception { <END> final Literal lower = factory.createLiteral("Hello", "en-gb"); final Literal upper = factory.createLiteral("Hello", "EN-GB"); final Literal mixed = factory.createLiteral("Hello", "en-GB"); assertEquals("en-gb", lower.getLanguageTag().get()); assertEquals("en-gb", upper.getLanguageTag().get().toLowerCase(Locale.ROOT)); assertEquals("en-gb", mixed.getLanguageTag().get().toLowerCase(Locale.ROOT)); assertEquals(lower, lower); assertEquals(lower, upper); assertEquals(lower, mixed); assertEquals(upper, lower); assertEquals(upper, upper); assertEquals(upper, mixed); assertEquals(mixed, lower); assertEquals(mixed, upper); assertEquals(mixed, mixed); assertEquals(lower.hashCode(), upper.hashCode()); assertEquals(lower.hashCode(), mixed.hashCode()); }</code><technical_language>this need @Test annotation</technical_language>

Target:
public void testCreateLiteralLangCaseInsensitive() throws Exception { final Literal upper = factory.createLiteral("Hello", "EN-GB"); final Literal lower = factory.createLiteral("Hello", "en-gb"); final Literal mixed = factory.createLiteral("Hello", "en-GB"); assertEquals("en-gb", lower.getLanguageTag().get().toLowerCase(Locale.ROOT)); assertEquals("en-gb", upper.getLanguageTag().get().toLowerCase(Locale.ROOT)); assertEquals("en-gb", mixed.getLanguageTag().get().toLowerCase(Locale.ROOT)); assertEquals(lower, lower); assertEqualsBothWays(lower, upper); assertEqualsBothWays(lower, mixed); assertEquals(upper, upper); assertEqualsBothWays(upper, mixed); assertEquals(mixed, mixed); }
Source:
<code>private static String getFacebookEndpoint() { <START> return String.format("<LINK_0>", BuildConfig.FACEBOOK_APP_ID); <END> }</code><technical_language>provided Locale in argument issues depending user Locale app set to. I ran this Simperium library</technical_language>

Target:
private static String getFacebookEndpoint() { return String.format(Locale.ENGLISH, "<LINK_0>", BuildConfig.FACEBOOK_APP_ID); }
Source:
<code>public Action<?, ?> failedAction() { <START> return new AbstractEnvStackConfigUpdatesAction<>(EnvStopFailedEvent.class) { <END> @Override protected void doExecute(CommonContext context, EnvStopFailedEvent payload, Map<Object, Object> variables) { LOGGER.warn( String.format("Failed to update environments stack configs '%s'. Status: '%s'.", payload.getEnvironmentDto(), payload.getEnvironmentStatus()), payload.getException()); EnvironmentDto environmentDto = environmentStatusUpdateService .updateFailedEnvironmentStatusAndNotify(context, payload, getCurrentStatus(payload.getResourceId()), ResourceEvent.ENVIRONMENT_STACK_CONFIGS_UPDATE_FAILED, EnvStackConfigUpdatesState.STACK_CONFIG_UPDATES_FAILED_STATE); metricService.incrementMetricCounter(MetricType.ENV_STACK_CONFIG_UPDATE_FAILED, environmentDto, payload.getException()); sendEvent(context, HANDLE_FAILED_ENV_STACK_CONIFG_UPDATES_EVENT.event(), payload); } }; }</code><technical_language>EnvStopFailedEvent</technical_language>

Target:
public Action<?, ?> failedAction() { return new AbstractEnvStackConfigUpdatesAction<>(EnvStackConfigUpdatesFailedEvent.class) { @Override protected void doExecute(CommonContext context, EnvStackConfigUpdatesFailedEvent payload, Map<Object, Object> variables) { LOGGER.warn( String.format("Failed to update environments stack configs '%s'. Status: '%s'.", payload.getEnvironmentDto(), payload.getEnvironmentStatus()), payload.getException()); EnvironmentDto environmentDto = environmentStatusUpdateService .updateFailedEnvironmentStatusAndNotify(context, payload, getCurrentStatus(payload.getResourceId()), ResourceEvent.ENVIRONMENT_STACK_CONFIGS_UPDATE_FAILED, EnvStackConfigUpdatesState.STACK_CONFIG_UPDATES_FAILED_STATE); metricService.incrementMetricCounter(MetricType.ENV_STACK_CONFIG_UPDATE_FAILED, environmentDto, payload.getException()); sendEvent(context, HANDLE_FAILED_ENV_STACK_CONIFG_UPDATES_EVENT.event(), payload); } }; }
Source:
<code>public BinderFactory binderFactory(BinderTypeRegistry binderTypeRegistry, ChannelBindingServiceProperties channelBindingServiceProperties) { Map<String, BinderConfiguration> binderConfigurations = new HashMap<>(); <START> if (!CollectionUtils.isEmpty(channelBindingServiceProperties.getBinders())) { <END> for (Map.Entry<String, BinderProperties> binderEntry : channelBindingServiceProperties.getBinders().entrySet()) { BinderProperties binderProperties = binderEntry.getValue(); if (binderTypeRegistry.get(binderEntry.getKey()) != null) { binderConfigurations.put(binderEntry.getKey(), new BinderConfiguration(binderTypeRegistry.get(binderEntry.getKey()), binderProperties.getProperties())); } else { Assert.hasText(binderProperties.getType(), "No 'type' property present for custom " + "binder " + binderEntry.getKey()); binderConfigurations.put(binderEntry.getKey(), new BinderConfiguration(binderTypeRegistry.get(binderProperties.getType()), binderProperties.getProperties())); } } } else { for (Map.Entry<String, BinderType> entry : binderTypeRegistry.getAll().entrySet()) { binderConfigurations.put(entry.getKey(), new BinderConfiguration(entry.getValue(), new Properties())); } } DefaultBinderFactory binderFactory = new DefaultBinderFactory<>(binderConfigurations); binderFactory.setDefaultBinder(channelBindingServiceProperties.getDefaultBinder()); return binderFactory; }</code><technical_language>add default binder configurations built-in default values for binders registered BinderTypeRegistry ? way, explicitly need create a binder configuration for a binder overriding binder properties</technical_language>

Target:
public BinderFactory binderFactory(BinderTypeRegistry binderTypeRegistry, ChannelBindingServiceProperties channelBindingServiceProperties) { Map<String, BinderConfiguration> binderConfigurations = new HashMap<>(); if (!CollectionUtils.isEmpty(channelBindingServiceProperties.getBinders())) { for (Map.Entry<String, BinderProperties> binderEntry : channelBindingServiceProperties.getBinders().entrySet()) { BinderProperties binderProperties = binderEntry.getValue(); if (binderTypeRegistry.get(binderEntry.getKey()) != null) { binderConfigurations.put(binderEntry.getKey(), new BinderConfiguration(binderTypeRegistry.get(binderEntry.getKey()), binderProperties.getEnvironment())); } else { Assert.hasText(binderProperties.getType(), "No 'type' property present for custom " + "binder " + binderEntry.getKey()); binderConfigurations.put(binderEntry.getKey(), new BinderConfiguration(binderTypeRegistry.get(binderProperties.getType()), binderProperties.getEnvironment())); } } } else { for (Map.Entry<String, BinderType> entry : binderTypeRegistry.getAll().entrySet()) { binderConfigurations.put(entry.getKey(), new BinderConfiguration(entry.getValue(), new Properties())); } } DefaultBinderFactory binderFactory = new DefaultBinderFactory<>(binderConfigurations); binderFactory.setDefaultBinder(channelBindingServiceProperties.getDefaultBinder()); return binderFactory; }
Source:
<code><START> public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) { <END> return constructListBoxModel(webhookSecretId); }</code><technical_language>Nitpick: I "create" is a more common word for pattern "construct". good duplicate code! (I caught earlier.)</technical_language>

Target:
public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) { return createListBoxModel(webhookSecretId); }
Source:
<code>private void checkResources() { File validatorDir = new File(validatorDirPath); List<URL> resources = new ArrayList<URL>(); boolean reloadResources = false; try { for (File f : validatorDir.listFiles()) { if (f.getName().endsWith(".jar")) { resources.add(f.toURI().toURL()); <START> if (resourceTimestamps.get(f.getName()) != f.lastModified()) { <END> reloadResources = true; logger.info("Resource " + f.getName() + " is updated. Reload the classloader."); resourceTimestamps.put(f.getName(), f.lastModified()); } } } } catch (MalformedURLException e) { throw new ValidatorManagerException(e); } if (reloadResources) { validatorLoader = new URLClassLoader(resources.toArray(new URL[resources.size()])); } }</code><technical_language>This introduce NPE if a resource is in resourceTimestamps</technical_language>

Target:
private void checkResources() { File validatorDir = new File(validatorDirPath); List<URL> resources = new ArrayList<URL>(); boolean reloadResources = false; try { for (File f : validatorDir.listFiles()) { if (f.getName().endsWith(".jar")) { resources.add(f.toURI().toURL()); if (resourceTimestamps.get(f.getName()) == null || resourceTimestamps.get(f.getName()) != f.lastModified()) { reloadResources = true; logger.info("Resource " + f.getName() + " is updated. Reload the classloader."); resourceTimestamps.put(f.getName(), f.lastModified()); } } } } catch (MalformedURLException e) { throw new ValidatorManagerException(e); } if (reloadResources) { validatorLoader = new URLClassLoader(resources.toArray(new URL[resources.size()])); } }
Source:
<code>public Server listen() throws InterruptedException { BeatsInitializer beatsInitializer = null; try { logger.info("Starting server on port: " + this.port); beatsInitializer = new BeatsInitializer(isSslEnable(), messageListener, clientInactivityTimeoutSeconds); ServerBootstrap server = new ServerBootstrap(); server.group(workGroup) .channel(NioServerSocketChannel.class) <START> .option(ChannelOption.SO_BACKLOG, 50) <END> .childOption(ChannelOption.SO_LINGER, 0) .childHandler(beatsInitializer); Channel channel = server.bind(host, port).sync().channel(); channel.closeFuture().sync(); } finally { workGroup.shutdownGracefully().sync(); beatsInitializer.shutdownEventExecutor(); } return this; }</code><technical_language>I _think_ this is ok - typically for netty applications, want avoid blocking main event loop - I guess in this case, want avoid acceptor event loop blindly accepting connections worker group deal a potentially blocked queue. I if, act of adding item a queue in logstash block, work group in thread pool, I this ok in short term</technical_language>

Target:
public Server listen() throws InterruptedException { BeatsInitializer beatsInitializer = null; try { logger.info("Starting server on port: " + this.port); beatsInitializer = new BeatsInitializer(isSslEnable(), messageListener, clientInactivityTimeoutSeconds, beatsHeandlerThreadCount); ServerBootstrap server = new ServerBootstrap(); server.group(workGroup) .channel(NioServerSocketChannel.class) .childOption(ChannelOption.SO_LINGER, 0) .childHandler(beatsInitializer); Channel channel = server.bind(host, port).sync().channel(); channel.closeFuture().sync(); } finally { workGroup.shutdownGracefully().sync(); beatsInitializer.shutdownEventExecutor(); } return this; }
Source:
<code>public Guid getUpServerId(Guid clusterId) { <START> return ClusterUtils.getInstance().getRandomUpServer(clusterId).getId(); <END> }</code><technical_language>NPE if upServer is null</technical_language>

Target:
public Guid getUpServerId(Guid clusterId) { VDS randomUpServer = ClusterUtils.getInstance().getRandomUpServer(clusterId); return randomUpServer == null ? null : randomUpServer.getId(); }
Source:
<code>void completePlayerSetup(boolean asked) { if (asked) { skinLayout = (OoyalaSkinLayout) findViewById(R.id.ooyalaSkin); PlayerDomain playerDomain = new PlayerDomain(domain); <START> Options options = new Options.Builder().setShowNativeLearnMoreButton(false).setShowPromoImage(false).setUseExoPlayer(true).setBypassPCodeMatching(true).build(); <END> player = new OoyalaPlayer(pcode, playerDomain, options); JSONObject overrides = createSkinOverrides(); SkinOptions skinOptions = new SkinOptions.Builder().setSkinOverrides(overrides).build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); if (player.setEmbedCode(embedCode)) { } else { Log.e(TAG, "Asset Failure"); } } }</code><technical_language>need add bypass default, add correct pcodes embed codes. If get pcode know</technical_language>

Target:
void completePlayerSetup(boolean asked) { if (asked) { skinLayout = (OoyalaSkinLayout) findViewById(R.id.ooyalaSkin); PlayerDomain playerDomain = new PlayerDomain(domain); Options options = new Options.Builder().setShowNativeLearnMoreButton(false).setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, playerDomain, options); JSONObject overrides = createSkinOverrides(); SkinOptions skinOptions = new SkinOptions.Builder().setSkinOverrides(overrides).build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); if (player.setEmbedCode(embedCode)) { } else { Log.e(TAG, "Asset Failure"); } } }
Source:
<code>public AttributeSet(String[] queryParams) { for (String param : queryParams) { String[] keyAndValue = param.split("="); if (keyAndValue.length != 2) { throw new IllegalArgumentException(String.format("Cannot parse query param '%s'", param)); } Attribute attr = Attribute.create(keyAndValue[0], keyAndValue[1]); attributeMap.put(attr.getName(), attr); <START> } <END> }</code><technical_language>needed for compatibility ObserveSpec. mark this deprecated forget remove ObserveSpec</technical_language>

Target:
public AttributeSet(String[] queryParams) { for (String param : queryParams) { String[] keyAndValue = param.split("="); if (keyAndValue.length != 2) { throw new IllegalArgumentException(String.format("Cannot parse query param '%s'", param)); } Attribute attr = Attribute.create(keyAndValue[0], keyAndValue[1]); attributeMap.put(attr.getCoRELinkParam(), attr); } }
Source:
<code>public Set<Rule<?>> rules() { <START> return ImmutableSet.of( <END> new ProjectExpressionRewrite(this::rewrite), new AggregationExpressionRewrite(this::rewrite), new FilterExpressionRewrite(this::rewrite), new TableScanExpressionRewrite(this::rewrite), new JoinExpressionRewrite(this::rewrite), new ValuesExpressionRewrite(this::rewrite)); }</code><technical_language>This is unreleated</technical_language>

Target:
public Set<Rule<?>> rules() { return ImmutableSet.of( projectExpressionRewrite(), aggregationExpressionRewrite(), filterExpressionRewrite(), tableScanExpressionRewrite(), joinExpressionRewrite(), valuesExpressionRewrite()); }
Source:
<code>public Object execute(JobExecutionContext context) throws JobExecutionException { JobArguments args = context.getJobArguments(); <START> String ownerKey = args.getAsString(OWNER_KEY); <END> ConflictOverrides overrides = new ConflictOverrides(args.getAs(CONFLICT_OVERRIDES, String[].class)); String storedFileId = args.getAsString(STORED_FILE_ID); String uploadedFileName = args.getAsString(UPLOADED_FILE_NAME); Throwable caught; Owner targetOwner = null; try { targetOwner = ownerCurator.getByKey(ownerKey); if (targetOwner == null) { throw new NotFoundException(String.format("Owner %s was not found.", ownerKey)); } ImportRecord importRecord = manifestManager.importStoredManifest(targetOwner, storedFileId, overrides, uploadedFileName); log.info("Async import complete."); return importRecord; } catch (SyncDataFormatException e) { caught = new BadRequestException(e.getMessage(), e); } catch (ImporterException e) { caught = new IseException(e.getMessage(), e); } catch (Exception e) { caught = e; } manifestManager.recordImportFailure(targetOwner, caught, uploadedFileName); manifestManager.deleteStoredManifest(storedFileId); throw new JobExecutionException(caught.getMessage(), caught, false); }</code><technical_language>able pull conflict overrides needing rebuild string array. If working, a problem in new serializer paths need address. Ideally line work: ConflictOverrides overrides = args.getAs(CONFLICT_OVERRIDES, ConflictOverrides.class) If so, setter change accordingly</technical_language>

Target:
public Object execute(JobExecutionContext context) throws JobExecutionException { JobArguments args = context.getJobArguments(); String ownerKey = args.getAsString(OWNER_KEY); ConflictOverrides overrides = new ConflictOverrides(args.getAs(CONFLICT_OVERRIDES, String[].class)); String storedFileId = args.getAsString(STORED_FILE_ID); String uploadedFileName = args.getAsString(UPLOADED_FILE_NAME); JobExecutionException toThrow; Throwable caught; Owner targetOwner = null; try { targetOwner = ownerCurator.getByKey(ownerKey); if (targetOwner == null) { throw new NotFoundException(String.format("Owner %s was not found.", ownerKey)); } ImportRecord importRecord = manifestManager.importStoredManifest(targetOwner, storedFileId, overrides, uploadedFileName); log.info("Async import complete."); return importRecord; } catch (ImportConflictException e) { toThrow = new ImportConflictJobException(e); caught = e; } catch (ImporterException e) { toThrow = new JobExecutionException(e.getMessage(), e, true); caught = e; } catch (Exception e) { toThrow = new JobExecutionException(e.getMessage(), e, false); caught = e; } manifestManager.recordImportFailure(targetOwner, caught, uploadedFileName); manifestManager.deleteStoredManifest(storedFileId); throw toThrow; }
Source:
<code>private void adjustConsumers(int newCount) { int delta = newCount - this.consumersPerQueue; if (delta != 0) { synchronized (this.consumersMonitor) { if (delta > 0) { List<SimpleConsumer> newConsumers = new ArrayList<>(); for (int i = 0; i < delta; i++) { for (String queue : getQueueNames()) { try { newConsumers.add(doConsumeFromQueue(queue)); } catch (IOException e) { logger.error("Failed to start a new consumer, reverting", e); for (SimpleConsumer consumer : newConsumers) { try { consumer.getChannel().basicCancel(consumer.getConsumerTag()); List<SimpleConsumer> list = this.consumersByQueue.get(queue); if (list != null) { list.remove(consumer); } } catch (IOException e1) { logger.error("Failed to cancel consumer during revert", e); } } <START> throw new AmqpIOException("Failed to increase consumers", e); <END> } } } } else { for (Entry<String, List<SimpleConsumer>> entry : this.consumersByQueue.entrySet()) { List<SimpleConsumer> consumerList = entry.getValue(); while (consumerList.size() > newCount) { SimpleConsumer consumer = consumerList.remove(consumerList.size() - 1); try { consumer.getChannel().basicCancel(consumer.getConsumerTag()); this.consumers.remove(consumer); } catch (IOException e) { logger.error("Failed to cancel consumer", e); } } } } } } }</code><technical_language>this operation atomic? adjust error break added new consumers</technical_language>

Target:
private void adjustConsumers(int newCount) { synchronized (this.consumersMonitor) { for (String queue : getQueueNames()) { try { while (this.consumersByQueue.get(queue) == null || this.consumersByQueue.get(queue).size() < newCount) { doConsumeFromQueue(queue); } if (this.consumersByQueue.get(queue).size() > newCount) { List<SimpleConsumer> consumerList = this.consumersByQueue.get(queue); while (consumerList.size() > newCount) { SimpleConsumer consumer = consumerList.remove(consumerList.size() - 1); try { consumer.getChannel().basicCancel(consumer.getConsumerTag()); this.consumers.remove(consumer); } catch (IOException e) { logger.error("Failed to cancel consumer", e); } } } } catch (IOException e) { throw new AmqpIOException( "Failed to adjust the consumer count for '" + queue + "' aborting adjustment", e); } } } }
Source:
<code><START> public void givenInvalidTestClass_integrationTest() { <END> Result result = JUnitCore.runClasses(TestClassWithErrors.class); assertThat(result.getFailureCount(), is(1)); Throwable failure = result.getFailures().get(0).getException(); assertThat(failure.getMessage(), allOf( startsWith("Invalid test class"), containsString(TestClassWithErrors.class.getName()), containsString("\n 1. "), containsString("\n 2. ") )); }</code><technical_language>This is fine. Thanks</technical_language>

Target:
public void givenInvalidTestClass_integrationTest() { Result result = JUnitCore.runClasses(TestClassWithErrors.class); assertThat(result.getFailureCount(), is(1)); Throwable failure = result.getFailures().get(0).getException(); assertThat(failure, instanceOf(InvalidTestClassError.class)); assertThat(failure.getMessage(), allOf( startsWith("Invalid test class '" + TestClassWithErrors.class.getName() + "'"), containsString("\n 1. "), containsString("\n 2. ") )); }
Source:
<code>static <T, U, R extends Traversable<U>> R scanRight(Traversable<? extends T> traversable, U zero, BiFunction<? super T, ? super U, ? extends U> operation, Function<Iterator<U>, R> finisher) { <START> final Iterator<? extends T> reversedElements = reverseIterator(traversable.iterator()); <END> return scanLeft(reversedElements, zero, (u, t) -> operation.apply(t, u), us -> finisher.apply(reverseIterator(us))); }</code><technical_language>+1: for new reverseIterator</technical_language>

Target:
static <T, U, R extends Traversable<U>> R scanRight(Traversable<? extends T> traversable, U zero, BiFunction<? super T, ? super U, ? extends U> operation, Function<Iterator<U>, R> finisher) { final Iterator<? extends T> reversedElements = reverseIterator(traversable); return scanLeft(reversedElements, zero, (u, t) -> operation.apply(t, u), us -> finisher.apply(reverseIterator(us))); }
Source:
<code>protected void validateUpdatedModel(final OperationContext context, final Resource resource) throws OperationFailedException { final ModelNode model = resource.getModel(); ModelNode path = model.get(CommonAttributes.PATH); final ServiceController<PathManager> controller = (ServiceController<PathManager>) context.getServiceRegistry(false) .getService(PathManagerService.SERVICE_NAME); if (controller != null) { if (model.hasDefined(CommonAttributes.RELATIVE_TO)) { final ModelNode relativeToPath = model.get(CommonAttributes.RELATIVE_TO); String pathName; try { pathName = controller.getValue().resolveRelativePathEntry(path.asString(), relativeToPath.asString()); } catch (IllegalArgumentException e) { throw new OperationFailedException( DeploymentScannerLogger.ROOT_LOGGER.pathEntryNotFound(relativeToPath.asString())); } if (pathName != null) { File relativePath = new File(pathName); if (!relativePath.exists()) { throw new OperationFailedException( DeploymentScannerLogger.ROOT_LOGGER.directoryIsNonexistent(relativePath.getAbsolutePath())); } if (!relativePath.isDirectory()) { throw new OperationFailedException( DeploymentScannerLogger.ROOT_LOGGER.isNotADirectory(relativePath.getAbsolutePath())); } if (!relativePath.canWrite()) { throw new OperationFailedException( DeploymentScannerLogger.ROOT_LOGGER.directoryIsNotWritable(relativePath.getAbsolutePath())); } <START> } <END> } } }</code><technical_language>This block starting L69 belong in this class. task of deployment-scanner subsystem validate these, ensuring attribute is a reference is a path. Validation of full path in WritePathAttributeHandler covers deployment-scanner subsystem's needs</technical_language>

Target:
protected void validateUpdatedModel(final OperationContext context, final Resource resource) throws OperationFailedException { final ModelNode model = resource.getModel(); final ModelNode relativeTo = DeploymentScannerDefinition.RELATIVE_TO.resolveModelAttribute(context, model); if (relativeTo.isDefined()) { try { PathEntry pathEntry = pathManager.getPathEntry(relativeTo.asString()); } catch (IllegalArgumentException e) { throw DeploymentScannerLogger.ROOT_LOGGER.pathEntryNotFound(relativeTo.asString()); } } }
Source:
<code>private int calcTotalBinaryDecodedLength(byte[] buf, int ptr) throws PatchApplyException { int total = 0; <START> while (buf[ptr] != '\n') { <END> int sizeChar = buf[ptr++]; total += resolveDecodedLength(sizeChar); ptr = nextLF(buf, ptr); } return total; }</code><technical_language>do ptr < buf.length && buf[ptr] != '\n' ArrayIndexOutOfBoundsException if nextLF walks end of array? is malformed enough throwing PatchApplyException</technical_language>

Target:
private int calcTotalBinaryDecodedLength(byte[] buf, int ptr) throws PatchApplyException { int total = 0; while (ptr < buf.length && buf[ptr] != '\n') { int sizeChar = buf[ptr++]; total += resolveDecodedLength(sizeChar); ptr = nextLF(buf, ptr); } if (ptr >= buf.length) { throw new PatchApplyException(JGitText.get().malformedBinaryPatch); } return total; }
Source:
<code>public ImmutableBitmap getBitmapIndex( String value, BitmapFactory bitmapFactory, int numRows ) { if (column == null) { return bitmapFactory.makeEmptyImmutableBitmap(); } <START> final float parsedFloat = Float.parseFloat(value); <END> final MutableBitmap bitmap = bitmapFactory.makeEmptyMutableBitmap(); for (int rowIdx = 0; rowIdx < column.getLength(); rowIdx++) { float rowVal = genericColumn.getFloatSingleValueRow(rowIdx); if (rowVal == parsedFloat) { bitmap.add(rowIdx); } } return bitmapFactory.makeImmutableBitmap(bitmap); }</code><technical_language>if a float</technical_language>

Target:
public ImmutableBitmap getBitmapIndex( String value, BitmapFactory bitmapFactory, int numRows ) { if (column == null) { return bitmapFactory.makeEmptyImmutableBitmap(); } final float parsedFloat; try { parsedFloat = Float.parseFloat(value); } catch (NumberFormatException nfe) { throw new ParseException("Could not parse value[%s] as float!", value); } final MutableBitmap bitmap = bitmapFactory.makeEmptyMutableBitmap(); for (int rowIdx = 0; rowIdx < column.getLength(); rowIdx++) { float rowVal = genericColumn.getFloatSingleValueRow(rowIdx); if (rowVal == parsedFloat) { bitmap.add(rowIdx); } } return bitmapFactory.makeImmutableBitmap(bitmap); }
Source:
<code>public String getResult() { try { float res = Float.parseFloat(result); if (res > 0) { return "+" + result; } else { return result; } <START> } catch (Exception e) { <END> return result; } }</code><technical_language>Again, please catch Exception. Code compiles fine try catch want replace catch for NumberFormatException</technical_language>

Target:
public String getResult(){ return result; }
Source:
<code>public void setup() throws AssumptionViolatedException { assumeTrue(CameraUtil.checkCameraDevice()); <START> Log.i("CameraTest", "setup"); <END> mMockOnImageAvailableListener = Mockito.mock(ImageReader.OnImageAvailableListener.class); FakeUseCaseConfig config = new FakeUseCaseConfig.Builder() .setTargetName("UseCase") .setLensFacing(DEFAULT_LENS_FACING) .build(); mCameraId = getCameraIdForLensFacingUnchecked(DEFAULT_LENS_FACING); mFakeUseCase = new TestUseCase(config, mMockOnImageAvailableListener); Map<String, Size> suggestedResolutionMap = new HashMap<>(); suggestedResolutionMap.put(mCameraId, new Size(640, 480)); mFakeUseCase.updateSuggestedResolution(suggestedResolutionMap); mCamera = sCameraFactory.getCamera(mCameraId); }</code><technical_language>Unnecessary log</technical_language>

Target:
public void setup() { assumeTrue(CameraUtil.deviceHasCamera()); mMockOnImageAvailableListener = Mockito.mock(ImageReader.OnImageAvailableListener.class); FakeUseCaseConfig config = new FakeUseCaseConfig.Builder() .setTargetName("UseCase") .setLensFacing(DEFAULT_LENS_FACING) .build(); mCameraId = getCameraIdForLensFacingUnchecked(DEFAULT_LENS_FACING); mFakeUseCase = new TestUseCase(config, mMockOnImageAvailableListener); Map<String, Size> suggestedResolutionMap = new HashMap<>(); suggestedResolutionMap.put(mCameraId, new Size(640, 480)); mFakeUseCase.updateSuggestedResolution(suggestedResolutionMap); mCamera = sCameraFactory.getCamera(mCameraId); }
Source:
<code><START> public void testGetAddressDeletedFromJournal() throws Exception { <END> SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); ActiveMQServerControl serverControl = createManagementControl(); Assert.assertFalse(ActiveMQServerControlTest.contains(address.toString(), serverControl.getAddressNames())); serverControl.createAddress(address.toString(), "ANYCAST"); Assert.assertTrue(ActiveMQServerControlTest.contains(address.toString(), serverControl.getAddressNames())); serverControl.deleteAddress(address.toString()); server.stop(); server.start(); Assert.assertFalse(ActiveMQServerControlTest.contains(address.toString(), serverControl.getAddressNames())); }</code><technical_language>This test is passing for change in PostOfficeJournalLoader.java. I wanted figure out I able reproduce this JUnit test day yesterday I noticed I in paragraph. Do ideas wrong</technical_language>

Target:
public void testGetAddressDeletedFromJournal() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); SimpleString name = RandomUtil.randomSimpleString(); ActiveMQServerControl serverControl = createManagementControl(); Assert.assertFalse(ActiveMQServerControlTest.contains(address.toString(), serverControl.getAddressNames())); serverControl.createAddress(address.toString(), "ANYCAST"); Assert.assertTrue(ActiveMQServerControlTest.contains(address.toString(), serverControl.getAddressNames())); restartServer(); serverControl.deleteAddress(address.toString()); restartServer(); Assert.assertFalse(ActiveMQServerControlTest.contains(address.toString(), serverControl.getAddressNames())); }
Source:
<code>private void handleKeyEvent(KeyEvent e) { if (e.getCode() == KeyCode.CAPS) { updateCapsLocked(); } <START> if (SHORTCUT_BACKSPACE.match(e)) { <END> swipe(); } }</code><technical_language>key events mutually exclusive, this else-if</technical_language>

Target:
private void handleKeyEvent(KeyEvent e) { if (e.getCode() == KeyCode.CAPS) { updateCapsLocked(); } else if (SHORTCUT_BACKSPACE.match(e)) { swipe(); } }
Source:
<code>public void onPlayButtonClicked() { modService.getFeaturedMod(COOP.getTechnicalName()) .thenAccept(featuredModBean -> gameService.hostGame(new NewGameInfo(titleTextField.getText(), Strings.emptyToNull(passwordTextField.getText()), featuredModBean, getSelectedMission().getMapFolderName(), emptySet(), <START> 0, 3000, <END> false))); }</code><technical_language>constants 0 3000 need away... null, null</technical_language>

Target:
public void onPlayButtonClicked() { modService.getFeaturedMod(COOP.getTechnicalName()) .thenAccept(featuredModBean -> gameService.hostGame(new NewGameInfo(titleTextField.getText(), Strings.emptyToNull(passwordTextField.getText()), featuredModBean, getSelectedMission().getMapFolderName(), emptySet()))); }
Source:
<code>public LeadershipToken blockOnBecomingLeader() throws InterruptedException { while (true) { PaxosValue greatestLearned = knowledge.getGreatestLearnedValue(); if (isThisNodeTheLeaderFor(greatestLearned)) { StillLeadingStatus leadingStatus = determineLeadershipStatus(greatestLearned); if (leadingStatus == StillLeadingStatus.LEADING) { log.info("Successfully became leader!"); return new PaxosLeadershipToken(greatestLearned); } else if (leadingStatus == StillLeadingStatus.NO_QUORUM) { long backoffTime = (long) (noQuorumMaxDelay * Math.random()); log.debug("Waiting for ms before rerequesting leadership status", SafeArg.of("waitTimeMs", backoffTime)); continue; <START> } <END> } else { if (pingLeader()) { Thread.sleep(updatePollingRateInMs); continue; } } boolean learnedNewState = updateLearnedStateFromPeers(greatestLearned); if (learnedNewState) { continue; } long backoffTime = (long) (randomWaitBeforeProposingLeadership * Math.random()); log.debug("Waiting for ms before proposing leadership", SafeArg.of("waitTimeMs", backoffTime)); Thread.sleep(backoffTime); proposeLeadershipAfter(greatestLearned); } }</code><technical_language>backoff</technical_language>

Target:
public LeadershipToken blockOnBecomingLeader() throws InterruptedException { while (true) { PaxosValue greatestLearned = knowledge.getGreatestLearnedValue(); if (isThisNodeTheLeaderFor(greatestLearned)) { StillLeadingStatus leadingStatus = determineLeadershipStatus(greatestLearned); if (leadingStatus == StillLeadingStatus.LEADING) { log.info("Successfully became leader!"); return new PaxosLeadershipToken(greatestLearned); } else if (leadingStatus == StillLeadingStatus.NO_QUORUM) { long backoffTime = ThreadLocalRandom.current().nextLong(0, noQuorumMaxDelay + 1); log.debug("Waiting for ms before rerequesting leadership status", SafeArg.of("waitTimeMs", backoffTime)); Thread.sleep(backoffTime); continue; } } else { if (pingLeader()) { Thread.sleep(updatePollingRateInMs); continue; } } boolean learnedNewState = updateLearnedStateFromPeers(greatestLearned); if (learnedNewState) { continue; } long backoffTime = ThreadLocalRandom.current().nextLong(0, randomWaitBeforeProposingLeadership + 1); log.debug("Waiting for ms before proposing leadership", SafeArg.of("waitTimeMs", backoffTime)); Thread.sleep(backoffTime); proposeLeadershipAfter(greatestLearned); } }
Source:
<code>private void processVmDevices(XmlRpcStruct vm) { <START> int i = 0; <END> if (vm == null || vm.getItem("vmId") == null) { log.errorFormat("Recieved NULL VM or VM id when processing VM devices, abort."); return; } Guid vmId = new Guid((String) vm.getItem("vmId")); HashSet<Guid> processedDevices = new HashSet<Guid>(); Object[] objects = (Object[]) vm.getItem("devices"); for (Object o : objects) { XmlRpcStruct device = new XmlRpcStruct((Map<String, Object>) o); Guid deviceId = getDeviceId(device); if ((device.getItem("address")) == null) { log.infoFormat("Recieved a Device without an address when processing VM devices, skipping device: {0}.", device.getInnerMap().toString()); continue; } VmDevice vmDevice = DbFacade.getInstance().getVmDeviceDAO().get(new VmDeviceId(deviceId, vmId)); if (deviceId == null || vmDevice == null) { deviceId = addNewVmDevice(vmId, device); } else { vmDevice.setAddress(((Map<String, String>) device.getItem("address")).toString()); DbFacade.getInstance().getVmDeviceDAO().update(vmDevice); } processedDevices.add(deviceId); } handleRemovedDevices(vmId, processedDevices); }</code><technical_language>please remove i, used</technical_language>

Target:
private void processVmDevices(XmlRpcStruct vm) { if (vm == null || vm.getItem("vmId") == null) { log.errorFormat("Recieved NULL VM or VM id when processing VM devices, abort."); return; } Guid vmId = new Guid((String) vm.getItem("vmId")); HashSet<Guid> processedDevices = new HashSet<Guid>(); Object[] objects = (Object[]) vm.getItem("devices"); for (Object o : objects) { XmlRpcStruct device = new XmlRpcStruct((Map<String, Object>) o); Guid deviceId = getDeviceId(device); if ((device.getItem("address")) == null) { log.infoFormat("Recieved a Device without an address when processing VM {0} devices, skipping device: {1}.", vmId, device.getInnerMap().toString()); continue; } VmDevice vmDevice = DbFacade.getInstance().getVmDeviceDAO().get(new VmDeviceId(deviceId, vmId)); if (deviceId == null || vmDevice == null) { deviceId = addNewVmDevice(vmId, device); } else { vmDevice.setAddress(((Map<String, String>) device.getItem("address")).toString()); addVmDeviceToList(vmDevice); } processedDevices.add(deviceId); } handleRemovedDevices(vmId, processedDevices); }
Source:
<code>public void testRemoveIfUnsupportedOperation() { Collection<Integer> c = Arrays.asList(1, 2, 3, 4); try { c.removeIf(truth); fail(); } catch (UnsupportedOperationException expected) { } <START> try { c.removeIf(falsity); } catch (Exception e) { fail(); } <END> }</code><technical_language>unnecessary try { catch } . test "throw Exception" write this c.removeIf. advantage of is test runner give a full stack of happened</technical_language>

Target:
public void testRemoveIfUnsupportedOperation() { Collection<Integer> c = Arrays.asList(1, 2, 3, 4); try { c.removeIf(truth); fail(); } catch (UnsupportedOperationException expected) { } c.removeIf(falsity); }
Source:
<code>AuthenticationResult acquireTokenWithBrokerSilent() throws AuthenticationException { mAuthRequest.setVersion(AuthenticationContext.getVersionName()); mAuthRequest.setBrokerAccountName(mAuthRequest.getLoginHint()); logBrokerVersion(); final AuthenticationResult authenticationResult; <START> if (StringExtensions.isNullOrBlank(mAuthRequest.getBrokerAccountName()) && StringExtensions <END> .isNullOrBlank(mAuthRequest.getUserId())) { Logger.v(TAG, "User is not specified, skipping background(silent) token request"); authenticationResult = null; } else { Logger.v(TAG, "User is specified for background(silent) token request, trying to acquire token silently."); authenticationResult = mBrokerProxy.getAuthTokenInBackground(mAuthRequest); } return authenticationResult; }</code><technical_language>talked Friday, I checkstyle, findbug rules. kind of changes for flipping check, i needs do it. benefits get here</technical_language>

Target:
AuthenticationResult acquireTokenWithBrokerSilent() throws AuthenticationException { mAuthRequest.setVersion(AuthenticationContext.getVersionName()); mAuthRequest.setBrokerAccountName(mAuthRequest.getLoginHint()); logBrokerVersion(); final AuthenticationResult authenticationResult; if (!StringExtensions.isNullOrBlank(mAuthRequest.getBrokerAccountName()) || !StringExtensions .isNullOrBlank(mAuthRequest.getUserId())) { Logger.v(TAG, "User is specified for background(silent) token request, trying to acquire token silently."); authenticationResult = mBrokerProxy.getAuthTokenInBackground(mAuthRequest); } else { Logger.v(TAG, "User is not specified, skipping background(silent) token request"); authenticationResult = null; } return authenticationResult; }
Source:
<code>private void validateOAuth2ClientConfig(ClientConfiguration clientConfiguration) { Assert.notNull(clientConfiguration.getClientId(), "clientId cannot be null"); Assert.isTrue(clientConfiguration.getScopes() != null && !clientConfiguration.getScopes().isEmpty(), "At least one scope is required"); String privateKey = clientConfiguration.getPrivateKey(); Assert.hasText(privateKey, "privateKey cannot be null (either PEM file path (or) full PEM content must be supplied)"); <START> if (!(privateKey.startsWith("-----BEGIN PRIVATE KEY-----") && privateKey.contains("-----END PRIVATE KEY-----"))) { <END> Path privateKeyPemFilePath = Paths.get(privateKey); boolean privateKeyPemFileExists = Files.exists(privateKeyPemFilePath, LinkOption.NOFOLLOW_LINKS); Assert.isTrue(privateKeyPemFileExists, "privateKey file does not exist"); } }</code><technical_language>a types of PEM wrapper strings (IIRC PKCS#1 PKCS#8), checking start string startsWith -----BEGIN (should enough cover of edge cases, if want a more concrete solution, a bouncy castle</technical_language>

Target:
private void validateOAuth2ClientConfig(ClientConfiguration clientConfiguration) { Assert.notNull(clientConfiguration.getClientId(), "clientId cannot be null"); Assert.isTrue(clientConfiguration.getScopes() != null && !clientConfiguration.getScopes().isEmpty(), "At least one scope is required"); String privateKey = clientConfiguration.getPrivateKey(); Assert.hasText(privateKey, "privateKey cannot be null (either PEM file path (or) full PEM content must be supplied)"); if (!ConfigUtil.hasPrivateKeyContentWrapper(privateKey)) { Path privateKeyPemFilePath; try { privateKeyPemFilePath = Paths.get(privateKey); } catch (InvalidPathException ipe) { throw new IllegalArgumentException("Invalid privateKey file path", ipe); } boolean privateKeyPemFileExists = Files.exists(privateKeyPemFilePath, LinkOption.NOFOLLOW_LINKS); Assert.isTrue(privateKeyPemFileExists, "privateKey file does not exist"); } }
Source:
<code>public int hashCode() { <START> return Objects.hash(stream, partitionId, sequenceNumber, data); <END> }</code><technical_language>data is a list of arrays, hash computed properly java public int hashCode() { final int hashOfData = data.stream().map(Arrays::hashCode).collect(Collectors.toList()).hashCode(); return Objects.hash(stream, partitionId, sequenceNumber, hashOfData); }</technical_language>

Target:
public int hashCode() { final int hashOfData = data.stream().map(Arrays::hashCode).collect(Collectors.toList()).hashCode(); return Objects.hash(stream, partitionId, sequenceNumber, hashOfData); }
Source:
<code>public void finishedGeotagging(ArrayList<File> files) { FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_geotag_layout); <START> if (fragment == null || !(fragment instanceof FinishGeoTagFragment)) { <END> fragment = new FinishGeoTagFragment(); Bundle args = new Bundle(); args.putSerializable(GeoTagImagesService.EXTRA_GEOTAGGED_FILES, files); fragment.setArguments(args); fm.beginTransaction().replace(R.id.fragment_geotag_layout, fragment).commit(); } }</code><technical_language>@chaviw here. skip check for null</technical_language>

Target:
public void finishedGeotagging(ArrayList<File> files) { FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_geotag_layout); if (!(fragment instanceof FinishGeoTagFragment)) { fragment = new FinishGeoTagFragment(); Bundle args = new Bundle(); if (files != null && files.size() > 0) { args.putInt(NUM_IMAGE_FILES, files.size()); args.putString(PARENT_DIR, files.get(0).getParent()); } fragment.setArguments(args); fm.beginTransaction().replace(R.id.fragment_geotag_layout, fragment).commit(); } }
Source:
<code>public static int compare(Number number, BigDecimal value, OptionalInt treatNanAs) { if ( number instanceof Double ) { return compare( (Double) number, value, treatNanAs ); } if ( number instanceof Float ) { return compare( (Float) number, value, treatNanAs ); } if ( number instanceof BigDecimal ) { return compare( (BigDecimal) number, value ); } if ( number instanceof BigInteger ) { return compare( (BigInteger) number, value ); } <START> return BigDecimal.valueOf( number.longValue() ).compareTo( value ); <END> }</code><technical_language>I toString() reliable enough. I do is special case types end a double based comparison for Max/Min DecimalMax/Min. sense you</technical_language>

Target:
public static int compare(Number number, BigDecimal value, OptionalInt treatNanAs) { if ( number instanceof Double ) { return compare( (Double) number, value, treatNanAs ); } if ( number instanceof Float ) { return compare( (Float) number, value, treatNanAs ); } if ( number instanceof BigDecimal ) { return compare( (BigDecimal) number, value ); } if ( number instanceof BigInteger ) { return compare( (BigInteger) number, value ); } if ( number instanceof Byte || number instanceof Integer || number instanceof Long || number instanceof Short ) { return compare( number.longValue(), value ); } return compare( number.doubleValue(), value, treatNanAs ); }