auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testStripDefaultPort() throws URISyntaxException { String methodName = "stripDefaultPort"; assertEquals(new URI("<LINK_3>"), invoke(Configuration.class, methodName, new URI("<LINK_6>"))); assertEquals(new URI("<LINK_5>"), invoke(Configuration.class, methodName, new URI("<LINK_5>"))); assertEquals(new URI("<LINK_1>"), invoke(Configuration.class, methodName, new URI("<LINK_2>"))); assertEquals(new URI("<LINK_7>"), invoke(Configuration.class, methodName, new URI("<LINK_7>"))); assertEquals(new URI("HTTP://example.com/test"), invoke(Configuration.class, methodName, new URI("HTTP://example.com:80/test"))); }

Target:
public void testStripDefaultPort() throws URISyntaxException { String methodName = "stripDefaultPort"; assertEquals(new URI("<LINK_3>"), invoke(Configuration.class, methodName, new URI("<LINK_6>"))); assertEquals(new URI("<LINK_5>"), invoke(Configuration.class, methodName, new URI("<LINK_5>"))); assertEquals(new URI("<LINK_1>"), invoke(Configuration.class, methodName, new URI("<LINK_2>"))); assertEquals(new URI("<LINK_7>"), invoke(Configuration.class, methodName, new URI("<LINK_7>"))); assertEquals(new URI("HTTP://example.com/test"), invoke(Configuration.class, methodName, new URI("HTTP://example.com:80/test"))); assertEquals(new URI("HTTP://example.com:9080/test"), invoke(Configuration.class, methodName, new URI("HTTP://example.com:9080/test"))); assertEquals(new URI("<LINK_4>"), invoke(Configuration.class, methodName, new URI("<LINK_4>"))); assertEquals(new URI("<LINK_0>"), invoke(Configuration.class, methodName, new URI("<LINK_0>"))); }
Source:
public TestCase(final String name, final Object fieldValue, final String values, final Object expectedValue, final Class fieldType) { this.name = name; this.fieldValue = fieldValue; this.values = values; this.fieldType = fieldType; this.expectedValue = expectedValue; }

Target:
public TestCase(final String name, final Object fieldValue, final String values, final Object expectedValue, final Class fieldType) { this.name = name; this.fieldValue = fieldValue; this.values = values; this.expectedValue = expectedValue; this.fieldType = fieldType; }
Source:
public Subscriber (FSubscriberTransport t, FProtocolFactory pf) { transport = t; protocolFactory = pf; }

Target:
private Subscriber (FSubscriberTransport t, FProtocolFactory pf) { transport = t; protocolFactory = pf; }
Source:
protected void executeCommand() { storage_pool storagePool = DbFacade.getInstance().getStoragePoolDAO().get(getStoragePool().getId()); if ((storagePool.getQuotaEnforcementType() != QuotaEnforcmentTypeEnum.DISABLED) && (getStoragePool().getQuotaEnforcementType() == QuotaEnforcmentTypeEnum.DISABLED)) { QuotaHelper.getInstance().addDefaultQuota(storagePool); } DbFacade.getInstance().getStoragePoolDAO().updatePartial(getStoragePool()); if (getStoragePool().getstatus() == StoragePoolStatus.Up && !StringHelper.EqOp(_oldStoragePool.getname(), getStoragePool().getname())) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.SetStoragePoolDescription, new SetStoragePoolDescriptionVDSCommandParameters(getStoragePool().getId(), getStoragePool().getname())); } setSucceeded(true); }

Target:
protected void executeCommand() { storage_pool storagePool = DbFacade.getInstance().getStoragePoolDAO().get(getStoragePool().getId()); if ((storagePool.getQuotaEnforcementType() == QuotaEnforcmentTypeEnum.DISABLED) && (getStoragePool().getQuotaEnforcementType() != QuotaEnforcmentTypeEnum.DISABLED)) { QuotaHelper.getInstance().setDefaultQuotaAsRegularQuota(storagePool); } DbFacade.getInstance().getStoragePoolDAO().updatePartial(getStoragePool()); if (getStoragePool().getstatus() == StoragePoolStatus.Up && !StringHelper.EqOp(_oldStoragePool.getname(), getStoragePool().getname())) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.SetStoragePoolDescription, new SetStoragePoolDescriptionVDSCommandParameters(getStoragePool().getId(), getStoragePool().getname())); } setSucceeded(true); }
Source:
public Boolean visitNoScoping() { if (processNoScope) { synchronized (cleanupActions) { cleanupActions.put(injectee, new UnscopedCleanupAction(context, lifecycleActions)); } LOGGER.debug("predestroy action registered for unscoped instance from {}", injectee, context); } return true; }

Target:
public Boolean visitNoScoping() { if (processNoScope) { cleanupActions.computeIfAbsent(injectee, i->{ LOGGER.debug("predestroy action registered for unscoped instance from {}", i, context); return new UnscopedCleanupAction(context, lifecycleActions); }); } return true; }
Source:
public void sessionFactoryCreated(SessionFactoryImplementor sessionFactoryImplementor) { this.associationQueries = initializeAssociationQueries( sessionFactoryImplementor ); this.entityQueries = initializeEntityQueries( sessionFactoryImplementor, associationQueries ); }

Target:
public void sessionFactoryCreated(SessionFactoryImplementor sessionFactoryImplementor) { this.associationQueries = Collections.unmodifiableMap( initializeAssociationQueries( sessionFactoryImplementor ) ); this.entityQueries = Collections.unmodifiableMap( initializeEntityQueries( sessionFactoryImplementor, associationQueries ) ); }
Source:
private void onTest() { if (!validateConnectionSettings()) { getTestResult().setEntity(ConstantsManager.getInstance().getConstants().testFailedInsufficientParams()); return; } flush(); startProgress(null); if (provider.getUrl().toLowerCase().startsWith(Uri.SCHEME_HTTPS)) { AsyncDataProvider.getInstance().getProviderCertificateChain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { boolean ok = false; certificate = null; if (returnValue != null) { List<CertificateInfo> certs = (List<CertificateInfo>) returnValue; if (certs.size() > 0) { ConfirmationModel confirmationModel = getImportCertificateConfirmationModel(certs.get(0)); sourceListModel.setConfirmWindow(confirmationModel); importProviderCertificate(); ok = true; } } if (!ok) { stopProgress(); getTestResult().setEntity(ConstantsManager.getInstance() .getConstants() .testFailedUnknownErrorMsg()); } } }), provider); } else { testProviderConnectivity(); } }

