auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Iterable<Object> executeQuery(Query query) { <START> EntityManager entityManager = emf.createEntityManager(); <END> SQLSchema schema = schemas.get(query.getSchema().getEntityClass()); Preconditions.checkNotNull(schema); SQLQuery sql = toSQL(query, schema); log.debug("SQL Query: " + sql); javax.persistence.Query jpaQuery = entityManager.createNativeQuery(sql.toString()); Pagination pagination = query.getPagination(); if (pagination != null) { jpaQuery.setFirstResult(pagination.getOffset()); jpaQuery.setMaxResults(pagination.getLimit()); if (pagination.isGenerateTotals()) { SQLQuery paginationSQL = toPageTotalSQL(sql); javax.persistence.Query pageTotalQuery = entityManager.createNativeQuery(paginationSQL.toString()); supplyFilterQueryParameters(query, pageTotalQuery); long total = new TimedFunction<>( () -> CoerceUtil.coerce(pageTotalQuery.getSingleResult(), Long.class), "Running Query: " + paginationSQL ).get(); pagination.setPageTotals(total); } } supplyFilterQueryParameters(query, jpaQuery); List<Object> results = new TimedFunction<>(() -> jpaQuery.getResultList(), "Running Query: " + sql).get(); return new SQLEntityHydrator(results, query, dictionary, entityManager).hydrate(); }</code><technical_language>entityManager shoudl closed query. put this in a try block leak it: java try ( EntityManager entityManager = emf.createEntityManager()) { //do stuff } java</technical_language>

Target:
public Iterable<Object> executeQuery(Query query) { EntityManager entityManager = null; try { entityManager = emf.createEntityManager(); SQLSchema schema = schemas.get(query.getSchema().getEntityClass()); Preconditions.checkNotNull(schema); SQLQuery sql = toSQL(query, schema); log.debug("SQL Query: " + sql); javax.persistence.Query jpaQuery = entityManager.createNativeQuery(sql.toString()); Pagination pagination = query.getPagination(); if (pagination != null) { jpaQuery.setFirstResult(pagination.getOffset()); jpaQuery.setMaxResults(pagination.getLimit()); if (pagination.isGenerateTotals()) { SQLQuery paginationSQL = toPageTotalSQL(sql); javax.persistence.Query pageTotalQuery = entityManager.createNativeQuery(paginationSQL.toString()); supplyFilterQueryParameters(query, pageTotalQuery); long total = new TimedFunction<>( () -> CoerceUtil.coerce(pageTotalQuery.getSingleResult(), Long.class), "Running Query: " + paginationSQL ).get(); pagination.setPageTotals(total); } } supplyFilterQueryParameters(query, jpaQuery); List<Object> results = new TimedFunction<>(() -> jpaQuery.getResultList(), "Running Query: " + sql).get(); return new SQLEntityHydrator(results, query, dictionary, entityManager).hydrate(); } finally { if (entityManager != null) { entityManager.close(); } } }
Source:
<code>private void updateOrienteerUserRoleDoc(ODatabaseDocument db, ODocument perspective) { OSecurity security = db.getMetadata().getSecurity(); ORole role = security.getRole(ORIENTEER_USER_ROLE); if (role == null) { ORole reader = security.getRole("reader"); role = security.createRole(ORIENTEER_USER_ROLE, reader, OSecurityRole.ALLOW_MODES.DENY_ALL_BUT); } role.grant(ResourceGeneric.CLASS, OWidgetsModule.OCLASS_WIDGET, OrientPermission.READ.getPermissionFlag()); role.grant(ResourceGeneric.CLASS, OWidgetsModule.OCLASS_DASHBOARD, OrientPermission.READ.getPermissionFlag()); role.grant(OSecurityHelper.FEATURE_RESOURCE, SearchPage.SEARCH_FEATURE, OrientPermission.READ.getPermissionFlag()); <START> role.grant(ResourceGeneric.CLASS, OrienteerUser.CLASS_NAME, 6); <END> role.grant(ResourceGeneric.DATABASE, "cluster", 6); role.getDocument().field(PerspectivesModule.PROP_PERSPECTIVE, perspective); role.save(); }</code><technical_language>hard get 6 means. Recommend OrientPermission - is method get combined flag int</technical_language>

Target:
private void updateOrienteerUserRoleDoc(ODatabaseDocument db, ODocument perspective) { OSecurity security = db.getMetadata().getSecurity(); ORole role = security.getRole(ORIENTEER_USER_ROLE); if (role == null) { ORole reader = security.getRole("reader"); role = security.createRole(ORIENTEER_USER_ROLE, reader, OSecurityRole.ALLOW_MODES.DENY_ALL_BUT); } role.grant(ResourceGeneric.CLASS, OWidgetsModule.OCLASS_WIDGET, READ.getPermissionFlag()); role.grant(ResourceGeneric.CLASS, OWidgetsModule.OCLASS_DASHBOARD, READ.getPermissionFlag()); role.grant(OSecurityHelper.FEATURE_RESOURCE, SearchPage.SEARCH_FEATURE, READ.getPermissionFlag()); role.grant(ResourceGeneric.CLASS, OrienteerUser.CLASS_NAME, OrientPermission.combinedPermission(READ, UPDATE)); role.grant(ResourceGeneric.DATABASE, "cluster", OrientPermission.combinedPermission(READ, UPDATE)); role.getDocument().field(PerspectivesModule.PROP_PERSPECTIVE, perspective); role.save(); }
Source:
<code><START> public void testApplyStatefulOperatorGetState() throws InterruptedException, IOException, ClassNotFoundException { <END> final ApplyStatefulFunction applyStatefulFunction = new FindMaxIntFunction(); final ApplyStatefulOperator<Integer, Integer> applyStatefulOperator = new ApplyStatefulOperator<>(applyStatefulFunction); final MistDataEvent data10 = new MistDataEvent(10, 0L); final MistDataEvent data20 = new MistDataEvent(20, 1L); final List<MistEvent> result = new LinkedList<>(); applyStatefulOperator.setOutputEmitter(new OutputBufferEmitter(result)); applyStatefulOperator.processLeftData(data10); applyStatefulOperator.processLeftData(data20); final int expectedApplyStatefulOperatorState = 20; final Map<String, Object> operatorState = applyStatefulOperator.getOperatorState(); final int applyStatefulOperatorState = (int)operatorState.get("applyStatefulFunctionState"); Assert.assertEquals(expectedApplyStatefulOperatorState, applyStatefulOperatorState); }</code><technical_language>please remove added exceptions</technical_language>

Target:
public void testApplyStatefulOperatorGetState() throws InterruptedException { final ApplyStatefulFunction applyStatefulFunction = new FindMaxIntFunction(); final ApplyStatefulOperator<Integer, Integer> applyStatefulOperator = new ApplyStatefulOperator<>(applyStatefulFunction); final MistDataEvent data10 = new MistDataEvent(10, 0L); final MistDataEvent data20 = new MistDataEvent(20, 1L); final List<MistEvent> result = new LinkedList<>(); applyStatefulOperator.setOutputEmitter(new OutputBufferEmitter(result)); applyStatefulOperator.processLeftData(data10); applyStatefulOperator.processLeftData(data20); final int expectedApplyStatefulOperatorState = 20; final Map<String, Object> operatorState = applyStatefulOperator.getOperatorState(); final int applyStatefulOperatorState = (int)operatorState.get("applyStatefulFunctionState"); Assert.assertEquals(expectedApplyStatefulOperatorState, applyStatefulOperatorState); }
Source:
<code>public Cookie getCookie(String cookieName) { <START> throw new IllegalStateException("Not supported yet"); <END> }</code><technical_language>This UnsupportedOperationException, IllegalStateException</technical_language>

Target:
public Cookie getCookie(String cookieName) { throw new UnsupportedOperationException("Not supported yet"); }
Source:
<code>private static void buildHashTableStrict( Block keyBlock, int keyOffset, int keyCount, MethodHandle keyBlockEquals, MethodHandle keyBlockHashCode, int[] outputHashTable, int hashTableOffset, int hashTableSize) throws DuplicateMapKeyException { for (int i = 0; i < keyCount; i++) { int hash = getHashPosition(keyBlock, keyOffset + i, keyBlockHashCode, hashTableSize); while (true) { if (outputHashTable[hashTableOffset + hash] == -1) { outputHashTable[hashTableOffset + hash] = i; break; } Boolean isDuplicateKey; try { isDuplicateKey = (Boolean) keyBlockEquals.invokeExact(keyBlock, keyOffset + i, keyBlock, keyOffset + outputHashTable[hashTableOffset + hash]); } catch (RuntimeException e) { throw e; } catch (Throwable throwable) { throw new RuntimeException(throwable); } if (isDuplicateKey == null) { <START> throw new PrestoException(NOT_SUPPORTED, "map key cannot be indeterminate"); <END> } if (isDuplicateKey) { throw new DuplicateMapKeyException(keyBlock, keyOffset + i); } hash++; if (hash == hashTableSize) { hash = 0; } } } }</code><technical_language>ditto "indeterminate" in error messages</technical_language>

Target:
private static void buildHashTableStrict( Block keyBlock, int keyOffset, int keyCount, MethodHandle keyBlockEquals, MethodHandle keyBlockHashCode, int[] outputHashTable, int hashTableOffset, int hashTableSize) throws DuplicateMapKeyException { for (int i = 0; i < keyCount; i++) { int hash = getHashPosition(keyBlock, keyOffset + i, keyBlockHashCode, hashTableSize); while (true) { if (outputHashTable[hashTableOffset + hash] == -1) { outputHashTable[hashTableOffset + hash] = i; break; } Boolean isDuplicateKey; try { isDuplicateKey = (Boolean) keyBlockEquals.invokeExact(keyBlock, keyOffset + i, keyBlock, keyOffset + outputHashTable[hashTableOffset + hash]); } catch (RuntimeException e) { throw e; } catch (Throwable throwable) { throw new RuntimeException(throwable); } if (isDuplicateKey == null) { throw new PrestoException(NOT_SUPPORTED, "map key cannot be null or contain nulls"); } if (isDuplicateKey) { throw new DuplicateMapKeyException(keyBlock, keyOffset + i); } hash++; if (hash == hashTableSize) { hash = 0; } } } }
Source:
<code>public NodeMetadata apply(Container container) { String group = "jclouds"; String name = "container"; NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder(); nodeMetadataBuilder.id(container.getId()) .name(name) .group(group); LocationBuilder locationBuilder = new LocationBuilder(); locationBuilder.description(""); locationBuilder.id(""); locationBuilder.scope(LocationScope.HOST); nodeMetadataBuilder.location(locationBuilder.build()); if (container.getStatus() != null) { nodeMetadataBuilder.status(container.getStatus().contains("Up") ? NodeMetadata.Status.RUNNING : NodeMetadata.Status.SUSPENDED); } else { nodeMetadataBuilder.status(container.getState().isRunning() ? NodeMetadata.Status.RUNNING : NodeMetadata.Status.SUSPENDED); <START> } <END> nodeMetadataBuilder.imageId(container.getImage()); nodeMetadataBuilder.loginPort(getLoginPort(container)); nodeMetadataBuilder.publicAddresses(getPublicIpAddresses()); nodeMetadataBuilder.privateAddresses(getPrivateIpAddresses(container)); nodeMetadataBuilder.operatingSystem(OperatingSystem.builder().description("my description") .family(OsFamily.UNRECOGNIZED) .build()); return nodeMetadataBuilder.build(); }</code><technical_language>Refactor this a reusable (injectable) function transforms a Docker state a jclouds node Status</technical_language>

Target:
public NodeMetadata apply(Container container) { String name = cleanUpName(container.getName()); String group = nodeNamingConvention.extractGroup(name); NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(container.getId()) .name(name) .group(group) .hostname(container.getContainerConfig().getHostname()) .hardware(new HardwareBuilder() .id("") .ram(container.getContainerConfig().getMemory()) .processor(new Processor(container.getContainerConfig().getCpuShares(), container.getContainerConfig().getCpuShares())) .build()); builder.status(toPortableStatus.apply(container.getState())); builder.imageId(container.getImage()); builder.loginPort(getLoginPort(container)); builder.publicAddresses(getPublicIpAddresses()); builder.privateAddresses(getPrivateIpAddresses(container)); builder.location(Iterables.getOnlyElement(locations.get())); Image image = images.get().get(container.getImage()); builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); return builder.build(); }
Source:
<code>public Object invoke(Object proxy, Method method, Object[] args) { setCalled = method.getName().startsWith("set"); boolean argNull = args.length > 1 && args[1] == null; setNull = "setNull".equals(method.getName()) || argNull; <START> return null; <END> }</code><technical_language>I _might_ a problem is argument implementations depend e.g. statement.isWrapperFor() statement.unwrap() unwrap a vendor-specific prepared statement error @DefineNamedBindings behave fine</technical_language>

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws SQLException { if (method.getName().equals("unwrap") && args.length == 1 && method.getParameterTypes()[0].equals(Class.class)) { throw new SQLException("The current implementation of DefineNamedBindings is incompatible with " + "arguments that rely on java.sql.Wrapper.unwrap(Class<?>)"); } if (method.getName().startsWith("set")) { setCalled = true; boolean argNull = args.length > 1 && args[1] == null; setNull = argNull || "setNull".equals(method.getName()); } return defaultValue(method.getReturnType()); }
Source:
<code>private void minimizeWorkload(SubscriptionAssignmentView state, SubscriptionAssignmentView.Transformer transformer) { Set<SubscriptionAssignment> redundant = new HashSet<>(); for (SubscriptionName subscriptionName : state.getSubscriptions()) { int diff = state.getAssignmentsCountForSubscription(subscriptionName) - consumersPerSubscription; if (diff > 0) { <START> Iterator<SubscriptionAssignment> iterator = state.getAssignmentsForSubscription(subscriptionName).iterator(); <END> while (diff > 0 && iterator.hasNext()) { SubscriptionAssignment assignment = iterator.next(); if (assignment.isAutoAssigned()) { redundant.add(assignment); diff--; } } } } redundant.forEach(transformer::removeAssignment); }</code><technical_language>indents in this method, I extract this part another method</technical_language>

