auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private LegendRequest addLayer(LayerInfo layerInfo, GetLegendGraphicRequest request) throws FactoryRegistryException, IOException, TransformException, SchemaException { FeatureType featureType=getLayerFeatureType(layerInfo); if(featureType != null) { LegendRequest legend = request.new LegendRequest(featureType); legend.setLayerInfo( layerInfo ); MapLayerInfo mli=new MapLayerInfo(layerInfo); if(mli.getLabel() != null) { legend.setTitle( mli.getLabel() ); } LegendInfo legendInfo = resolveLegendInfo(layerInfo.getLegend(),request); if(legendInfo != null ){ legend.setLegendInfo( legendInfo ); if (legendInfo.getHeight() > 0 && !request.getKvp().containsKey("HEIGHT")) { request.setHeight(legendInfo.getHeight()); } if (legendInfo.getWidth() > 0 && !request.getKvp().containsKey("WIDTH")) { request.setWidth(legendInfo.getWidth()); } } return legend; } else { throw new ServiceException("Cannot get FeatureType for Layer", "MissingFeatureType"); } }

Target:
private LegendRequest addLayer(LayerInfo layerInfo, GetLegendGraphicRequest request) throws FactoryRegistryException, IOException, TransformException, SchemaException { FeatureType featureType=getLayerFeatureType(layerInfo); if(featureType != null) { LegendRequest legend = request.new LegendRequest(featureType); legend.setLayerInfo( layerInfo ); MapLayerInfo mli=new MapLayerInfo(layerInfo); if(mli.getLabel() != null) { legend.setTitle( mli.getLabel() ); } LegendInfo legendInfo = resolveLegendInfo(layerInfo.getLegend(),request); if(legendInfo != null ){ configureLegendInfo(request, legend, legendInfo); } return legend; } else { throw new ServiceException("Cannot get FeatureType for Layer", "MissingFeatureType"); } }
Source:
static FileJournalEntry parse(final String entry) { String[] elements = entry.split(","); if (elements.length < 4) { throw new IllegalArgumentException("Invalid journal entry: " + entry); } return new FileJournalEntry(elements[INDEX_TOKEN_ID], elements[INDEX_ISSUE_TIME], elements[INDEX_EXPIRATION], elements[INDEX_MAX_LIFETIME]); }

Target:
static FileJournalEntry parse(final String entry) { String[] elements = entry.split(","); if (elements.length < 4) { throw new IllegalArgumentException("Invalid journal entry: " + entry); } String tokenId = elements[INDEX_TOKEN_ID].trim(); String issueTime = elements[INDEX_ISSUE_TIME].trim(); String expiration = elements[INDEX_EXPIRATION].trim(); String maxLifetime = elements[INDEX_MAX_LIFETIME].trim(); return new FileJournalEntry(tokenId.isEmpty() ? null : tokenId, issueTime.isEmpty() ? null : issueTime, expiration.isEmpty() ? null : expiration, maxLifetime.isEmpty() ? null : maxLifetime); }
Source:
protected String getJenkinsInstanceId() { return JenkinsUtils.getInstanceId(); }

Target:
protected String getJenkinsInstanceId() { return DockerTemplateBase.getJenkinsInstanceIdForContainerLabel(); }
Source:
public void evaluate_shouldGetGenderOfAPatient() throws Exception { Patient patient = Context.getPatientService().getPatient(8); Patient patient1 = Context.getPatientService().getPatient(2); Assert.assertTrue("patient returned null",patient!=null); Assert.assertTrue("patient1 returned null",patient1!=null); String expectedString="F"; String expectedString1="M"; MohGenderRule mohGenderRule = new MohGenderRule(); String foundString= mohGenderRule.evaluate(null,patient.getId(),null).toString(); String foundString1= mohGenderRule.evaluate(null,patient1.getId(),null).toString(); Assert.assertTrue(foundString, expectedString.equals(foundString)); Assert.assertTrue(foundString1, expectedString1.equals(foundString1)); }

Target:
public void evaluate_shouldGetGenderOfAPatient() throws Exception { Patient patient = Context.getPatientService().getPatient(8); Patient patient1 = Context.getPatientService().getPatient(2); Assert.assertNotNull("patient returned null",patient); Assert.assertNotNull("patient1 returned null",patient1); String expectedString="F"; String expectedString1="M"; MohGenderRule mohGenderRule = new MohGenderRule(); String foundString= mohGenderRule.evaluate(null,patient.getId(),null).toString(); String foundString1= mohGenderRule.evaluate(null,patient1.getId(),null).toString(); Assert.assertEquals("Female was not found",expectedString, foundString); Assert.assertEquals("Male was not found",expectedString1, foundString1); }
Source:
Mono<Response<ExtractKeyPhraseResult>> extractKeyPhrasesWithResponse(String text, String language, Context context) { return extractBatchKeyPhrasesWithResponse( Arrays.asList(new TextDocumentInput(Integer.toString(0), text, language)), null, context) .flatMap(response -> { Iterator<ExtractKeyPhraseResult> responseItem = response.getValue().iterator(); return Mono.just(new SimpleResponse<>(response, responseItem.next())); }); }

Target:
Mono<Response<ExtractKeyPhraseResult>> extractKeyPhrasesWithResponse(String text, String language, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); return extractBatchKeyPhrasesWithResponse( Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); }
Source:
private static boolean isWebpackRequireEnsureCallback(Node fnc) { checkArgument(fnc.isFunction()); if (fnc.getParent() == null) { return false; } Node callParent = fnc.getParent(); if (!callParent.isCall()) { return false; } if (callParent.getFirstChild() != null && callParent.getFirstChild().isGetProp() && callParent.getFirstFirstChild().isCall() && callParent .getFirstFirstChild() .getFirstChild() .matchesQualifiedName(WEBPACK_REQUIRE + ".e") && callParent.getFirstChild().getSecondChild().isString() && callParent.getFirstChild().getSecondChild().getString().equals("then")) { return true; } return false; }