Target:
private void onTest() { if (!validateConnectionSettings()) { getTestResult().setEntity(ConstantsManager.getInstance().getConstants().testFailedInsufficientParams()); return; } flush(); startProgress(null); if (provider.getUrl().startsWith(Uri.SCHEME_HTTPS)) { AsyncDataProvider.getInstance().getProviderCertificateChain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { boolean ok = false; certificate = null; if (returnValue != null) { List<CertificateInfo> certs = (List<CertificateInfo>) returnValue; if (certs.size() > 0) { certificate = certs.get(0).getPayload(); ConfirmationModel confirmationModel = getImportCertificateConfirmationModel(certs.get(0)); sourceListModel.setConfirmWindow(confirmationModel); ok = true; } } if (!ok) { stopProgress(); getTestResult().setEntity(ConstantsManager.getInstance() .getConstants() .testFailedUnknownErrorMsg()); } } }), provider); } else { testProviderConnectivity(); } }
Source:
private ManifestEntry buildEntry( final Path entry, final BasicFileAttributes attributes, final boolean directory ) throws IOException { final String path = this.root.relativize(entry).toString(); final Path fileName = entry.getFileName(); final String name = fileName == null ? EMPTY_STRING : fileName.toString(); final Instant lastModifiedTime = attributes.lastModifiedTime().toInstant(); final Instant lastAccessTime = attributes.lastAccessTime().toInstant(); final Instant creationTime = attributes.creationTime().toInstant(); final long size = attributes.size(); String md5 = null; String mimeType = null; if (!directory) { try (InputStream data = Files.newInputStream(entry, StandardOpenOption.READ)) { md5 = DigestUtils.md5Hex(data); } catch (final IOException ioe) { log.error("Unable to create MD5 for due to error", entry, ioe); } try (TikaInputStream inputStream = TikaInputStream.get(entry)) { mimeType = this.tikaConfig.getDetector().detect(inputStream, new Metadata()).toString(); } catch (final IOException ioe) { log.error("Unable to detect mime type for due to error", entry, ioe); mimeType = MediaType.OCTET_STREAM.toString(); } } final Set<String> children = Sets.newHashSet(); if (directory) { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(entry)) { for (final Path child : directoryStream) { children.add(this.root.relativize(child).toString()); } } } String parent = null; if (StringUtils.isNotEmpty(path)) { parent = this.root.relativize(entry.getParent()).toString(); } return new ManifestEntry( path, name, lastModifiedTime, lastAccessTime, creationTime, directory, size, md5, mimeType, parent, children ); }

Target:
private ManifestEntry buildEntry( final Path entry, final BasicFileAttributes attributes, final boolean directory ) throws IOException { final String path = this.root.relativize(entry).toString(); final Path fileName = entry.getFileName(); final String name = fileName == null ? EMPTY_STRING : fileName.toString(); final Instant lastModifiedTime = attributes.lastModifiedTime().toInstant(); final Instant lastAccessTime = attributes.lastAccessTime().toInstant(); final Instant creationTime = attributes.creationTime().toInstant(); final long size = attributes.size(); String md5 = null; String mimeType = null; if (!directory) { try (InputStream data = Files.newInputStream(entry, StandardOpenOption.READ)) { md5 = DigestUtils.md5Hex(data); } catch (final IOException ioe) { log.error("Unable to create MD5 for due to error", entry, ioe); } mimeType = this.getMimeType(name, entry); } final Set<String> children = Sets.newHashSet(); if (directory) { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(entry)) { for (final Path child : directoryStream) { children.add(this.root.relativize(child).toString()); } } } String parent = null; if (StringUtils.isNotEmpty(path)) { parent = this.root.relativize(entry.getParent()).toString(); } return new ManifestEntry( path, name, lastModifiedTime, lastAccessTime, creationTime, directory, size, md5, mimeType, parent, children ); }
Source:
public INDArray doForward(boolean training) { if (!canDoForward()) throw new IllegalStateException("Cannot do forward pass: inputs not set"); nInForwardPass = inputs.length; if (inputs.length == 1) return inputs[0]; switch (op) { case Add: INDArray sum = inputs[0].dup(); for (int i = 1; i < inputs.length; i++) { sum.addi(inputs[i]); } return sum; case Average: INDArray average = inputs[0].dup(); for (int i = 1; i < inputs.length; i++) { average.addi(inputs[i]); } return average.divi(inputs.length); case Subtract: if (inputs.length != 2) throw new IllegalArgumentException("ElementWise subtraction only supports 2 inputs"); return inputs[0].sub(inputs[1]); case Product: INDArray product = inputs[0].dup(); for (int i = 1; i < inputs.length; i++) { product.muli(inputs[i]); } return product; case Max: INDArray max = inputs[0].dup(); CustomOp op = DynamicCustomOp.builder("mergemax") .setInputs(inputs) .setOutputs(max) .callInplace(false) .build(); Nd4j.getExecutioner().exec(op); return max; default: throw new UnsupportedOperationException("Unknown op: " + this.op); } }