Target:
private void minimizeWorkload(SubscriptionAssignmentView state, SubscriptionAssignmentView.Transformer transformer) { state.getSubscriptions() .stream() .flatMap(subscriptionName -> findRedundantAssignments(state, subscriptionName)) .forEach(transformer::removeAssignment); }
Source:
<code>public void removePartition(String partitionIdStr) { PartitionId partitionId = partitionIdMap.get(partitionIdStr); if (partitionId != null) { assignedPartitionIds.remove(partitionIdMap.get(partitionIdStr)); for (VirtualReplicatorClusterListener listener : listeners) { listener.onPartitionRemoved(partitionId); } logger.info("Removed partition to current VCR: ", partitionIdStr); } else { <START> logger.trace("Partition not in clusterMap on remove.", partitionIdStr); <END> metrics.partitionIdNotInClusterMapOnRemove.inc(); } }</code><technical_language>Error warn</technical_language>

Target:
public void removePartition(String partitionIdStr) { PartitionId partitionId = partitionIdMap.get(partitionIdStr); if (partitionId != null) { if (assignedPartitionIds.remove(partitionId)) { for (VirtualReplicatorClusterListener listener : listeners) { listener.onPartitionRemoved(partitionId); } logger.info("Partition is removed from current VCR: {}.", partitionIdStr, vcrInstanceName); } else { logger.info("Partition not exists on current VCR: {}", partitionIdStr, vcrInstanceName); } } else { logger.error("Partition not in clusterMap on remove.", partitionIdStr); metrics.partitionIdNotInClusterMapOnRemove.inc(); } }
Source:
<code>private Element getDownloadElement() throws IOException { Element releaseContainer = getLatestReleaseElement().select("div.release-body ul.release-downloads").first(); <START> Iterator<Element> iter = releaseContainer.select("li a").iterator(); <END> LinkedHashSet<Element> assets = new LinkedHashSet<Element>(); while (iter.hasNext()) { Element button = iter.next(); if (button.hasClass("button") && button.hasClass("primary") && button.hasAttr("href")) assets.add(button); } switch (assets.size()) { case 0: throw new IOException("No releases found for this mod"); case 1: Iterator<Element> i = assets.iterator(); return i.next(); default: Iterator<Element> j = assets.iterator(); HashMap<String, Element> releases = new HashMap<String, Element>(); while (j.hasNext()) { Element dl = j.next(); releases.put(dl.attr("href").substring(dl.attr("href").lastIndexOf('/') + 1), dl); } if (downloadAsset != null && releases.containsKey(downloadAsset)) return releases.get(downloadAsset); downloadAsset = (String) JOptionPane.showInputDialog(null, "Which variant of the mod should be used?", "Multiple Downloads Available", JOptionPane.QUESTION_MESSAGE, null, releases.keySet().toArray(), releases.keySet().toArray()[0]); if (downloadAsset == null) throw new IOException("You must select a download to use the mod!"); return releases.get(downloadAsset); } }</code><technical_language>I smell a C++ coder here. Please a for-each loop eyes bleed. :) for (Element button : releseContainer.select("li a")){ } Magic</technical_language>