Target:
private static boolean isWebpackRequireEnsureCallback(Node fnc) { checkArgument(fnc.isFunction()); if (fnc.getParent() == null) { return false; } Node callParent = fnc.getParent(); if (!callParent.isCall()) { return false; } if (callParent.hasChildren() && callParent.getFirstChild().isGetProp() && callParent.getFirstFirstChild().isCall() && callParent .getFirstFirstChild() .getFirstChild() .matchesQualifiedName(WEBPACK_REQUIRE + ".e") && callParent.getFirstChild().getSecondChild().isString() && callParent.getFirstChild().getSecondChild().getString().equals("then")) { return true; } return false; }
Source:
@Override protected ImmutableListValue<Living> constructValue(List<Living> defaultValue) { return new ImmutableSpongeListValue<>(Keys.TARGETS, ImmutableList.copyOf(defaultValue)); }

Target:
protected ImmutableListValue<Living> constructValue(List<Living> defaultValue) { return new ImmutableSpongeListValue<>(Keys.TARGETS, ImmutableList.copyOf(defaultValue)); }
Source:
void runOnce() { if (transactionManager != null) { try { transactionManager.resetProducerIdIfNeeded(); if (!transactionManager.isTransactional()) { maybeWaitForProducerId(); } else if (transactionManager.hasUnresolvedSequences() && !transactionManager.hasFatalError()) { transactionManager.transitionToFatalError( new KafkaException("The client hasn't received acknowledgment for " + "some previously sent messages and can no longer retry them. It isn't safe to continue.")); } else if (maybeSendAndPollTransactionalRequest()) { return; } if (transactionManager.hasFatalError() || !transactionManager.hasProducerId()) { RuntimeException lastError = transactionManager.lastError(); if (lastError != null) maybeAbortBatches(lastError); client.poll(retryBackoffMs, time.milliseconds()); return; } else if (transactionManager.hasAbortableError()) { if (accumulator.abortUndrainedBatches(transactionManager.lastError())) { return; } } } catch (AuthenticationException e) { log.trace("Authentication exception while processing transactional request: {}", e); transactionManager.authenticationFailed(e); } } long currentTimeMs = time.milliseconds(); long pollTimeout = sendProducerData(currentTimeMs); client.poll(pollTimeout, currentTimeMs); }

Target:
void runOnce() { if (transactionManager != null) { try { transactionManager.resetProducerIdIfNeeded(); if (!transactionManager.isTransactional()) { maybeWaitForProducerId(); } else if (transactionManager.hasUnresolvedSequences() && !transactionManager.hasFatalError()) { transactionManager.transitionToFatalError( new KafkaException("The client hasn't received acknowledgment for " + "some previously sent messages and can no longer retry them. It isn't safe to continue.")); } else if (maybeSendAndPollTransactionalRequest()) { return; } if (transactionManager.hasFatalError() || !transactionManager.hasProducerId()) { RuntimeException lastError = transactionManager.lastError(); if (lastError != null) maybeAbortBatches(lastError); client.poll(retryBackoffMs, time.milliseconds()); return; } } catch (AuthenticationException e) { log.trace("Authentication exception while processing transactional request: {}", e); transactionManager.authenticationFailed(e); } } long currentTimeMs = time.milliseconds(); long pollTimeout = sendProducerData(currentTimeMs); client.poll(pollTimeout, currentTimeMs); }
Source:
public void handleUpdate(List<MetadataMappingDescriptor> mappingDescriptors, DocumentModel doc) { for (MetadataMappingDescriptor mappingDescriptor : mappingDescriptors) { Property fileProp = doc.getProperty(mappingDescriptor.getBlobXPath()); Blob blob = fileProp.getValue(Blob.class); if (blob != null) { boolean isDirtyMapping = isDirtyMapping(mappingDescriptor, doc); if (isDirtyMapping) { if(!mappingDescriptor.getReadOnly()) { BlobManager blobManager = Framework.getService(BlobManager.class); BlobProvider blobProvider = blobManager.getBlobProvider(blob); if (blobProvider != null && (!blobProvider.supportsUserUpdate() || blobProvider.getBinaryManager() == null)) { return; } Blob newBlob = writeMetadata(mappingDescriptor.getProcessor(), fileProp.getValue(Blob.class), mappingDescriptor.getId(), doc); fileProp.setValue(newBlob); } } else if (fileProp.isDirty()) { writeMetadata(doc); } } } }

Target:
public void handleUpdate(List<MetadataMappingDescriptor> mappingDescriptors, DocumentModel doc) { for (MetadataMappingDescriptor mappingDescriptor : mappingDescriptors) { Property fileProp = doc.getProperty(mappingDescriptor.getBlobXPath()); Blob blob = fileProp.getValue(Blob.class); if (blob != null) { boolean isDirtyMapping = isDirtyMapping(mappingDescriptor, doc); if (isDirtyMapping) { if (!mappingDescriptor.isReadOnly()) { BlobManager blobManager = Framework.getService(BlobManager.class); BlobProvider blobProvider = blobManager.getBlobProvider(blob); if (blobProvider != null && (!blobProvider.supportsUserUpdate() || blobProvider.getBinaryManager() == null)) { return; } Blob newBlob = writeMetadata(mappingDescriptor.getProcessor(), fileProp.getValue(Blob.class), mappingDescriptor.getId(), doc); fileProp.setValue(newBlob); } } else if (fileProp.isDirty()) { writeMetadata(doc); } } } }
Source:
public void serialize() throws IOException, ClassNotFoundException { IntHashMap<String> map = new IntHashMap<>(); map.put(1, "one"); map.put(2, "two"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(map); byte[] serialized = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(serialized); ObjectInputStream ois = new ObjectInputStream(bais); IntHashMap<String> deserialized = (IntHashMap<String>) ois.readObject(); assertNotNull(deserialized); assertEquals(deserialized.get(1), "one"); assertEquals(deserialized.get(2), "two"); deserialized.put(3, "three"); deserialized.entrySet().iterator(); }

Target:
void serialize() throws IOException, ClassNotFoundException { IntHashMap<String> map = new IntHashMap<>(); map.put(1, "one"); map.put(2, "two"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(map); byte[] serialized = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(serialized); ObjectInputStream ois = new ObjectInputStream(bais); IntHashMap<String> deserialized = (IntHashMap<String>)ois.readObject(); assertNotNull(deserialized); assertEquals("one", deserialized.get(1)); assertEquals("two", deserialized.get(2)); deserialized.put(3, "three"); deserialized.entrySet().iterator(); }
Source:
public NetClient(ChannelHandlerContext ctx) { this.channel = ctx.channel(); this.currentState = NetState.HANDSHAKE; this.channel.closeFuture().addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> future) throws Exception { NetClient.this.disconnect(ChatComponent.empty()); future.removeListener(this); } }); }