Target:
public INDArray doForward(boolean training) { if (!canDoForward()) throw new IllegalStateException("Cannot do forward pass: inputs not set"); nInForwardPass = inputs.length; if (inputs.length == 1) return inputs[0]; switch (op) { case Add: INDArray sum = inputs[0].dup(inputs[0].ordering()); for (int i = 1; i < inputs.length; i++) { sum.addi(inputs[i]); } return sum; case Average: INDArray average = inputs[0].dup(inputs[0].ordering()); for (int i = 1; i < inputs.length; i++) { average.addi(inputs[i]); } return average.divi(inputs.length); case Subtract: if (inputs.length != 2) throw new IllegalArgumentException("ElementWise subtraction only supports 2 inputs"); return inputs[0].sub(inputs[1]); case Product: INDArray product = inputs[0].dup(inputs[0].ordering()); for (int i = 1; i < inputs.length; i++) { product.muli(inputs[i]); } return product; case Max: INDArray max = Nd4j.createUninitialized(inputs[0].shape(), inputs[0].ordering()); CustomOp op = DynamicCustomOp.builder("mergemax") .setInputs(inputs) .setOutputs(max) .callInplace(false) .build(); Nd4j.getExecutioner().exec(op); return max; default: throw new UnsupportedOperationException("Unknown op: " + this.op); } }
Source:
ScheduledProcedure(long delay, TimeUnit timeUnit, String procedure, Object... procedureParameters) { m_delayNs = Math.max(timeUnit.toNanos(delay), 0); m_procedure = procedure; m_procedureParameters = procedureParameters.clone(); }

Target:
ScheduledProcedure(long delay, TimeUnit timeUnit, String procedure, Object... procedureParameters) { m_requestedDelayNs = Math.max(timeUnit.toNanos(delay), 0); m_procedure = procedure; m_procedureParameters = procedureParameters.clone(); }
Source:
private static String limit(String s, int len) { return s.substring(0, Math.min(len, s.length())) + (s.length() > len ? "[...]" : ""); }

Target:
protected static String limit(String s, int len) { String truncated = s.substring(0, Math.min(len, s.length())); boolean isTruncated = len < s.length(); if (isTruncated) { truncated += "[...]"; } return truncated; }
Source:
public static Patient toPatient(OpenMRSPatient patient, OpenMRSPerson savedPerson, String motechPatientIdentifierTypeUuid, Map<String, String> patientIdentifiers) { Patient converted = new Patient(); Person person = new Person(); person.setUuid(savedPerson.getPersonId()); converted.setPerson(person); converted.getPerson().getPreferredAddress().setPreferred("true"); Location location = null; if (patient.getFacility() != null && StringUtils.isNotBlank(patient.getFacility().getFacilityId())) { location = new Location(); location.setUuid(patient.getFacility().getFacilityId()); } List<Identifier> identifiers = new ArrayList<>(); identifiers.add(createMotechPatientIdentifier(patient.getMotechId(), motechPatientIdentifierTypeUuid, location)); for (String identifierTypeUuid : patientIdentifiers.keySet()) { IdentifierType type = new IdentifierType(); type.setUuid(identifierTypeUuid); Identifier identifier = new Identifier(); identifier.setIdentifier(patientIdentifiers.get(identifierTypeUuid)); identifier.setLocation(location); identifier.setIdentifierType(type); identifiers.add(identifier); } converted.setIdentifiers(identifiers); return converted; }

Target:
public static Patient toPatient(OpenMRSPatient patient, OpenMRSPerson savedPerson, String motechPatientIdentifierTypeUuid, Map<String, String> patientIdentifiers) { Patient converted = new Patient(); Person person = new Person(); person.setUuid(savedPerson.getPersonId()); converted.setPerson(person); Location location = null; if (patient.getFacility() != null && StringUtils.isNotBlank(patient.getFacility().getFacilityId())) { location = new Location(); location.setUuid(patient.getFacility().getFacilityId()); } List<Identifier> identifiers = new ArrayList<>(); identifiers.add(createMotechPatientIdentifier(patient.getMotechId(), motechPatientIdentifierTypeUuid, location)); for (String identifierTypeUuid : patientIdentifiers.keySet()) { IdentifierType type = new IdentifierType(); type.setUuid(identifierTypeUuid); Identifier identifier = new Identifier(); identifier.setIdentifier(patientIdentifiers.get(identifierTypeUuid)); identifier.setLocation(location); identifier.setIdentifierType(type); identifiers.add(identifier); } converted.setIdentifiers(identifiers); return converted; }
Source:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); Schema inputSchema = context.getInputSchema(); if (inputSchema == null || inputSchema.getFields() == null) { return; } List<FieldOperation> fieldOperations = new ArrayList<>(); inputSchema.getFields().forEach( field -> fieldOperations.add(new FieldTransformOperation(String.format("Error collector for field %s", field.getName()), "Error collector identity transform", Collections.singletonList(field.getName()), field.getName()))); if (config.messageField != null) { fieldOperations.add(new FieldTransformOperation("Error collector message field", "Generated field", Collections.emptyList(), config.messageField)); } if (config.codeField != null) { fieldOperations.add(new FieldTransformOperation("Error collector code field", "Generated field", Collections.emptyList(), config.codeField)); } if (config.stageField != null) { fieldOperations.add(new FieldTransformOperation("Error collector stage field", "Generated field", Collections.emptyList(), config.stageField)); } context.record(fieldOperations); }

Target:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); Schema inputSchema = context.getInputSchema(); if (inputSchema == null || inputSchema.getFields() == null) { return; } List<FieldOperation> fieldOperations = new ArrayList<>(); inputSchema.getFields().forEach( field -> fieldOperations.add(new FieldTransformOperation(String.format("Error collector for field %s", field.getName()), "Error collector identity transform", Collections.singletonList(field.getName()), field.getName()))); if (config.messageField != null && !config.messageField.isEmpty()) { fieldOperations.add(new FieldTransformOperation("Error collector message field", "Generated field", Collections.emptyList(), config.messageField)); } if (config.codeField != null && !config.codeField.isEmpty()) { fieldOperations.add(new FieldTransformOperation("Error collector code field", "Generated field", Collections.emptyList(), config.codeField)); } if (config.stageField != null && !config.stageField.isEmpty()) { fieldOperations.add(new FieldTransformOperation("Error collector stage field", "Generated field", Collections.emptyList(), config.stageField)); } context.record(fieldOperations); }
Source:
public void testCustomPartitionCountOverridesPartitioningIfLarger() throws Exception { byte[] ratherBigPayload = new byte[2048]; Arrays.fill(ratherBigPayload, (byte) 65); KafkaTestBinder binder = getBinder(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); KafkaProducerProperties producerProperties = new KafkaProducerProperties(); producerProperties.setPartitionCount(5); producerProperties.setPartitionKeyExpression("payload"); KafkaConsumerProperties consumerProperties = new KafkaConsumerProperties(); consumerProperties.setMinPartitionCount(5); long uniqueBindingId = System.currentTimeMillis(); Binding<MessageChannel> producerBinding = binder.bindProducer("foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties); Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo" + uniqueBindingId + ".0", null, moduleInputChannel, consumerProperties); Message<?> message = org.springframework.integration.support.MessageBuilder.withPayload(ratherBigPayload).build(); binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = receive(moduleInputChannel); assertNotNull(inbound); assertArrayEquals(ratherBigPayload, (byte[]) inbound.getPayload()); Collection<Partition> partitions = binder.getCoreBinder().getConnectionFactory().getPartitions( "foo" + uniqueBindingId + ".0"); assertThat(partitions, hasSize(5)); producerBinding.unbind(); consumerBinding.unbind(); }