Target:
private Element getDownloadElement() throws IOException { LinkedHashSet<Element> assets = new LinkedHashSet<>(getLatestReleaseElement().select("div.release-body ul.release-downloads").first().select("li a.primary")); switch (assets.size()) { case 0: { throw new IOException("No releases found for this mod"); } case 1: { return assets.iterator().next(); } default: { HashMap<String, Element> releases = new HashMap<>(); for (Element dl : assets){ releases.put(dl.attr("href").substring(dl.attr("href").lastIndexOf('/') + 1), dl); } if (downloadAsset != null && releases.containsKey(downloadAsset)) return releases.get(downloadAsset); downloadAsset = (String) JOptionPane.showInputDialog(null, "Which variant of the mod should be used?", "Multiple Downloads Available", JOptionPane.QUESTION_MESSAGE, null, releases.keySet().toArray(), releases.keySet().toArray()[0]); if (downloadAsset == null) throw new IOException("You must select a download to use the mod!"); return releases.get(downloadAsset); } } }
Source:
<code>public void addElement(int x, int y, int z) { elementList.add(new GhostGroupElement(x, y, z, Eln.ghostBlock, GhostBlock.tCube)); <START> } <END></code><technical_language>I this intended update</technical_language>

Target:
public void addElement(int x, int y, int z) { elementList.add(new GhostGroupElement(x, y, z, ModBlock.ghostBlock, GhostBlock.tCube)); }
Source:
<code>public void onClose() { superOnClose(); dataTypesPage.disableShortcuts(); super.onClose(); <START> } <END></code><technical_language>Please rename superOnClose() (line 313) superDoClose() confusing java public void onClose() { superOnClose(); ... super.onClose(); }</technical_language>