Target:
public NetClient(ChannelHandlerContext ctx) { this.channel = ctx.channel(); this.currentState = NetState.HANDSHAKE; this.channel.closeFuture().addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> future) throws Exception { NetClient.this.disconnect(EMPTY); future.removeListener(this); } }); }
Source:
private AuditLogableBase createEvent() { final AuditLogableBase event = new AuditLogableBase(); event.setVds(host); return event; }

Target:
private AuditLogableBase createEvent() { final AuditLogableBase event = new AuditLogableBase(); event.setVdsName(host.getName()); return event; }
Source:
public static String replaceSubstringInBetween(final String str, final String replace, final String open, final String close) { if (str == null || open == null || close == null) { return null; } final int start = str.indexOf(open); if (start != INDEX_NOT_FOUND) { String preceding = ""; if (start > 0) { preceding = str.substring(0, start); } final int end = str.indexOf(close, start + open.length()); if (end != INDEX_NOT_FOUND) { String exceding = ""; if ((end < str.length() - 1) && (end + close.length() < str.length())) { exceding = str.substring(end + close.length(), str.length()); } return preceding + open + replace + close + exceding; } } return null; }

Target:
public static String replaceSubstringInBetween(final String str, final String replace, final String open, final String close) { if (str == null) { return null; } if (open == null || close == null) { return str; } final int start = str.indexOf(open); if (start != INDEX_NOT_FOUND) { String preceding = str.substring(0, start); final int end = str.indexOf(close, start + open.length()); if (end != INDEX_NOT_FOUND) { String exceeding = str.substring(end + close.length(), str.length()); return preceding + open + replace + close + exceeding; } } return str; }
Source:
public String[] getCatalogNames() { Connection connection = getConnection(); DatabaseMetaData metaData = null; ResultSet rs = null; try { metaData = connection.getMetaData(); } catch (SQLException e) { throw JdbcUtils.wrapException(e, "retrieve metadata", JdbcActionType.METADATA); } logger.debug("Retrieving catalogs"); List<String> catalogs = new ArrayList<>(); try { rs = metaData.getCatalogs(); while (rs.next()) { String catalogName = rs.getString(1); logger.debug("Found catalogName: {}", catalogName); catalogs.add(catalogName); } } catch (SQLException e) { logger.error("Error retrieving catalog metadata", e); } finally { if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } close(connection); logger.debug("Retrieved catalogs", catalogs.size()); } return catalogs.toArray(new String[catalogs.size()]); }

Target:
public String[] getCatalogNames() { Connection connection = getConnection(); DatabaseMetaData metaData = null; ResultSet rs = null; try { metaData = connection.getMetaData(); } catch (SQLException e) { throw JdbcUtils.wrapException(e, "retrieve metadata", JdbcActionType.METADATA); } logger.debug("Retrieving catalogs"); List<String> catalogs = new ArrayList<>(); try { rs = metaData.getCatalogs(); while (rs.next()) { String catalogName = rs.getString(1); logger.debug("Found catalogName: {}", catalogName); catalogs.add(catalogName); } } catch (SQLException e) { logger.error("Error retrieving catalog metadata", e); } finally { FileHelper.safeClose(rs); close(connection); logger.debug("Retrieved catalogs", catalogs.size()); } return catalogs.toArray(new String[catalogs.size()]); }
Source:
public void createCartWithALineItemWithAnExternalPrice() { withProduct(client(), product -> { final int quantity = 5; final int variantId = 1; final Money externalPrice = Money.from(EURO_12); final LineItemDraft lineItemDraft = LineItemDraft.of(product, variantId, quantity) .withExternalPrice(externalPrice); withCartWithLineItems(client(), singletonList(lineItemDraft), cart -> { final LineItem cartLineItem = cart.getLineItems().get(0); assertThat(cartLineItem.getPrice().getValue()).isEqualTo(externalPrice); assertThat(cartLineItem.getPriceMode()).isEqualTo(EXTERNAL_PRICE); return cart; }); }); }