Target:
public void testCustomPartitionCountOverridesPartitioningIfLarger() throws Exception { byte[] ratherBigPayload = new byte[2048]; Arrays.fill(ratherBigPayload, (byte) 65); KafkaTestBinder binder = getBinder(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); KafkaProducerProperties producerProperties = new KafkaProducerProperties(); producerProperties.setPartitionCount(5); producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("payload")); KafkaConsumerProperties consumerProperties = new KafkaConsumerProperties(); consumerProperties.setMinPartitionCount(5); long uniqueBindingId = System.currentTimeMillis(); Binding<MessageChannel> producerBinding = binder.bindProducer("foo" + uniqueBindingId + ".0", moduleOutputChannel, producerProperties); Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo" + uniqueBindingId + ".0", null, moduleInputChannel, consumerProperties); Message<?> message = org.springframework.integration.support.MessageBuilder.withPayload(ratherBigPayload).build(); binderBindUnbindLatency(); moduleOutputChannel.send(message); Message<?> inbound = receive(moduleInputChannel); assertNotNull(inbound); assertArrayEquals(ratherBigPayload, (byte[]) inbound.getPayload()); Collection<Partition> partitions = binder.getCoreBinder().getConnectionFactory().getPartitions( "foo" + uniqueBindingId + ".0"); assertThat(partitions, hasSize(5)); producerBinding.unbind(); consumerBinding.unbind(); }
Source:
public static void validateLabelFieldForTrainer(Schema inputSchema, String labelField) { Schema.Field prediction = inputSchema.getField(labelField); if (labelField == null) { throw new IllegalArgumentException(String.format("Label field %s does not exists in the input schema", labelField)); } Schema predictionSchema = prediction.getSchema(); Schema.Type predictionFieldType = predictionSchema.isNullableSimple() ? predictionSchema.getNonNullable().getType() : predictionSchema.getType(); if (predictionFieldType != Schema.Type.DOUBLE) { throw new IllegalArgumentException(String.format("Prediction field must be of type Double, but was %s.", predictionFieldType)); } }

Target:
static void validateLabelFieldForTrainer(Schema inputSchema, String labelField) { Schema.Field prediction = inputSchema.getField(labelField); if (prediction == null) { throw new IllegalArgumentException(String.format("Label field %s does not exists in the input schema.", labelField)); } Schema predictionSchema = prediction.getSchema(); Schema.Type predictionFieldType = predictionSchema.isNullableSimple() ? predictionSchema.getNonNullable().getType() : predictionSchema.getType(); if (predictionFieldType != Schema.Type.DOUBLE) { throw new IllegalArgumentException(String.format("Label field must be of type Double, but was %s.", predictionFieldType)); } }
Source:
public void configure(Binder binder) { binder.disableCircularProxies(); jaxrsBinder(binder).bind(JsonMapper.class); jaxrsBinder(binder).bind(SmileMapper.class); jaxrsBinder(binder).bind(TimingResourceDynamicFeature.class); jaxrsBinder(binder).bind(DisallowOptionsModelProcessor.class); jaxrsBinder(binder).bindInjectionProvider(ClientInfo.class).to(ClientInfoSupplier.class); jaxrsBinder(binder).bindAdmin(ParsingExceptionMapper.class); jaxrsBinder(binder).bindAdmin(QueryParamExceptionMapper.class); jaxrsBinder(binder).bindAdmin(OverrideMethodFilter.class); jaxrsBinder(binder).bindAdmin(ThreadDumpResource.class); newSetBinder(binder, Object.class, JaxrsResource.class).permitDuplicates(); newSetBinder(binder, JaxrsBinding.class, JaxrsResource.class).permitDuplicates(); newMapBinder(binder, new TypeLiteral<Class<?>>() {}, new TypeLiteral<Supplier<?>>() {}, JaxrsInjectionProvider.class); }

Target:
public void configure(Binder binder) { binder.disableCircularProxies(); jaxrsBinder(binder).bindInjectionProvider(ClientInfo.class).to(ClientInfoSupplier.class); jaxrsBinder(binder).bindAdmin(ParsingExceptionMapper.class); jaxrsBinder(binder).bindAdmin(QueryParamExceptionMapper.class); jaxrsBinder(binder).bindAdmin(OverrideMethodFilter.class); jaxrsBinder(binder).bindAdmin(ThreadDumpResource.class); newSetBinder(binder, Object.class, JaxrsResource.class).permitDuplicates(); newSetBinder(binder, JaxrsBinding.class, JaxrsResource.class).permitDuplicates(); newMapBinder(binder, new TypeLiteral<Class<?>>() {}, new TypeLiteral<Supplier<?>>() {}, JaxrsInjectionProvider.class); }
Source:
public void write(@Nonnull PriorityScoreReasons entity, @Nonnull FieldWriter writer, @Nonnull OutputContext ctxt) throws IOException { writer.writeList( "positive", "positive", entity.getPositive() != null ? entity.getPositive() : null, ctxt ); writer.writeList( "negative", "negative", entity.getNegative() != null ? entity.getNegative() : null, ctxt ); }