Target:
public void onClose() { superDoClose(); dataTypesPage.disableShortcuts(); super.onClose(); }
Source:
<code>private void updateState(AuthState state) { if (this.state != null && this.state == state) { return; } this.state = state; switch (state) { case AUTH_START: <START> if (authType != null && authType.equals("auth_type_email")) { <END> showFragment(new SignEmailFragment(), false, false); } else if (authType != null && authType.equals("auth_type_phone")){ showFragment(new SignPhoneFragment(), false, false); } break; case CODE_VALIDATION_PHONE: case CODE_VALIDATION_EMAIL: if((state==AuthState.CODE_VALIDATION_EMAIL && authType.equals("auth_type_phone")) || (state==AuthState.CODE_VALIDATION_PHONE && authType.equals("auth_type_email"))){ updateState(AuthState.AUTH_START); break; } Fragment signInFragment = new SignInFragment(); Bundle args = new Bundle(); args.putString("authType", state==AuthState.CODE_VALIDATION_EMAIL?SignInFragment.AUTH_TYPE_EMAIL : SignInFragment.AUTH_TYPE_PHONE); signInFragment.setArguments(args); showFragment(signInFragment, false, false); break; case GET_OAUTH_PARAMS: executeAuth(messenger().requestGetOAuthParams(), "get_oauth_params"); break; case COMPLETE_OAUTH: if(authType.equals("auth_type_phone")){ updateState(AuthState.AUTH_START); break; } showFragment(new SignEmailFragment(), false, false); startActivityForResult(new Intent(this, OAuthDialogActivity.class), OAUTH_DIALOG); break; case SIGN_UP: showFragment(new SignUpFragment(), false, false); break; case LOGGED_IN: messenger().trackAuthSuccess(); finish(); startActivity(new Intent(this, MainActivity.class)); break; } }</code><technical_language>"auth_type_email" string? Enum integers magic numbers</technical_language>

Target:
private void updateState(AuthState state) { if (this.state != null && this.state == state) { return; } this.state = state; switch (state) { case AUTH_START: if (authType == AUTH_TYPE_EMAIL) { showFragment(new SignEmailFragment(), false, false); } else if (authType == AUTH_TYPE_PHONE) { showFragment(new SignPhoneFragment(), false, false); } break; case CODE_VALIDATION_PHONE: case CODE_VALIDATION_EMAIL: if ((state == AuthState.CODE_VALIDATION_EMAIL && authType == AUTH_TYPE_PHONE) || (state == AuthState.CODE_VALIDATION_PHONE && authType == AUTH_TYPE_EMAIL)) { updateState(AuthState.AUTH_START); break; } Fragment signInFragment = new SignInFragment(); Bundle args = new Bundle(); args.putString("authType", state == AuthState.CODE_VALIDATION_EMAIL ? SignInFragment.AUTH_TYPE_EMAIL : SignInFragment.AUTH_TYPE_PHONE); signInFragment.setArguments(args); showFragment(signInFragment, false, false); break; case GET_OAUTH_PARAMS: executeAuth(messenger().requestGetOAuthParams(), "get_oauth_params"); break; case COMPLETE_OAUTH: if (authType == AUTH_TYPE_PHONE) { updateState(AuthState.AUTH_START); break; } showFragment(new SignEmailFragment(), false, false); startActivityForResult(new Intent(this, OAuthDialogActivity.class), OAUTH_DIALOG); break; case SIGN_UP: showFragment(new SignUpFragment(), false, false); break; case LOGGED_IN: messenger().trackAuthSuccess(); finish(); startActivity(new Intent(this, MainActivity.class)); break; } }
Source:
<code>public AnalyzedRelation visitQueriedSelectRelation(QueriedSelectRelation<?> relation, CoordinatorTxnCtx context) { AnalyzedRelation subRelation = relation.subRelation(); AnalyzedRelation normalizedSubRelation = process(subRelation, context); QueriedSelectRelation<?> newRelation; if (normalizedSubRelation instanceof FieldResolver) { EvaluatingNormalizer evalNormalizer = new EvaluatingNormalizer( functions, RowGranularity.CLUSTER, null, ((FieldResolver) normalizedSubRelation)); <START> if (subRelation == normalizedSubRelation) { <END> newRelation = relation.map(s -> evalNormalizer.normalize(s, context)); } else { newRelation = relation .replaceSubRelation(normalizedSubRelation) .map(s -> evalNormalizer.normalize(s, context)); } } else if (subRelation == normalizedSubRelation) { newRelation = relation; } else { newRelation = relation.replaceSubRelation(normalizedSubRelation); } WhereClauseValidator.validate(newRelation.where().queryOrFallback()); return newRelation; }</code><technical_language>Yeah, I agree winning time, complicates code path. in favour of dropping</technical_language>