Target:
public void createCartWithALineItemWithAnExternalPrice() { withProduct(client(), product -> { final int quantity = 5; final int variantId = 1; final MonetaryAmount externalPrice = EURO_12; final LineItemDraft lineItemDraft = LineItemDraft.of(product, variantId, quantity) .withExternalPrice(externalPrice); withCartWithLineItems(client(), singletonList(lineItemDraft), cart -> { final LineItem cartLineItem = cart.getLineItems().get(0); assertThat(cartLineItem.getPrice().getValue()).isEqualTo(externalPrice); assertThat(cartLineItem.getPriceMode()).isEqualTo(EXTERNAL_PRICE); return cart; }); }); }
Source:
public void testEncryptDecryptWithEmptyPlaintext() throws GeneralSecurityException { for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = new byte[0]; byte[] aad = Random.randBytes(Random.randInt(128) + 1); byte[] ciphertext = dead.encryptDeterministically(plaintext, aad); byte[] rebuiltPlaintext = dead.decryptDeterministically(ciphertext, aad); assertEquals(AesUtil.BLOCK_SIZE, ciphertext.length); assertEquals(Hex.encode(plaintext), Hex.encode(rebuiltPlaintext)); byte[] nullAadCiphertext = dead.encryptDeterministically(plaintext, null); byte[] nullAadDecryptedText = dead.encryptDeterministically(plaintext, null); assertEquals(AesUtil.BLOCK_SIZE, nullAadCiphertext.length); assertEquals(Hex.encode(nullAadDecryptedText), Hex.encode(nullAadCiphertext)); } } }

Target:
public void testEncryptDecryptWithEmptyPlaintext() throws GeneralSecurityException { for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = new byte[0]; byte[] aad = Random.randBytes(Random.randInt(128) + 1); byte[] ciphertext = dead.encryptDeterministically(plaintext, aad); byte[] rebuiltPlaintext = dead.decryptDeterministically(ciphertext, aad); assertEquals(AesUtil.BLOCK_SIZE, ciphertext.length); assertEquals(Hex.encode(plaintext), Hex.encode(rebuiltPlaintext)); } } }
Source:
public boolean hasDSpacePermission(Authentication authentication, Serializable targetId, String targetType, DSpaceRestPermission permission) { if (!StringUtils.equals("POOLTASK", targetType)) { return false; } Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson == null) { return false; } Integer dsoId = Integer.parseInt(targetId.toString()); PoolTask poolTask = poolTaskService.find(context, dsoId); if (poolTask == null) { return true; } XmlWorkflowItem workflowItem = poolTask.getWorkflowItem(); PoolTask poolTask2 = poolTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson); if (poolTask2 != null && poolTask2.getID() == poolTask.getID()) { return true; } } catch (SQLException | AuthorizeException | IOException e) { log.error(e.getMessage(), e); } return false; }

Target:
public boolean hasDSpacePermission(Authentication authentication, Serializable targetId, String targetType, DSpaceRestPermission permission) { if (!StringUtils.equalsIgnoreCase(PoolTaskRest.NAME, targetType)) { return false; } Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson == null) { return false; } Integer dsoId = Integer.parseInt(targetId.toString()); PoolTask poolTask = poolTaskService.find(context, dsoId); if (poolTask == null) { return true; } XmlWorkflowItem workflowItem = poolTask.getWorkflowItem(); PoolTask poolTask2 = poolTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson); if (poolTask2 != null && poolTask2.getID() == poolTask.getID()) { return true; } } catch (SQLException | AuthorizeException | IOException e) { log.error(e.getMessage(), e); } return false; }
Source:
private void addQuadWithAlpha(MatrixStack.Entry matrixEntryIn, BakedQuad quadIn, Vector4f color, int light, int combinedOverlayIn, IVertexBuilder builder) { int[] vertexData = quadIn.getVertexData(); Vec3i normalInt = quadIn.getFace().getDirectionVec(); Vector3f normal = new Vector3f(normalInt.getX(), normalInt.getY(), normalInt.getZ()); Matrix4f transform = matrixEntryIn.getMatrix(); normal.transform(matrixEntryIn.getNormal()); int intSize = DefaultVertexFormats.BLOCK.getIntegerSize(); int j = vertexData.length/intSize; try(MemoryStack memorystack = MemoryStack.stackPush()) { ByteBuffer bytebuffer = memorystack.malloc(DefaultVertexFormats.BLOCK.getSize()); IntBuffer intbuffer = bytebuffer.asIntBuffer(); for(int i = 0; i < j; ++i) { intbuffer.clear(); intbuffer.put(vertexData, i*intSize, intSize); float x = bytebuffer.getFloat(0); float y = bytebuffer.getFloat(4); float z = bytebuffer.getFloat(8); int lightmapUV = builder.applyBakedLighting(light, bytebuffer); float texU = bytebuffer.getFloat(16); float texV = bytebuffer.getFloat(20); Vector4f vector4f = new Vector4f(x, y, z, 1.0F); vector4f.transform(transform); builder.applyBakedNormals(normal, bytebuffer, matrixEntryIn.getNormal()); builder.addVertex( vector4f.getX(), vector4f.getY(), vector4f.getZ(), color.getX(), color.getY(), color.getZ(), color.getW(), texU, texV, combinedOverlayIn, lightmapUV, normal.getX(), normal.getY(), normal.getZ() ); } } }

Target:
private void addQuadWithAlpha(MatrixStack.Entry matrixEntryIn, BakedQuad quadIn, Vector4f color, int light, int combinedOverlayIn, IVertexBuilder builder) { int[] vertexData = quadIn.getVertexData(); Vec3i normalInt = quadIn.getFace().getDirectionVec(); Vector3f normal = new Vector3f(normalInt.getX(), normalInt.getY(), normalInt.getZ()); Matrix4f transform = matrixEntryIn.getMatrix(); normal.transform(matrixEntryIn.getNormal()); int vertexSize = DefaultVertexFormats.BLOCK.getIntegerSize(); int numVertices = vertexData.length/vertexSize; try(MemoryStack memorystack = MemoryStack.stackPush()) { ByteBuffer bytebuffer = memorystack.malloc(DefaultVertexFormats.BLOCK.getSize()); IntBuffer intbuffer = bytebuffer.asIntBuffer(); for(int i = 0; i < numVertices; ++i) { intbuffer.clear(); intbuffer.put(vertexData, i*vertexSize, vertexSize); float x = bytebuffer.getFloat(0); float y = bytebuffer.getFloat(4); float z = bytebuffer.getFloat(8); int lightmapUV = builder.applyBakedLighting(light, bytebuffer); float texU = bytebuffer.getFloat(16); float texV = bytebuffer.getFloat(20); Vector4f vector4f = new Vector4f(x, y, z, 1.0F); vector4f.transform(transform); builder.applyBakedNormals(normal, bytebuffer, matrixEntryIn.getNormal()); builder.addVertex( vector4f.getX(), vector4f.getY(), vector4f.getZ(), color.getX(), color.getY(), color.getZ(), color.getW(), texU, texV, combinedOverlayIn, lightmapUV, normal.getX(), normal.getY(), normal.getZ() ); } } }
Source:
public void slicesOfTwo() { Series series = new Series("35"); List<String> expected = Arrays.asList("3", "5"); List<String> actual = series.slices(2); assertEquals(expected, actual); }