Target:
public void write(@Nonnull PriorityScoreReasons entity, @Nonnull FieldWriter writer, @Nonnull OutputContext ctxt) throws IOException { writer.writeList( "positive", "positive", entity.getPositive(), ctxt ); writer.writeList( "negative", "negative", entity.getNegative(), ctxt ); }
Source:
protected int cancelQueuedBuildByPrNumber(final int id) { Queue queue = getJenkinsInstance().getQueue(); int canceled = 0; for (Queue.Item item : queue.getItems()) { if (!(item.task instanceof Job)) { LOGGER.debug("Item not instanceof job", item); continue; } final Job<?, ?> jobTask = (Job<?, ?>) item.task; if (!jobTask.getDisplayName().equals(job.getDisplayName())) { LOGGER.debug("{} != {}", jobTask.getFullName(), job.getFullName()); continue; } final CauseAction action = item.getAction(CauseAction.class); if (isNull(action)) { LOGGER.debug("Cause action is null for {}", jobTask.getFullName()); continue; } Optional<Cause> cause = from(action.getCauses()) .filter(instanceOf(GitHubPRCause.class)) .firstMatch(new CauseHasPRNum(id)); if (cause.isPresent()) { LOGGER.debug("Cancelling {}", item); queue.cancel(item); canceled++; } } return canceled; }

Target:
protected int cancelQueuedBuildByPrNumber(final int id) { int canceled = 0; SecurityContext old = impersonate(ACL.SYSTEM); try { final Queue queue = getJenkinsInstance().getQueue(); final Queue.Item[] items = queue.getItems(); for (Queue.Item item : items) { if (!(item.task instanceof Job)) { LOGGER.debug("Item not instanceof job", item); continue; } final Job<?, ?> jobTask = (Job<?, ?>) item.task; if (!jobTask.getFullName().equals(job.getFullName())) { LOGGER.debug("{} != {}", jobTask.getFullName(), job.getFullName()); continue; } final CauseAction action = item.getAction(CauseAction.class); if (isNull(action)) { LOGGER.debug("Cause action is null for {}", jobTask.getFullName()); continue; } Optional<Cause> cause = from(action.getCauses()) .filter(instanceOf(GitHubPRCause.class)) .firstMatch(new CauseHasPRNum(id)); if (cause.isPresent()) { LOGGER.debug("Cancelling {}", item); queue.cancel(item); canceled++; } } } finally { SecurityContextHolder.setContext(old); } return canceled; }
Source:
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (fSelection instanceof IStructuredSelection) { Object[] elems = ((IStructuredSelection) fSelection).toArray(); fSelectedModels = new ArrayList<>(elems.length); for (int i = 0; i < elems.length; i++) { if (elems[i] instanceof IFile) elems[i] = ((IFile) elems[i]).getProject(); if (elems[i] instanceof IProject && WorkspaceModelManager.isPluginProject((IProject) elems[i]) && !WorkspaceModelManager.isBinaryProject((IProject) elems[i])) fSelectedModels.add(elems[i]); } fModelChangeTable = new ModelChangeTable(); if (fExternalizeSelectedPluginsOnly) { monitor.beginTask(PDEUIMessages.GetNonExternalizedStringsOperation_taskMessage, fSelectedModels.size()); Iterator<Object> iterator = fSelectedModels.iterator(); while (iterator.hasNext() && !fCanceled) { IProject project = (IProject) iterator.next(); if (!WorkspaceModelManager.isBinaryProject(project)) getUnExternalizedStrings(project, SubMonitor.convert(monitor, 1)); } } else { IPluginModelBase[] pluginModels = PluginRegistry.getWorkspaceModels(); monitor.beginTask(PDEUIMessages.GetNonExternalizedStringsOperation_taskMessage, pluginModels.length); for (int i = 0; i < pluginModels.length && !fCanceled; i++) { IProject project = pluginModels[i].getUnderlyingResource().getProject(); if (!WorkspaceModelManager.isBinaryProject(project)) getUnExternalizedStrings(project, SubMonitor.convert(monitor, 1)); } } } }

Target:
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (fSelection instanceof IStructuredSelection) { Object[] elems = ((IStructuredSelection) fSelection).toArray(); fSelectedModels = new ArrayList<>(elems.length); for (int i = 0; i < elems.length; i++) { if (elems[i] instanceof IFile) elems[i] = ((IFile) elems[i]).getProject(); if (elems[i] instanceof IProject && WorkspaceModelManager.isPluginProject((IProject) elems[i]) && !WorkspaceModelManager.isBinaryProject((IProject) elems[i])) fSelectedModels.add(elems[i]); } fModelChangeTable = new ModelChangeTable(); if (fExternalizeSelectedPluginsOnly) { SubMonitor subMonitor = SubMonitor.convert(monitor, PDEUIMessages.GetNonExternalizedStringsOperation_taskMessage, fSelectedModels.size()); Iterator<Object> iterator = fSelectedModels.iterator(); while (iterator.hasNext() && !fCanceled) { IProject project = (IProject) iterator.next(); if (!WorkspaceModelManager.isBinaryProject(project)) getUnExternalizedStrings(project, subMonitor.newChild(1)); } } else { IPluginModelBase[] pluginModels = PluginRegistry.getWorkspaceModels(); SubMonitor subMonitor = SubMonitor.convert(monitor, PDEUIMessages.GetNonExternalizedStringsOperation_taskMessage, pluginModels.length); for (int i = 0; i < pluginModels.length && !fCanceled; i++) { IProject project = pluginModels[i].getUnderlyingResource().getProject(); if (!WorkspaceModelManager.isBinaryProject(project)) getUnExternalizedStrings(project, subMonitor.newChild(1)); } } } }
Source:
public static Observable<String> getTagsFromPref(String pref) { Timber.d("Retuning tags for pref:%s", pref); switch (pref) { case "Author": return Observable.fromArray(TAG_ARTIST, TAG_CAMARA_OWNER_NAME); case "Copyright": return Observable.fromArray(TAG_COPYRIGHT); case "Location": return Observable.fromArray(TAG_GPS_LATITUDE, TAG_GPS_LATITUDE_REF, TAG_GPS_LONGITUDE, TAG_GPS_LONGITUDE_REF, TAG_GPS_ALTITUDE, TAG_GPS_ALTITUDE_REF); case "Camera Model": return Observable.fromArray(TAG_MAKE, TAG_MODEL); case "Lens Model": return Observable.fromArray(TAG_LENS_MAKE, TAG_LENS_MODEL, TAG_LENS_SPECIFICATION); case "Serial Numbers": return Observable.fromArray(TAG_BODY_SERIAL_NUMBER, TAG_LENS_SERIAL_NUMBER); case "Software": return Observable.fromArray(TAG_SOFTWARE); default: return null; } }