Target:
public AnalyzedRelation visitQueriedSelectRelation(QueriedSelectRelation<?> relation, CoordinatorTxnCtx context) { AnalyzedRelation normalizedSubRelation = process(relation.subRelation(), context); final QueriedSelectRelation<?> newRelation; if (normalizedSubRelation instanceof FieldResolver) { EvaluatingNormalizer evalNormalizer = new EvaluatingNormalizer( functions, RowGranularity.CLUSTER, null, ((FieldResolver) normalizedSubRelation)); newRelation = relation .replaceSubRelation(normalizedSubRelation) .map(s -> evalNormalizer.normalize(s, context)); } else { newRelation = relation.replaceSubRelation(normalizedSubRelation); } WhereClauseValidator.validate(newRelation.where().queryOrFallback()); return newRelation; }
Source:
<code>public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( <START> trainingOperationResponse -> <END> trainingOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(extractedForm -> { extractedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); }); extractedForm.getPages().forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println(); }); }) ) ); END: com.azure.ai.formrecognizer.FormRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl#string-string }</code><technical_language>lets call this trainingPollOperationResponse indicating return a poller instance</technical_language>

Target:
public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); END: com.azure.ai.formrecognizer.FormRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl#string-string }
Source:
<code>private void checkDeltaByteArrayProblem(FileMetaData meta, Configuration conf, BlockMetaData block) { if (conf.getBoolean(ParquetInputFormat.SPLIT_FILES, true)) { Set<Encoding> encodings = new HashSet<Encoding>(); for (ColumnChunkMetaData column : block.getColumns()) { try { encodings.addAll(column.getEncodings()); <START> } catch (KeyAccessDeniedException e) { <END> LOG.warn("checkDeltaByteArrayProblem: Bypass encrypted column because key unavailable", column); } } for (Encoding encoding : encodings) { if (CorruptDeltaByteArrays.requiresSequentialReads(meta.getCreatedBy(), encoding)) { throw new ParquetDecodingException("Cannot read data due to " + "PARQUET-246: to read safely, set " + SPLIT_FILES + " to false"); } } } }</code><technical_language>is clear need suppress this exception</technical_language>

Target:
private void checkDeltaByteArrayProblem(FileMetaData meta, Configuration conf, BlockMetaData block) { if (conf.getBoolean(ParquetInputFormat.SPLIT_FILES, true)) { Set<Encoding> encodings = new HashSet<Encoding>(); for (ColumnChunkMetaData column : block.getColumns()) { encodings.addAll(column.getEncodings()); } for (Encoding encoding : encodings) { if (CorruptDeltaByteArrays.requiresSequentialReads(meta.getCreatedBy(), encoding)) { throw new ParquetDecodingException("Cannot read data due to " + "PARQUET-246: to read safely, set " + SPLIT_FILES + " to false"); } } } }
Source:
<code>public HiveMetaStore(Configuration conf, HdfsSinkConnectorConfig connectorConfig) throws HiveMetaStoreException { HiveConf hiveConf = new HiveConf(conf, HiveConf.class); String hiveConfDir = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_CONF_DIR_CONFIG); String hiveMetaStoreURIs = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_METASTORE_URIS_CONFIG); if (!hiveConfDir.equals("")) { hiveConf.addResource(new Path(hiveConfDir, "/hive-site.xml")); <START> } <END> hiveConf.set("hive.metastore.uris", hiveMetaStoreURIs); try { client = HCatUtil.getHiveMetastoreClient(hiveConf); } catch (IOException | MetaException e) { throw new HiveMetaStoreException(e); } }</code><technical_language>Minor: Validate hive-site.xml exists print a warning if doesn't? this a common mistake</technical_language>

Target:
public HiveMetaStore(Configuration conf, HdfsSinkConnectorConfig connectorConfig) throws HiveMetaStoreException { HiveConf hiveConf = new HiveConf(conf, HiveConf.class); String hiveConfDir = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_CONF_DIR_CONFIG); String hiveMetaStoreURIs = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_METASTORE_URIS_CONFIG); if (!hiveConfDir.equals("")) { String hiveSitePath = hiveConfDir + "/hive-site.xml"; File hiveSite = new File(hiveSitePath); if (!hiveSite.exists()) { log.warn("hive-site.xml does not exist in provided Hive configuration directory {}.", hiveConf); } hiveConf.addResource(new Path(hiveSitePath)); } hiveConf.set("hive.metastore.uris", hiveMetaStoreURIs); try { client = HCatUtil.getHiveMetastoreClient(hiveConf); } catch (IOException | MetaException e) { throw new HiveMetaStoreException(e); } }
Source:
<code>private int determineMaxExtractedTextLength( DatabaseMetaData metaData ) { ResultSet resultSet = null; try { resultSet = metaData.getColumns(null, null, null, EXTRACTED_TEXT_COLUMN_NAME); <START> return resultSet.next() ? resultSet.getInt("COLUMN_SIZE") : DEFAULT_MAX_EXTRACTED_TEXT_LENGTH; <END> } catch (SQLException e) { LOGGER.debug(e, "Cannot determine the maximum size of the column which holds the extracted text. Defaulting to {0}", DEFAULT_MAX_EXTRACTED_TEXT_LENGTH); return DEFAULT_MAX_EXTRACTED_TEXT_LENGTH; } finally { tryToClose(resultSet); } }</code><technical_language>This find of columns name in table in schema in database, right? return more result? this code, this pretty brittle</technical_language>