Target:
public void slicesOfTwo() { Series series = new Series("35"); List<String> expected = Collections.singletonList("35"); List<String> actual = series.slices(2); assertEquals(expected, actual); }
Source:
public JobFactory amazonBucketJobFactory() { return new JobFactory() { @Override public Job createJob(JobExecution jobExecution) { final AmazonBucketJobExecution amazonBucketJobExecution = (AmazonBucketJobExecution) jobExecution; final String targetEntityId = amazonBucketJobExecution.getTargetEntityId(); final String jobExecutionID = amazonBucketJobExecution.getIdentifier(); final String bucket = amazonBucketJobExecution.getBucket(); final String key = amazonBucketJobExecution.getKey(); final String profile = amazonBucketJobExecution.getProfile(); final boolean isExpression = amazonBucketJobExecution.isExpression(); return progress -> ingester .ingest(jobExecutionID, targetEntityId, bucket, key, profile, isExpression, progress); } @Override public JobType getJobType() { JobType result = jobTypeFactory.create("BucketIngest"); result.setLabel("Bucket ingest"); result.setDescription("This job downloads a file from a URL and imports it into MOLGENIS."); result.setSchema(""); result.setJobExecutionType(amazonBucketJobExecutionMetaData); return result; } }; }

Target:
public JobFactory<AmazonBucketJobExecution> amazonBucketJobFactory() { return new JobFactory<AmazonBucketJobExecution>() { @Override public Job createJob(AmazonBucketJobExecution amazonBucketJobExecution) { final String targetEntityId = amazonBucketJobExecution.getTargetEntityId(); final String jobExecutionID = amazonBucketJobExecution.getIdentifier(); final String bucket = amazonBucketJobExecution.getBucket(); final String key = amazonBucketJobExecution.getKey(); final String profile = amazonBucketJobExecution.getProfile(); final String region = amazonBucketJobExecution.getRegion(); final boolean isExpression = amazonBucketJobExecution.isExpression(); return progress -> ingester .ingest(jobExecutionID, targetEntityId, bucket, key, profile, region, isExpression, progress); } }; }
Source:
public synchronized String getNextReassignmentDestination() { if (!initialized) { activeNodes.forEach(node -> nodeBucketCounts.put(node, 0)); bucketNodes.forEach(bucketNode -> nodeBucketCounts.compute(bucketNode.getNodeIdentifier(), (node, bucketCount) -> (bucketCount == null) ? 1 : bucketCount + 1)); initialized = true; } String assignedNode; if (activeNodes.size() > 1) { assignedNode = randomTwoChoices(); } else { assignedNode = activeNodes.get(0); } nodeBucketCounts.compute(assignedNode, (node, count) -> count + 1); return assignedNode; }

Target:
public String getNextReassignmentDestination() { if (!initialized) { for (String node : activeNodes) { nodeBucketCounts.put(node, 0); } for (BucketNode bucketNode : bucketNodes) { nodeBucketCounts.computeIfPresent(bucketNode.getNodeIdentifier(), (node, bucketCount) -> bucketCount + 1); } initialized = true; } String assignedNode; if (activeNodes.size() > 1) { assignedNode = randomTwoChoices(); } else { assignedNode = activeNodes.get(0); } nodeBucketCounts.compute(assignedNode, (node, count) -> count + 1); return assignedNode; }
Source:
private static <T> void collapse(List<ChangeNotification<T>> notifications, Map<T, Integer> markers, List<ChangeNotification<T>> result) { for (int i = notifications.size() - 1; i >= 0; i--) { ChangeNotification<T> next = notifications.get(i); T data = next.getData(); if (markers.keySet().contains(data)) { int idx = markers.get(data); if (next.getKind() == Kind.Add && result.get(idx).getKind() == Kind.Modify) { result.set(idx, next); } } else { markers.put(data, result.size()); result.add(next); } } }

Target:
private static <T> void collapse(List<ChangeNotification<T>> notifications, Map<T, Integer> markers, List<ChangeNotification<T>> result) { for (int i = notifications.size() - 1; i >= 0; i--) { ChangeNotification<T> next = notifications.get(i); if(next.isDataNotification()) { T data = next.getData(); if (markers.keySet().contains(data)) { int idx = markers.get(data); if (next.getKind() == Kind.Add && result.get(idx).getKind() == Kind.Modify) { result.set(idx, next); } } else { markers.put(data, result.size()); result.add(next); } } } }
Source:
boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { return true; } if (inFlight.containsKey(op.getURI())) { return false; } pending.remove(op.getURI()); inFlight.put(op.getURI(), op); } return true; }

Target:
boolean requestRunway (PushOne op) { synchronized (stateLock) { if (op.wasCanceled()) { return true; } pending.remove(op.getURI()); if (inFlight.containsKey(op.getURI())) { return false; } inFlight.put(op.getURI(), op); } return true; }
Source:
public Collection<String> staticLabels() { Collection<String> knownStaticLabels = this.staticLabels; if (knownStaticLabels == null) { synchronized (this) { knownStaticLabels = this.staticLabels; if (knownStaticLabels == null) { this.staticLabels = Collections.unmodifiableCollection(collectLabels(new ArrayList<>())); knownStaticLabels = this.staticLabels; } } } return knownStaticLabels; }