Target:
public static String[] getTagsFromPref(String pref) { Timber.d("Retuning tags for pref:%s", pref); switch (pref) { case "Author": return new String[]{TAG_ARTIST, TAG_CAMARA_OWNER_NAME}; case "Copyright": return new String[]{TAG_COPYRIGHT}; case "Location": return new String[]{TAG_GPS_LATITUDE, TAG_GPS_LATITUDE_REF, TAG_GPS_LONGITUDE, TAG_GPS_LONGITUDE_REF, TAG_GPS_ALTITUDE, TAG_GPS_ALTITUDE_REF}; case "Camera Model": return new String[]{TAG_MAKE, TAG_MODEL}; case "Lens Model": return new String[]{TAG_LENS_MAKE, TAG_LENS_MODEL, TAG_LENS_SPECIFICATION}; case "Serial Numbers": return new String[]{TAG_BODY_SERIAL_NUMBER, TAG_LENS_SERIAL_NUMBER}; case "Software": return new String[]{TAG_SOFTWARE}; default: return new String[]{}; } }
Source:
public void testGetGeoJsonResponseWfs20() throws Exception { JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); print(response); checkStation1Exists(response); }

Target:
public void testGetGeoJsonResponseWfs20() throws Exception { JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); checkStation1Exists(response); }
Source:
private void build(Tree tree) { if (tree.is(Kind.IF_STATEMENT)) { visitIfStatement((IfStatementTree) tree); } else if (tree.is(Kind.BLOCK)) { visitBlock((BlockTree) tree); } else if (tree.is(Kind.EXPRESSION_STATEMENT)) { buildExpression((ExpressionStatementTree) tree); } }

Target:
private void build(Tree tree) { if (tree.is(Kind.IF_STATEMENT)) { visitIfStatement((IfStatementTree) tree); } else if (tree.is(Kind.BLOCK)) { visitBlock((BlockTree) tree); } else if (tree.is(Kind.EXPRESSION_STATEMENT)) { currentBlock.addElement(tree); } else { throw new UnsupportedOperationException("Not supported tree kind " + tree.getKind()); } }
Source:
private synchronized void closeContext() throws IOException { if (!mClosed.get()) { mClosed.set(true); mFileSystemMasterClientPool.close(); mFileSystemMasterClientPool = null; mBlockMasterClientPool.close(); mBlockMasterClientPool = null; for (BlockWorkerClientPool pool : mBlockWorkerClientPoolMap.values()) { pool.close(); } mWorkerGroup.shutdownGracefully(1L, 10L, TimeUnit.SECONDS); mBlockWorkerClientPoolMap = null; mLocalWorkerInitialized = false; mLocalWorker = null; if (mMetricsEnabled) { MetricsHeartbeatContext.removeHeartbeat(getClientContext()); } } else { LOG.warn("Attempted to close FileSystemContext which has already been closed or not " + "initialized."); } }

Target:
private synchronized void closeContext() throws IOException { if (!mClosed.get()) { mClosed.set(true); mFileSystemMasterClientPool.close(); mFileSystemMasterClientPool = null; mBlockMasterClientPool.close(); mBlockMasterClientPool = null; for (BlockWorkerClientPool pool : mBlockWorkerClientPoolMap.values()) { pool.close(); } mWorkerGroup.shutdownGracefully(1L, 10L, TimeUnit.SECONDS); mBlockWorkerClientPoolMap.clear(); mBlockWorkerClientPoolMap = null; mLocalWorkerInitialized = false; mLocalWorker = null; if (mMetricsEnabled) { MetricsHeartbeatContext.removeHeartbeat(getClientContext()); } } else { LOG.warn("Attempted to close FileSystemContext which has already been closed or not " + "initialized."); } }
Source:
public MockMethodAdvice(WeakConcurrentMap<Object, MockMethodInterceptor> interceptors, String identifier) { this.interceptors = interceptors; this.identifier = identifier; try { Field field = WeakConcurrentMap.class.getDeclaredField("target"); field.setAccessible(true); backingMap = field.get(interceptors); } catch (Exception e) { throw new MockitoException("Could not resolve backing map from concurrent hash map", e); } }

Target:
public MockMethodAdvice(WeakConcurrentMap<Object, MockMethodInterceptor> interceptors, String identifier) { this.interceptors = interceptors; this.identifier = identifier; }
Source:
public Map<MultiKey, Map<String, String>> getAllMaps() { final Lock readLock = startStopSync.readLock(); readLock.lock(); try { if (!started) { throw new ISE("Factory [%s] not started", extractorID); } String preVersion = null, postVersion = null; Map<MultiKey, Map<String, String>> mapMap = null; do { preVersion = manager.getVersion(extractorID); if (preVersion == null) { throw new ISE("Namespace vanished for [%s]", extractorID); } mapMap = manager.getCacheMap(extractorID); postVersion = manager.getVersion(extractorID); if (postVersion == null) { manager.delete(extractorID); throw new ISE("Lookup [%s] is deleting", extractorID); } } while (!preVersion.equals(postVersion)); return mapMap; } finally { readLock.unlock(); } }