Target:
private int determineMaxExtractedTextLength( DatabaseMetaData metaData ) { ResultSet resultSet = null; try { String tableName = this.tableName; if (metaData.storesLowerCaseIdentifiers()) { tableName = tableName.toLowerCase(); } else if (metaData.storesUpperCaseIdentifiers()) { tableName = tableName.toUpperCase(); } resultSet = metaData.getColumns(null, null, tableName, EXTRACTED_TEXT_COLUMN_NAME); return resultSet.next() ? resultSet.getInt("COLUMN_SIZE") : DEFAULT_MAX_EXTRACTED_TEXT_LENGTH; } catch (SQLException e) { LOGGER.debug(e, "Cannot determine the maximum size of the column which holds the extracted text. Defaulting to {0}", DEFAULT_MAX_EXTRACTED_TEXT_LENGTH); return DEFAULT_MAX_EXTRACTED_TEXT_LENGTH; } finally { tryToClose(resultSet); } }
Source:
<code>void updateLabel() { String msg; <START> ICluster cluster = AccountService.getDefault().getModel().getClusters().get(0); <END> if (removed || cluster.getAccounts().isEmpty()) { msg = "No configured accounts"; } else { IAccount account = cluster.getAccounts().get(0); msg = account.getId() + " account configured valid until " + Date.from(Instant.ofEpochMilli(account.getAccessTokenExpiryTime())); } label.setText(msg); }</code><technical_language>if clusters? TODO jira</technical_language>

Target:
void updateLabel() { String msg; if (removed || osioCluster.getAccounts().isEmpty()) { msg = "No configured accounts"; } else { IAccount account = osioCluster.getAccounts().get(0); msg = account.getId() + " account configured valid until " + Date.from(Instant.ofEpochMilli(account.getAccessTokenExpiryTime())); } label.setText(msg); }
Source:
<code>public static boolean deepEquals(final @Nullable Object o1, @Nullable final Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } Class<?> class1 = o1.getClass(); Class<?> class2 = o2.getClass(); if (!class1.equals(class2)) { return false; } if (class1.isArray()) { <START> int length = Array.getLength(o1); if (Array.getLength(o2) != length) { return false; } for (int i = 0; i < length; i++) { if (!deepEquals(Array.get(o1, i), Array.get(o2, i))) { return false; } } return true; <END> } else if (o1 instanceof Collection) { Collection<?> c1 = (Collection<?>) o1; Collection<?> c2 = (Collection<?>) o2; int size = c1.size(); if (c2.size() != size) { return false; } if (o1 instanceof Set) { for (Object e1 : c1) { boolean contains = false; for (Object e2 : c2) { if (deepEquals(e1, e2)) { contains = true; break; } } if (!contains) { return false; } } return true; } Iterator<?> i1 = c1.iterator(); Iterator<?> i2 = c2.iterator(); while (i1.hasNext()) { if (!deepEquals(i1.next(), i2.next())) { return false; } } return true; } return o1.equals(o2); }</code><technical_language>extract</technical_language>