Target:
public Collection<String> staticLabels() { Collection<String> knownStaticLabels = this.staticLabels; if (knownStaticLabels == null) { synchronized (this) { knownStaticLabels = this.staticLabels; if (knownStaticLabels == null) { this.staticLabels = Collections.unmodifiableCollection(collectLabels()); knownStaticLabels = this.staticLabels; } } } return knownStaticLabels; }
Source:
private Map<String, Diagram> createDiagramMap() { final Map<String, Diagram> diagramMap = new HashMap<String, Diagram>(); final List<?> diagramEditors = EditorService.getInstance().getRegisteredEditorParts(); final Iterator<?> it = diagramEditors.iterator(); while (it.hasNext()) { final Object obj = it.next(); if (obj instanceof DiagramEditor) { final DiagramEditor dEditor = (DiagramEditor) obj; Diagram diagram = dEditor.getDiagram(); String diagramName = dEditor.getPartName(); if (diagramName == null) { diagramName = dEditor.getTitle(); } if (diagramName == null) { diagramName = diagram.getName(); } Resource resource = diagram.eResource(); if (resource != null) { URI diagramURI = resource.getURI(); diagramName = diagramURI.toString() + "#" + diagramName; } diagramName = makeNameUnique(diagramName, diagramMap.keySet()); diagramMap.put(diagramName, diagram); } } return diagramMap; }

Target:
private Map<String, Diagram> createDiagramMap() { final Map<String, Diagram> diagramMap = new HashMap<String, Diagram>(); final List<?> diagramEditors = EditorService.getInstance().getRegisteredEditorParts(); final Iterator<?> it = diagramEditors.iterator(); while (it.hasNext()) { final Object obj = it.next(); if (obj instanceof DiagramEditor) { final DiagramEditor dEditor = (DiagramEditor) obj; Diagram diagram = dEditor.getDiagram(); String diagramName = dEditor.getPartName(); if (diagramName == null) { diagramName = dEditor.getTitle(); } if (diagramName == null) { diagramName = diagram.getName(); } Resource resource = diagram.eResource(); if (resource != null) { URI resourceURI = resource.getURI(); diagramName = resourceURI.toString() + "#" + diagramName; } diagramName = makeNameUnique(diagramName, diagramMap.keySet()); diagramMap.put(diagramName, diagram); } } return diagramMap; }
Source:
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpResponse && WebSocketExtensionUtil.isWebsocketUpgrade(((HttpResponse) msg).headers())) { if (validExtensions != null) { HttpResponse response = (HttpResponse) msg; String headerValue = response.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS); for (WebSocketServerExtension extension : validExtensions) { WebSocketExtensionData extensionData = extension.newReponseData(); headerValue = WebSocketExtensionUtil.appendExtension(headerValue, extensionData.name(), extensionData.parameters()); } promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { for (WebSocketServerExtension extension : validExtensions) { WebSocketExtensionDecoder decoder = extension.newExtensionDecoder(); WebSocketExtensionEncoder encoder = extension.newExtensionEncoder(); ctx.pipeline() .addAfter(ctx.name(), decoder.getClass().getName(), decoder) .addAfter(ctx.name(), encoder.getClass().getName(), encoder); } } } }); if (headerValue != null) { response.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, headerValue); } } promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ctx.pipeline().remove(ctx.name()); } } }); } super.write(ctx, msg, promise); }

Target:
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpResponse) { HttpHeaders headers = ((HttpResponse) msg).headers(); if (WebSocketExtensionUtil.isWebsocketUpgrade(headers)) { if (validExtensions != null) { String headerValue = headers.getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS); for (WebSocketServerExtension extension : validExtensions) { WebSocketExtensionData extensionData = extension.newReponseData(); headerValue = WebSocketExtensionUtil.appendExtension(headerValue, extensionData.name(), extensionData.parameters()); } promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { for (WebSocketServerExtension extension : validExtensions) { WebSocketExtensionDecoder decoder = extension.newExtensionDecoder(); WebSocketExtensionEncoder encoder = extension.newExtensionEncoder(); ctx.pipeline() .addAfter(ctx.name(), decoder.getClass().getName(), decoder) .addAfter(ctx.name(), encoder.getClass().getName(), encoder); } } } }); if (headerValue != null) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, headerValue); } } promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { ctx.pipeline().remove(WebSocketServerExtensionHandler.this); } } }); } } super.write(ctx, msg, promise); }
Source:
public Command exec(String command) throws ConnectionException, TransportException { checkReuse(); log.debug("Will request to exec `{}`", command); sendChannelRequest("exec", true, new Buffer.PlainBuffer().putString(command.getBytes(getRemoteCharset()))) .await(conn.getTimeoutMs(), TimeUnit.MILLISECONDS); usedUp = true; return this; }

Target:
public Command exec(String command) throws ConnectionException, TransportException { checkReuse(); log.debug("Will request to exec `{}`", command); sendChannelRequest("exec", true, new Buffer.PlainBuffer().putString(command, getRemoteCharset())) .await(conn.getTimeoutMs(), TimeUnit.MILLISECONDS); usedUp = true; return this; }
Source:
private static boolean codecNeedsSetOutputSurfaceWorkaround(String name) { return (("deb".equals(Util.DEVICE) || "flo".equals(Util.DEVICE)) && "OMX.qcom.video.decoder.avc".equals(name)) || (("tcl_eu".equals(Util.DEVICE) || Util.MODEL.startsWith("BRAVIA")) && "OMX.MTK.VIDEO.DECODER.AVC".equals(name)); }