Target:
public Map<Pair, Map<String, String>> getAllMaps() { final Lock readLock = startStopSync.readLock(); readLock.lock(); try { if (!started) { throw new ISE("Factory [%s] not started", extractorID); } String preVersion = null, postVersion = null; Map<Pair, Map<String, String>> mapMap = null; do { preVersion = manager.getVersion(extractorID); if (preVersion == null) { throw new ISE("Namespace vanished for [%s]", extractorID); } mapMap = manager.getCacheMap(extractorID); postVersion = manager.getVersion(extractorID); if (postVersion == null) { manager.delete(extractorID); throw new ISE("Lookup [%s] is deleting", extractorID); } } while (!preVersion.equals(postVersion)); return mapMap; } finally { readLock.unlock(); } }
Source:
public static void testExistsEmployee(DataStore<String, Employee> dataStore) throws Exception { dataStore.createSchema(); Employee employee = DataStoreTestUtil.createEmployee(); String ssn = employee.getSsn().toString(); dataStore.put(ssn, employee); dataStore.flush(); assertTrue(dataStore.exists(ssn)); dataStore.delete(ssn); dataStore.flush(); assertFalse(dataStore.exists(ssn)); }

Target:
public static void testExistsEmployee(DataStore<String, Employee> dataStore) throws Exception { dataStore.createSchema(); Employee employee = DataStoreTestUtil.createEmployee(); String uuid = UUID.randomUUID().toString(); dataStore.put(uuid, employee); dataStore.flush(); assertTrue(dataStore.exists(uuid)); dataStore.delete(uuid); dataStore.flush(); assertFalse(dataStore.exists(uuid)); }
Source:
public void resetUsbPlug() throws IOException, JadbException { try (InputStream stream = device.executeShell("dumpsys", "battery", "reset")) { Stream.flushRead(stream); stream.close(); } }

Target:
public void resetUsbPlug() throws IOException, JadbException { try (InputStream stream = device.executeShell("dumpsys", "battery", "reset")) { Stream.flushRead(stream); } }
Source:
public double avgTimePerElem() { return sum / elemCount / 1000.0D; }

Target:
public double avgTimePerElem() { if (elemCount == 0) { return Double.POSITIVE_INFINITY; } return sum / elemCount / 1000.0D; }
Source:
private static Response invalid_request(final String message) { return Response.status(Response.Status.BAD_REQUEST).entity(message).build(); }

Target:
private static Response invalid_request(final String message) { return Response.status(Response.Status.BAD_REQUEST) .entity(new JsonError(400, message)) .type(MediaType.APPLICATION_JSON_TYPE) .build(); }
Source:
public boolean visitEnter(ComparisonParseNode node) throws SQLException { return true; }

Target:
public boolean visitEnter(ComparisonParseNode node) { return true; }
Source:
private static boolean isAloneOnLine(Details details, String targetSrcLine) { final DetailAST rcurly = details.rcurly; final DetailAST nextToken = details.nextToken; return rcurly.getLineNo() != nextToken.getLineNo() && CommonUtils.hasWhitespaceBefore(details.rcurly.getColumnNo(), targetSrcLine); }

Target:
private static boolean isAloneOnLine(Details details, String targetSrcLine) { final DetailAST rcurly = details.rcurly; final DetailAST nextToken = details.nextToken; return (rcurly.getLineNo() != nextToken.getLineNo() || skipDoubleBraceInstInit(details)) && CommonUtil.hasWhitespaceBefore(details.rcurly.getColumnNo(), targetSrcLine); }
Source:
static BookKeeper createBookKeeperClient(ServerConfiguration conf) throws InterruptedException, IOException { ClientConfiguration clientConfiguration = new ClientConfiguration(conf); clientConfiguration.setClientRole(ClientConfiguration.CLIENT_ROLE_SYSTEM); LOG.info("AuthProvider used by the Auditor is {}", clientConfiguration.getClientAuthProviderFactoryClass()); try { return BookKeeper.forConfig(clientConfiguration).build(); } catch (BKException e) { throw new IOException("Failed to create bookkeeper client", e); } }

Target:
static BookKeeper createBookKeeperClient(ServerConfiguration conf) throws InterruptedException, IOException { ClientConfiguration clientConfiguration = new ClientConfiguration(conf); clientConfiguration.setClientRole(ClientConfiguration.CLIENT_ROLE_SYSTEM); try { return BookKeeper.forConfig(clientConfiguration).build(); } catch (BKException e) { throw new IOException("Failed to create bookkeeper client", e); } }
Source:
public void setTag(@NonNull String key, @NonNull Object tag) { if (mTag == null) { mTag = new SessionConfigTagMap(); } ((SessionConfigTagMap) mTag).setTagMap(key, tag); }

Target:
public void setTag(@NonNull String key, @NonNull Object tag) { if (mTag == null) { mTag = new TagBundle(); } mTag.putTag(key, tag); }
Source:
public static void udpateUserRoleMappingWithExactParams(Connection dbConnection, String sqlStmt, String[] roles, String userName, Integer[] tenantIds, int currentTenantId) throws UserStoreException { boolean localConnection = false; try (PreparedStatement ps = dbConnection.prepareStatement(sqlStmt)){ byte count = 0; byte index = 0; for (String role : roles) { count = 0; ps.setString(++count, role); ps.setInt(++count, tenantIds[index]); ps.setString(++count, userName); ps.setInt(++count, currentTenantId); ps.setInt(++count, currentTenantId); ps.setInt(++count, tenantIds[index]); ps.addBatch(); ++index; } int[] cnt = ps.executeBatch(); if (log.isDebugEnabled()) { log.debug("Executed a batch update. Query is : " + sqlStmt + ": and result is" + Arrays.toString(cnt)); } if (localConnection) { dbConnection.commit(); } } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { close(dbConnection); } }