Target:
public static boolean deepEquals(final @Nullable Object o1, @Nullable final Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } Class<?> class1 = o1.getClass(); Class<?> class2 = o2.getClass(); if (!class1.equals(class2)) { return false; } if (class1.isArray()) { int length = Array.getLength(o1); if (Array.getLength(o2) != length) { return false; } for (int i = 0; i < length; i++) { if (!deepEquals(Array.get(o1, i), Array.get(o2, i))) { return false; } } return true; } else if (o1 instanceof Collection) { Collection<?> c1 = (Collection<?>) o1; Collection<?> c2 = (Collection<?>) o2; int size = c1.size(); if (c2.size() != size) { return false; } if (o1 instanceof Set && !(o1 instanceof SortedSet<?>)) { for (Object e1 : c1) { boolean contains = false; for (Object e2 : c2) { if (deepEquals(e1, e2)) { contains = true; break; } } if (!contains) { return false; } } return true; } Iterator<?> i1 = c1.iterator(); Iterator<?> i2 = c2.iterator(); while (i1.hasNext()) { if (!deepEquals(i1.next(), i2.next())) { return false; } } return true; } return o1.equals(o2); }
Source:
<code>public Collection<Object> convertDimensionValue(String name, String value) { List<Object> result = new ArrayList<Object>(); try { String typeName = getDomainDatatype(name); if (typeName != null) { Class<?> type = Class.forName(typeName); if (type == java.util.Date.class) { result.addAll(new TimeParser().parse(value)); <START> } else if ((type == java.lang.Double.class || type == java.lang.Float.class) && !value.contains(",")) { <END> result.add(parseNumberOrRange(value)); } else { for (String element : value.split(",")) { result.add(Converters.convert(element, type)); } } } else { result.add(value); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to convert dimension value: ", e); result.add(value); } return result; }</code><technical_language>if integer, short, ... whatever? check Number.class.isAssignableFrom(...) instead</technical_language>

Target:
public Collection<Object> convertDimensionValue(String name, String value) { List<Object> result = new ArrayList<Object>(); try { String typeName = getDomainDatatype(name); if (typeName != null) { Class<?> type = Class.forName(typeName); if (type == java.util.Date.class) { result.addAll(new TimeParser().parse(value)); } else if (Number.class.isAssignableFrom(type) && !value.contains(",")) { result.add(parseNumberOrRange(value)); } else { for (String element : value.split(",")) { result.add(Converters.convert(element, type)); } } } else { result.add(value); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to convert dimension value: ", e); result.add(value); } return result; }
Source:
<code>public void testConsistentIdNotConfigured() throws Exception { Ignite ignite = startGrid(0); assertNull(ignite.configuration().getConsistentId()); <START> assertTrue(ADDR_WITH_PORT_PATTERN.matcher(ignite.cluster().localNode().consistentId().toString()).find()); <END> info("Consistent id in that case: " + ignite.cluster().localNode().consistentId()); }</code><technical_language>I guess String::matches instead of Pattern ceremony. This is important - change it, I mind way</technical_language>

Target:
public void testConsistentIdNotConfigured() throws Exception { Ignite ignite = startGrid(0); assertNull(ignite.configuration().getConsistentId()); assertTrue(ADDR_WITH_PORT_PATTERN.matcher(ignite.cluster().localNode().consistentId().toString()).find()); info("Consistent ID: " + ignite.cluster().localNode().consistentId()); }
Source:
<code>protected Collection<Asset> getNewestAssets() throws IOException { JsonObject assetsElement = getLatestReleaseElement(); Collection<Asset> assets = new LinkedList<>(); JsonArray jsonArray = assetsElement.get("assets").getAsJsonArray(); <START> for(int index = 0; index < jsonArray.size(); index++) { <END> JsonObject jsonObject = jsonArray.get(index).getAsJsonObject(); assets.add(new Asset( jsonObject.get("name").getAsString(), new URL( jsonObject.get("browser_download_url").getAsString()) )); } return assets; }</code><technical_language>for-each for (JsonElement jsonEle : jsonArray) { // stuff }</technical_language>

Target:
protected Collection<Asset> getNewestAssets() throws IOException { JsonObject assetsElement = getLatestReleaseElement(); Collection<Asset> assets = new LinkedList<>(); JsonArray jsonArray = assetsElement.get("assets").getAsJsonArray(); for(JsonElement element: jsonArray) { JsonObject jsonObject = element.getAsJsonObject(); assets.add(new Asset( jsonObject.get("name").getAsString(), new URL( jsonObject.get("browser_download_url").getAsString()) )); } return assets; }
Source:
<code>public PoolDTO createPool(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "pool", required = true) PoolDTO inputPoolDTO) { log.info("Creating custom pool for owner {}: {}" + ownerKey, inputPoolDTO); Pool pool = new Pool(); Owner owner = findOwnerByKey(ownerKey); pool.setOwner(owner); this.populateEntity(pool, inputPoolDTO); <START> pool = resolverUtil.resolvePool(pool); <END> pool = poolManager.createAndEnrichPools(pool); return this.translator.translate(pool, PoolDTO.class); }</code><technical_language>This is unnecessary -- of resolution is done population of entity DTO</technical_language>

Target:
public PoolDTO createPool(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "pool", required = true) PoolDTO inputPoolDTO) { log.info("Creating custom pool for owner {}: {}" + ownerKey, inputPoolDTO); Pool pool = new Pool(); Owner owner = findOwnerByKey(ownerKey); pool.setOwner(owner); this.populateEntity(pool, inputPoolDTO); pool = poolManager.createAndEnrichPools(pool); return this.translator.translate(pool, PoolDTO.class); }
Source:
<code>private JSONArray buildWarnings() { try { String warningsText = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("warnings.json")); <START> JSONArray warnings = JSONArray.fromObject(warningsText); <END> return warnings; } catch (IOException e) { return new JSONArray(); } }</code><technical_language>check of missing resource</technical_language>

Target:
private JSONArray buildWarnings() throws IOException { String warningsText = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("warnings.json")); JSONArray warnings = JSONArray.fromObject(warningsText); return warnings; }
Source:
<code>public static void testChangeInterestRateForActiveRevolvingCreditLoans() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LoansService loanService = MambuAPIFactory.getLoanService(); AccountState accountState = loanService.getLoanAccount(NEW_LOAN_ACCOUNT_ID).getAccountState(); LoanProductType loanProductType = demoProduct.getLoanProductType(); if (loanProductType.equals(LoanProductType.REVOLVING_CREDIT) && accountState.equals(AccountState.ACTIVE)) { JSONTransactionRequest jsonTransactionRequest = new JSONTransactionRequest(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); jsonTransactionRequest.setDate(calendar.getTime()); jsonTransactionRequest.setRate(new BigDecimal(10)); jsonTransactionRequest.setNotes("some notes"); LoanTransaction loanTransaction = loanService.executeJSONTransactionRequest(NEW_LOAN_ACCOUNT_ID, LoanTransactionType.INTEREST_RATE_CHANGED, jsonTransactionRequest); System.out.println("The interest rate was edited for the loan account " + NEW_LOAN_ACCOUNT_ID + ". Transaction ID = " + loanTransaction); } else { System.out.println( <START> "The loan amount does not meet the prerequisites, therefore its interest rate will not be updated."); <END> } }</code><technical_language>I guess account amount</technical_language>

Target:
public static void testChangeInterestRateForActiveRevolvingCreditLoans() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LoansService loanService = MambuAPIFactory.getLoanService(); AccountState accountState = loanService.getLoanAccount(NEW_LOAN_ACCOUNT_ID).getAccountState(); LoanProductType loanProductType = demoProduct.getLoanProductType(); if (loanProductType.equals(LoanProductType.REVOLVING_CREDIT) && accountState.equals(AccountState.ACTIVE)) { JSONTransactionRequest jsonTransactionRequest = new JSONTransactionRequest(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); jsonTransactionRequest.setDate(calendar.getTime()); jsonTransactionRequest.setRate(new BigDecimal(10)); jsonTransactionRequest.setNotes("some notes"); LoanTransaction loanTransaction = loanService.executeJSONTransactionRequest(NEW_LOAN_ACCOUNT_ID, LoanTransactionType.INTEREST_RATE_CHANGED, jsonTransactionRequest); System.out.println("The interest rate was edited for the loan account " + NEW_LOAN_ACCOUNT_ID + ". Transaction ID = " + loanTransaction); } else { System.out.println( "The loan account does not meet the prerequisites, therefore its interest rate will not be updated."); } }
Source:
<code>private BufferAggregator getBuffer() { System.out.println("In getBuffer"); BufferAggregator result; if (this.buffers.isEmpty() && this.numBuffs < this.maxBuffs) { System.out.println("Allocating buffer aggregator"); result = new BufferAggregator(this.buffSize); this.numBuffs++; } else { try { <START> System.out.println("Attempting to take buffer aggregator from queue"); <END> result = this.buffers.take(); } catch (InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException("BufferedUpload thread interrupted. Thread:" + Thread.currentThread().getId())); } } return result; }</code><technical_language>I print size of buffers queue? validate is > 0</technical_language>