Target:
private static boolean codecNeedsSetOutputSurfaceWorkaround(String name) { return (("deb".equals(Util.DEVICE) || "flo".equals(Util.DEVICE)) && "OMX.qcom.video.decoder.avc".equals(name)) || (("tcl_eu".equals(Util.DEVICE) || "SVP-DTV15".equals(Util.DEVICE) || "BRAVIA_ATV2".equals(Util.DEVICE)) && "OMX.MTK.VIDEO.DECODER.AVC".equals(name)); }
Source:
public int hashCode() { return Objects.hash(id, resource); }

Target:
public int hashCode() { return (int) id + resource.hashCode(); }
Source:
public void assertAuthentication(MockWebServer server) { assertEquals(server.getRequestCount(), 2); try { assertEquals(server.takeRequest().getRequestLine(), "POST /tokens HTTP/1.1"); } catch (InterruptedException e) { Throwables.propagate(e); } }

Target:
public void assertAuthentication(MockWebServer server) { assertTrue(server.getRequestCount() >= 1); try { assertEquals(server.takeRequest().getRequestLine(), "POST /tokens HTTP/1.1"); } catch (InterruptedException e) { Throwables.propagate(e); } }
Source:
public Set<PatternWrapper> getPatterns() { final Set<PatternWrapper> patterns = new HashSet<>(); final BRLRuleModel brlRuleModel = new BRLRuleModel(presenter.getModel()); final List<String> variables = brlRuleModel.getLHSPatternVariables(); variables.stream().forEach(var -> { final String factType = brlRuleModel.getLHSBoundFact(var).getFactType(); final boolean isNegated = brlRuleModel.getLHSBoundFact(var).isNegated(); patterns.add(new PatternWrapper(factType, var, isNegated)); }); return patterns; }

Target:
public Set<PatternWrapper> getPatterns() { final Set<PatternWrapper> patterns = new HashSet<>(); final BRLRuleModel brlRuleModel = new BRLRuleModel(presenter.getModel()); final List<String> variables = brlRuleModel.getLHSPatternVariables(); variables.forEach(var -> { final String factType = brlRuleModel.getLHSBoundFact(var).getFactType(); final boolean isNegated = brlRuleModel.getLHSBoundFact(var).isNegated(); patterns.add(new PatternWrapper(factType, var, isNegated)); }); return patterns; }
Source:
ILogData read(@NonNull Long nextRead, @NonNull NavigableSet<Long> addresses, @NonNull ReadOptions options) { if (cacheReadRequest(options)) { ILogData data = readCache.getIfPresent(nextRead); if (data == null) { List<Long> batch = getBatch(nextRead, addresses); log.trace("read: request address {}, read batch {}", nextRead, batch); Map<Long, ILogData> mapAddresses = this.read(batch, options); data = mapAddresses.getOrDefault(nextRead, LogData.COMPACTED); } return data; } return fetch(nextRead); }

Target:
ILogData read(@NonNull Long nextRead, @NonNull NavigableSet<Long> addresses, @NonNull ReadOptions options) { if (cacheReadRequest(options)) { ILogData data = readCache.getIfPresent(nextRead); if (data == null) { List<Long> batch = getBatch(nextRead, addresses); log.trace("read: request address {}, read batch {}", nextRead, batch); Map<Long, ILogData> mapAddresses = this.read(batch, options); data = mapAddresses.getOrDefault(nextRead, LogData.getCompacted(nextRead)); } return data; } return fetch(nextRead); }
Source:
public void shutdown() { if (enableEvents) { monitoringTask.cancel(true); } }

Target:
public void shutdown() { if (enableEvents && monitoringTask != null) { try { monitoringTask.cancel(true); } finally { monitoringTask = null; } } }
Source:
public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) { return mapper(session).selectUuidsForQualifiers(Qualifiers.VIEW, Qualifiers.SUBVIEW, Qualifiers.APP); }

Target:
public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) { return mapper(session).selectUuidsForQualifiers(Qualifiers.VIEW, Qualifiers.SUBVIEW); }
Source:
public int hashCode() { return new HashCodeBuilder(3, 17).append(right).append(simple) .append(securityTool).toHashCode(); }

Target:
public int hashCode() { return new HashCodeBuilder().append(right).append(simple).toHashCode(); }
Source:
private static List<GenericDescription> createEquinoxCapabilities(ManifestElement[] equinoxCapabilities) throws BundleException { if (equinoxCapabilities == null) return null; ArrayList<GenericDescription> results = new ArrayList<>(equinoxCapabilities.length); for (ManifestElement equinoxCapabilitie : equinoxCapabilities) { String[] genericNames = equinoxCapabilitie.getValueComponents(); for (String genericName : genericNames) { GenericDescriptionImpl desc = new GenericDescriptionImpl(); String name = genericName; int colonIdx = genericName.indexOf(':'); if (colonIdx > 0) { name = genericName.substring(0, colonIdx); desc.setType(genericName.substring(colonIdx + 1)); if (IdentityNamespace.IDENTITY_NAMESPACE.equals(desc.getType())) throw new BundleException("A bundle is not allowed to define a capability in the " + IdentityNamespace.IDENTITY_NAMESPACE + " name space."); } Map<String, Object> mapAttrs = getAttributes(equinoxCapabilitie, new String[] {Constants.VERSION_ATTRIBUTE}); Dictionary<String, Object> attrs = mapAttrs == null ? new Hashtable<String, Object>() : new Hashtable<>(mapAttrs); attrs.put(desc.getType(), name); String versionString = equinoxCapabilitie.getAttribute(Constants.VERSION_ATTRIBUTE); if (versionString != null) attrs.put(Constants.VERSION_ATTRIBUTE, Version.parseVersion(versionString)); desc.setAttributes(attrs); results.add(desc); } } return results; }