Target:
public static void udpateUserRoleMappingWithExactParams(Connection dbConnection, String sqlStmt, String[] roles, String userName, Integer[] tenantIds, int currentTenantId) throws UserStoreException { boolean localConnection = false; try (PreparedStatement ps = dbConnection.prepareStatement(sqlStmt)){ byte count = 0; byte index = 0; for (String role : roles) { count = 0; ps.setString(++count, role); ps.setInt(++count, tenantIds[index]); ps.setString(++count, userName); ps.setInt(++count, currentTenantId); ps.setInt(++count, currentTenantId); ps.setInt(++count, tenantIds[index]); ps.addBatch(); ++index; } int[] cnt = ps.executeBatch(); if (log.isDebugEnabled()) { log.debug("Executed a batch update. Query is : " + sqlStmt + ": and result is" + Arrays.toString(cnt)); } if (localConnection) { dbConnection.commit(); } } catch (SQLException e) { String errorMessage = "Using sql : " + sqlStmt + " " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { if(localConnection){ close(dbConnection); } } }
Source:
public void testRangeRequestCompositeBlob() throws Exception { for (int i = 0; i < 5; i++) { blobSize = random.nextInt(maxChunkSize) + maxChunkSize * random.nextInt(10); int randomOne = random.nextInt(blobSize); int randomTwo = random.nextInt(blobSize); testRangeRequestClosedRange(Math.min(randomOne, randomTwo), Math.max(randomOne, randomTwo), true); } blobSize = random.nextInt(maxChunkSize) + maxChunkSize * random.nextInt(10); testRangeRequestClosedRange(0, blobSize - 1, true); testRangeRequestOpenRange(random.nextInt(blobSize), true); testRangeRequestLastNBytes(random.nextInt(blobSize) + 1, true); testRangeRequestLastNBytes(blobSize + 1, false); testRangeRequestClosedRange(random.nextInt(blobSize), blobSize + 5, false); testRangeRequestOpenRange(blobSize, false); testRangeRequestClosedRange(blobSize, blobSize + 20, false); testRangeRequestLastNBytes(0, true); blobSize = maxChunkSize * 2 + random.nextInt(maxChunkSize); testRangeRequestClosedRange(0, maxChunkSize - 1, true); testRangeRequestClosedRange(maxChunkSize, maxChunkSize * 2 - 1, true); testRangeRequestClosedRange(maxChunkSize * 2, blobSize - 1, true); }

Target:
public void testRangeRequestCompositeBlob() throws Exception { for (int i = 0; i < 5; i++) { blobSize = random.nextInt(maxChunkSize) + maxChunkSize * random.nextInt(10); int randomOne = random.nextInt(blobSize); int randomTwo = random.nextInt(blobSize); testRangeRequestOffsetRange(Math.min(randomOne, randomTwo), Math.max(randomOne, randomTwo), true); } blobSize = random.nextInt(maxChunkSize) + maxChunkSize * random.nextInt(10); testRangeRequestOffsetRange(0, blobSize - 1, true); testRangeRequestFromStartOffset(random.nextInt(blobSize), true); testRangeRequestLastNBytes(random.nextInt(blobSize) + 1, true); testRangeRequestLastNBytes(blobSize + 1, false); testRangeRequestOffsetRange(random.nextInt(blobSize), blobSize + 5, false); testRangeRequestFromStartOffset(blobSize, false); testRangeRequestOffsetRange(blobSize, blobSize + 20, false); testRangeRequestLastNBytes(0, true); testRangeRequestOffsetRange(0, 0, true); testRangeRequestOffsetRange(blobSize - 1, blobSize - 1, true); testRangeRequestFromStartOffset(blobSize - 1, true); testRangeRequestLastNBytes(1, true); blobSize = maxChunkSize * 2 + random.nextInt(maxChunkSize); testRangeRequestOffsetRange(0, maxChunkSize - 1, true); testRangeRequestOffsetRange(maxChunkSize, maxChunkSize * 2 - 1, true); testRangeRequestOffsetRange(maxChunkSize * 2, blobSize - 1, true); testRangeRequestOffsetRange(maxChunkSize / 2, maxChunkSize + maxChunkSize / 2, true); testRangeRequestFromStartOffset(maxChunkSize + maxChunkSize / 2, true); }
Source:
public void test_add_1() { HuffmanParamsCalculator c = new HuffmanParamsCalculator(); c.add(1); c.calculate(); int[] values = c.getValues(); int[] bitLens = c.getBitLens(); Assert.assertEquals(1, values.length); Assert.assertEquals(1, bitLens.length); Assert.assertEquals(1, values[0]); Assert.assertEquals(0, bitLens[0]); }

Target:
public void test_add_1() { final HuffmanParamsCalculator c = new HuffmanParamsCalculator(); c.addOne(1); c.calculate(); final int[] values = c.getValues(); final int[] bitLens = c.getBitLens(); Assert.assertEquals(1, values.length); Assert.assertEquals(1, bitLens.length); Assert.assertEquals(1, values[0]); Assert.assertEquals(0, bitLens[0]); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Condition condition = (Condition) o; return Objects.equals(cf, condition.cf) && Objects.equals(cq, condition.cq) && Objects.equals(cv, condition.cv) && Objects.equals(val, condition.val) && Objects.equals(ts, condition.ts) && Arrays.equals(iterators, condition.iterators); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Condition)) return false; Condition condition = (Condition) o; return Objects.equals(cf, condition.cf) && Objects.equals(cq, condition.cq) && Objects.equals(cv, condition.cv) && Objects.equals(val, condition.val) && Objects.equals(ts, condition.ts) && Arrays.equals(iterators, condition.iterators); }
Source:
public static CatalogDto newDtoFromUrl(String url) { log.debug("Retrieving catalog from: "+url); try { InputStream source = new ResourceUtils(null).getResourceFromUrl(url); return (CatalogDto) new CatalogXmlSerializer().deserialize(new InputStreamReader(source)); } catch (Throwable t) { log.debug("Unable to retrieve catalog from: "+url+" ("+t+")"); throw Exceptions.propagate(t); } finally { log.debug("Retrieved catalog from: "+url); } }

Target:
public static CatalogDto newDtoFromUrl(String url) { if (log.isDebugEnabled()) log.debug("Retrieving catalog from: {}", url); try { InputStream source = new ResourceUtils(null).getResourceFromUrl(url); CatalogDto result = (CatalogDto) new CatalogXmlSerializer().deserialize(new InputStreamReader(source)); if (log.isDebugEnabled()) log.debug("Retrieved catalog from: {}", url); return result; } catch (Throwable t) { log.debug("Unable to retrieve catalog from: "+url+" ("+t+")"); throw Exceptions.propagate(t); } }