Target:
private BufferAggregator getBuffer() { System.out.println("In getBuffer"); BufferAggregator result; if (this.buffers.isEmpty() && this.numBuffs < this.maxBuffs) { System.out.println("Allocating buffer aggregator"); result = new BufferAggregator(this.buffSize); this.numBuffs++; } else { try { System.out.println("Attempting to take buffer aggregator from queue"); System.out.println("Size of buffer: " + this.buffers.remainingCapacity()); System.out.println("Num buffs: " + this.numBuffs); System.out.println("Max buffs: " + this.maxBuffs); result = this.buffers.take(); } catch (InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException("BufferedUpload thread interrupted. Thread:" + Thread.currentThread().getId())); } } return result; }
Source:
<code>public void ensureOldMapsRemoved() { for (Cache<Object, Object> cache : caches(CACHE_NAME)) { DataContainer dc = TestingUtil.extractComponent(cache, DataContainer.class); if (!(dc instanceof DefaultSegmentedDataContainer)) { <START> throw new AssertionError("Test requires DefaultSegmentedDataContainer impl"); <END> } DefaultSegmentedDataContainer segmentedDataContainer = (DefaultSegmentedDataContainer) dc; DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class); Address address = cache.getCacheManager().getAddress(); Set<Integer> segments = dm.getReadConsistentHash().getSegmentsForOwner(address); int mapCount = 0; for (int i = 0; i < segmentedDataContainer.maps.length(); ++i) { if (segmentedDataContainer.maps.get(i) != null) { assertTrue("Segment " + i + " has non null map, but wasn't owned by node: " + address + "!", segments.contains(i)); mapCount++; } } assertEquals(mapCount, segments.size()); } }</code><technical_language>assertTrue</technical_language>

Target:
public void ensureOldMapsRemoved() { for (Cache<Object, Object> cache : caches(CACHE_NAME)) { DataContainer dc = TestingUtil.extractComponent(cache, DataContainer.class); assertTrue(dc instanceof DefaultSegmentedDataContainer); DefaultSegmentedDataContainer segmentedDataContainer = (DefaultSegmentedDataContainer) dc; DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class); Address address = cache.getCacheManager().getAddress(); Set<Integer> segments = dm.getReadConsistentHash().getSegmentsForOwner(address); int mapCount = 0; for (int i = 0; i < segmentedDataContainer.maps.length(); ++i) { if (segmentedDataContainer.maps.get(i) != null) { assertTrue("Segment " + i + " has non null map, but wasn't owned by node: " + address + "!", segments.contains(i)); mapCount++; } } assertEquals(mapCount, segments.size()); } }
Source:
<code>public void run(final double[] values, final int limit, final boolean infectious_nans, final MutableNumericType dp) { if (limit < 1) { throw new IllegalDataException("Limit must be greater than 0"); } double sum = 0; int nans = 0; for (int i = 0; i < limit; i++) { if (Double.isNaN(values[i]) && !infectious_nans) { nans++; continue; } sum += values[i]; } <START> if (nans == limit) { <END> dp.resetValue(Double.NaN); } else { dp.resetValue(sum); } }</code><technical_language>Fix condition</technical_language>

Target:
public void run(final double[] values, final int limit, final boolean infectious_nans, final MutableNumericType dp) { if (limit < 1) { throw new IllegalDataException("Limit must be greater than 0"); } double sum = 0; int nans = 0; for (int i = 0; i < limit; i++) { if (Double.isNaN(values[i]) && !infectious_nans) { nans++; continue; } sum += values[i]; } if (nans == limit || (nans > 0 && infectious_nans)) { dp.resetValue(Double.NaN); } else { dp.resetValue(sum); } }
Source:
<code>public void testPublish() { byte[] testBytes = {}; <START> String testString = "Test"; <END> when(urlService.inputStreamToByteArray(inputStream)).thenReturn(testBytes); when(facebookService.publishToFacebook(any(byte[].class), any(String.class), any(String.class), any(String.class), any(String.class))).thenReturn(testString); Response response = resource.publish(key, "Test", inputStream, contentDisposition, "photo", "Test", "Test"); String result = (String) response.getEntity(); assertEquals(response.getStatusInfo(), Response.Status.OK); assertEquals(result, "Test"); }</code><technical_language>local variable</technical_language>

Target:
public void testPublish() { byte[] testBytes = {}; when(urlService.inputStreamToByteArray(inputStream)).thenReturn(testBytes); when(facebookService.publishToFacebook(any(byte[].class), any(String.class), any(String.class), any(String.class), any(String.class))).thenReturn("Test"); Response response = resource.publish(key, "Test", inputStream, contentDisposition, "photo", "Test", "Test"); String result = (String) response.getEntity(); assertEquals(response.getStatusInfo(), Response.Status.OK); assertEquals(result, "Test"); }
Source:
<code><START> public String toString() { <END> return "Reference: " + referenceId + ", Id: " + id + ", errors: " + errors; }</code><technical_language>Is a good idea output errors in a toString. sensitive data</technical_language>

Target:
public String toString() { final StringBuilder buildy = new StringBuilder("Reference: ").append(referenceId).append(", Id: "); final List<RestError> anyErrors = getErrors(); if (anyErrors.isEmpty()) { buildy.append(", with no errors"); } else { buildy.append(", with "); buildy.append(anyErrors.size()); buildy.append(" error(s)"); } return buildy.toString(); }