Target:
private static List<GenericDescription> createEquinoxCapabilities(ManifestElement[] equinoxCapabilities) throws BundleException { if (equinoxCapabilities == null) return null; ArrayList<GenericDescription> results = new ArrayList<>(equinoxCapabilities.length); for (ManifestElement equinoxCapability : equinoxCapabilities) { String[] genericNames = equinoxCapability.getValueComponents(); for (String genericName : genericNames) { GenericDescriptionImpl desc = new GenericDescriptionImpl(); String name = genericName; int colonIdx = genericName.indexOf(':'); if (colonIdx > 0) { name = genericName.substring(0, colonIdx); desc.setType(genericName.substring(colonIdx + 1)); if (IdentityNamespace.IDENTITY_NAMESPACE.equals(desc.getType())) throw new BundleException("A bundle is not allowed to define a capability in the " + IdentityNamespace.IDENTITY_NAMESPACE + " name space."); } Map<String, Object> mapAttrs = getAttributes(equinoxCapability, new String[] {Constants.VERSION_ATTRIBUTE}); Dictionary<String, Object> attrs = mapAttrs == null ? new Hashtable<String, Object>() : new Hashtable<>(mapAttrs); attrs.put(desc.getType(), name); String versionString = equinoxCapability.getAttribute(Constants.VERSION_ATTRIBUTE); if (versionString != null) attrs.put(Constants.VERSION_ATTRIBUTE, Version.parseVersion(versionString)); desc.setAttributes(attrs); results.add(desc); } } return results; }
Source:
public void execute(JobExecutionContext context) throws JobExecutionException { Logger.debug(this, "Running DistReindexJournalCleanupThread - " + new Date()); try { run(); } catch (Exception e) { Logger.info(this, e.toString()); } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.error(this, e.getMessage(), e); } } }

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { Logger.debug(this, "Running DistReindexJournalCleanupThread - " + new Date()); try { run(); } catch (Exception e) { Logger.info(this, e.toString()); } }
Source:
public void testOverrideWithStore() { final ConfigurationBuilder builder1 = new ConfigurationBuilder(); builder1.loaders().addStore(DummyInMemoryCacheStoreConfigurationBuilder.class).fetchPersistentState(true); cm = new DefaultCacheManager(new GlobalConfigurationBuilder().build(), builder1.build()); ConfigurationBuilder builder2 = new ConfigurationBuilder(); builder2.read(cm.getDefaultCacheConfiguration()); builder2.eviction().maxEntries(1000); cm.defineConfiguration("named", builder2.build()); cm.getCache("named"); }

Target:
public void testOverrideWithStore() { final ConfigurationBuilder builder1 = new ConfigurationBuilder(); builder1.loaders().addStore(DummyInMemoryCacheStoreConfigurationBuilder.class); cm = new DefaultCacheManager(new GlobalConfigurationBuilder().build(), builder1.build()); ConfigurationBuilder builder2 = new ConfigurationBuilder(); builder2.read(cm.getDefaultCacheConfiguration()); builder2.eviction().maxEntries(1000); Configuration configuration = cm.defineConfiguration("named", builder2.build()); assertEquals(1, configuration.loaders().cacheLoaders().size()); }
Source:
@Override public Result load(Request request, int networkPolicy) throws IOException { Response response = downloader.load(request.uri, request.networkPolicy); if (response == null) { return null; } Picasso.LoadedFrom loadedFrom = response.cached ? DISK : NETWORK; Bitmap bitmap = response.getBitmap(); if (bitmap != null) { return new Result(bitmap, loadedFrom); } InputStream is = response.getInputStream(); if (is == null) { return null; } if (loadedFrom == DISK && response.getContentLength() == 0) { Utils.closeQuietly(is); throw new ContentLengthException("Received response with 0 content-length header."); } if (loadedFrom == NETWORK && response.getContentLength() > 0) { stats.dispatchDownloadFinished(response.getContentLength()); } try { int orientation = ExifStreamReader.getOrientation(is); return new Result(is, loadedFrom, orientation); } catch (IOException ignored) { } return new Result(is, loadedFrom); }

Target:
@Override public Result load(Request request, int networkPolicy) throws IOException { Response response = downloader.load(request.uri, request.networkPolicy); if (response == null) { return null; } Picasso.LoadedFrom loadedFrom = response.cached ? DISK : NETWORK; Bitmap bitmap = response.getBitmap(); if (bitmap != null) { return new Result(bitmap, loadedFrom); } InputStream is = response.getInputStream(); if (is == null) { return null; } if (loadedFrom == DISK && response.getContentLength() == 0) { Utils.closeQuietly(is); throw new ContentLengthException("Received response with 0 content-length header."); } if (loadedFrom == NETWORK && response.getContentLength() > 0) { stats.dispatchDownloadFinished(response.getContentLength()); } try { MarkableInputStream markStream = new MarkableInputStream(is); is = markStream; int orientation = ExifStreamReader.getOrientation(is); return new Result(is, loadedFrom, orientation); } catch (IOException ignored) { } return new Result(is, loadedFrom); }
Source:
private void increaseNumberOfHandledNodesWithLockAndPersist(final int additionalNumberOfNodes) { setPersistedInfraVariable((PersistedInfraVariablesHandler<Void>) () -> { int updated = (int) this.persistedInfraVariables.get(NB_HANDLED_NODES_KEY) + additionalNumberOfNodes; this.persistedInfraVariables.put(NB_HANDLED_NODES_KEY, updated); return null; }); }

Target:
private void increaseNumberOfHandledNodesWithLockAndPersist(final int additionalNumberOfNodes) { setPersistedInfraVariable(() -> { int updated = (int) this.persistedInfraVariables.get(NB_HANDLED_NODES_KEY) + additionalNumberOfNodes; this.persistedInfraVariables.put(NB_HANDLED_NODES_KEY, updated); return updated; }); }