auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey) throws ValueOutOfRangeException, IllegalStateException { lock.lock(); try { if (state() == null || !connectionOpen || step != InitStep.CHANNEL_OPEN) throw new IllegalStateException("Channel is not fully initialized/has already been closed"); if (increasePaymentFuture != null) throw new IllegalStateException("Already incrementing paying, wait for previous payment to complete."); <START> if (wallet.isEncrypted() && (userKey == null || userKey.getKey().length == 0) ) <END> throw new IllegalArgumentException("Must supply a key parameter when the wallet is encrypted."); PaymentChannelClientState.IncrementedPayment payment = state().incrementPaymentBy(size, userKey); Protos.UpdatePayment.Builder updatePaymentBuilder = Protos.UpdatePayment.newBuilder() .setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin())) .setClientChangeValue(state.getValueRefunded().value); if (info != null) updatePaymentBuilder.setInfo(info); increasePaymentFuture = SettableFuture.create(); increasePaymentFuture.addListener(new Runnable() { @Override public void run() { lock.lock(); increasePaymentFuture = null; lock.unlock(); } }, MoreExecutors.sameThreadExecutor()); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setUpdatePayment(updatePaymentBuilder) .setType(Protos.TwoWayChannelMessage.MessageType.UPDATE_PAYMENT) .build()); lastPaymentActualAmount = payment.amount; return increasePaymentFuture; } finally { lock.unlock(); } }</code><technical_language>here. Is case userKey.getKey().length zero</technical_language>

Target:
public ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey) throws ValueOutOfRangeException, IllegalStateException, ECKey.KeyIsEncryptedException { lock.lock(); try { if (state() == null || !connectionOpen || step != InitStep.CHANNEL_OPEN) throw new IllegalStateException("Channel is not fully initialized/has already been closed"); if (increasePaymentFuture != null) throw new IllegalStateException("Already incrementing paying, wait for previous payment to complete."); if (wallet.isEncrypted() && userKey == null) throw new ECKey.KeyIsEncryptedException(); PaymentChannelClientState.IncrementedPayment payment = state().incrementPaymentBy(size, userKey); Protos.UpdatePayment.Builder updatePaymentBuilder = Protos.UpdatePayment.newBuilder() .setSignature(ByteString.copyFrom(payment.signature.encodeToBitcoin())) .setClientChangeValue(state.getValueRefunded().value); if (info != null) updatePaymentBuilder.setInfo(info); increasePaymentFuture = SettableFuture.create(); increasePaymentFuture.addListener(new Runnable() { @Override public void run() { lock.lock(); increasePaymentFuture = null; lock.unlock(); } }, MoreExecutors.sameThreadExecutor()); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setUpdatePayment(updatePaymentBuilder) .setType(Protos.TwoWayChannelMessage.MessageType.UPDATE_PAYMENT) .build()); lastPaymentActualAmount = payment.amount; return increasePaymentFuture; } finally { lock.unlock(); } }
Source:
<code>protected void onShowErrata() { logger.info(this.getClass().toString() + " onShowErrata"); if (getWindow() != null) { return; } this.setTitle("Errata for VM xxxx"); <START> setWindow(this); <END> initCommands(this); }</code><technical_language>I pretty this work, re-use model for popup</technical_language>

Target:
protected void onShowErrata() { if (getWindow() != null) { return; } VmErrataCountModel transferObj = new VmErrataCountModel(); transferObj.setTitle(messages.errataForVm(getName())); transferObj.setGuid(getGuid()); transferObj.setName(getName()); setWindow(transferObj); initCommands(transferObj); }
Source:
<code>public String toString() { String data = ""; try { <START> String.valueOf(atts.get("dn").get(0)); <END> } catch (NamingException e) { } return data; }</code><technical_language>data is assigned, this method returns "". instead use: public String toString() { try { return getDN(); } catch (NamingException e) { return ""; } } forget return proper value, duplicating logic appears in getDN method above</technical_language>

Target:
public String toString() { try { return getDN(); } catch (NamingException e) { return ""; } }
Source:
<code>public abstract void setSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException; public abstract Address[] getRecipients(RecipientType type) throws MessagingException; <START> public abstract Address[] getListPost(); <END> public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; public void setRecipient(RecipientType type, Address address) throws MessagingException { setRecipients(type, new Address[] { address }); }</code><technical_language>Please add more utility methods Message. Instead create a method ListHeaders.getListPostAddress(Message) header message</technical_language>

Target:
public abstract void setSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException; public abstract Address[] getRecipients(RecipientType type) throws MessagingException; public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; public void setRecipient(RecipientType type, Address address) throws MessagingException { setRecipients(type, new Address[] { address }); }
Source:
<code>protected void build(Controller controller) { Skin skin = controller.getApplicationAssets().getSkin(); I18N i18n = controller.getApplicationAssets().getI18N(); this.duration = new TextField(DEFAULT_DURATION, skin) { @Override public float getPrefWidth() { return IMAGE_WIDTH; } }; duration.setMaxLength(MAX_DURATION_LENGTH); duration.setRightAligned(true); IconButton dup = new IconButton("close", skin); dup.setTooltip(i18n.m("frames.duplicate")); IconButton delete = new IconButton("close", skin); <START> dup.setTooltip(i18n.m("frames.delete")); <END> top = new Table(); top.setVisible(false); top.add(dup).left(); top.add(delete).expandX().right(); getImage().setScaling(Scaling.fit); topCell = add(top).expandX().fillX().ignore(); row(); add(widget).height(IMAGE_HEIGHT).width(IMAGE_WIDTH); row(); add(duration); }</code><technical_language>delete.setTooltip</technical_language>

Target:
protected void build(Controller controller) { Skin skin = controller.getApplicationAssets().getSkin(); I18N i18n = controller.getApplicationAssets().getI18N(); this.duration = new TextField(DEFAULT_DURATION, skin) { @Override public float getPrefWidth() { return IMAGE_WIDTH; } }; duration.setMaxLength(MAX_DURATION_LENGTH); duration.setRightAligned(true); IconButton dup = new IconButton("close", skin); dup.setTooltip(i18n.m("frames.duplicate")); IconButton delete = new IconButton("close", skin); delete.setTooltip(i18n.m("frames.delete")); top = new Table(); top.setVisible(false); top.add(dup).left(); top.add(delete).expandX().right(); getImage().setScaling(Scaling.fit); topCell = add(top).expandX().fillX().ignore(); row(); add(widget).height(IMAGE_HEIGHT).width(IMAGE_WIDTH); row(); add(duration); }
Source:
<code>private static boolean isLeafDirectory(DirectoryNode node) { Directory dir = node.getLookup().lookup(Directory.class); boolean ret = true; try { for (Content c : dir.getChildren()) { if (c instanceof Directory && (!((Directory) c).getName().equals(".") && !((Directory) c).getName().equals(".."))) { ret = false; break; <START> } else if (0 < Case.getCurrentCase().getSleuthkitCase().getVisibleContentChildrenCount(c)) { <END> ret = false; break; } } } catch (TskException ex) { Logger.getLogger(DirectoryTreeFilterChildren.class.getName()) .log(Level.WARNING, "Error getting directory children", ex); return false; } return ret; }</code><technical_language>c.hasVisibleChildren() here</technical_language>

Target:
private static boolean isLeafDirectory(DirectoryNode node) { Directory dir = node.getLookup().lookup(Directory.class); boolean ret = true; try { for (Content c : dir.getChildren()) { if (c instanceof Directory && (!((Directory) c).getName().equals(".") && !((Directory) c).getName().equals(".."))) { ret = false; break; } else if(AbstractContentNode.contentHasVisibleContentChildren(c)){ ret = false; break; } } } catch (TskException ex) { Logger.getLogger(DirectoryTreeFilterChildren.class.getName()) .log(Level.WARNING, "Error getting directory children", ex); return false; } return ret; }
Source:
<code>public void testCatalogMethodImpl() throws Throwable { try { testResult(checkNotNull(this.method.invoke(this.catalogType), "return value")); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw e.getCause(); } throw e; } <START> } <END></code><technical_language>is this changing work previously</technical_language>

Target:
public void testCatalogMethodImpl() throws Throwable { if (!last.equals(this.catalogKey)) { last = this.catalogKey; testKeyAndName(this.catalogType); if (this.catalogType instanceof Translatable) { testTranslation((Translatable) this.catalogType); } } try { testResult(checkNotNull(this.method.invoke(this.catalogType), "return value")); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw e.getCause(); } throw e; } }
Source:
<code>public void testDropViewKeepsHTable() throws Exception { HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TEST_PROPERTIES).getAdmin(); String hbaseNativeViewName = generateRandomString(); byte[] hbaseNativeBytes = SchemaUtil.getTableNameAsBytes(HBASE_NATIVE_SCHEMA_NAME, hbaseNativeViewName); try { try { <START> admin.disableTable(hbaseNativeBytes); <END> admin.deleteTable(hbaseNativeBytes); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { } @SuppressWarnings("deprecation") HTableDescriptor descriptor = new HTableDescriptor(hbaseNativeBytes); HColumnDescriptor columnDescriptor = new HColumnDescriptor(FAMILY_NAME); columnDescriptor.setKeepDeletedCells(true); descriptor.addFamily(columnDescriptor); admin.createTable(descriptor); } finally { admin.close(); } Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); conn.createStatement().execute("create view " + hbaseNativeViewName+ " (uint_key unsigned_int not null," + " ulong_key unsigned_long not null," + " string_key varchar not null,\n" + " \"1\".uint_col unsigned_int," + " \"1\".ulong_col unsigned_long" + " CONSTRAINT pk PRIMARY KEY (uint_key, ulong_key, string_key))\n" + HColumnDescriptor.DATA_BLOCK_ENCODING + "='" + DataBlockEncoding.NONE + "'"); conn.createStatement().execute("drop view " + hbaseNativeViewName); admin = driver.getConnectionQueryServices(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES)).getAdmin(); try { try { admin.disableTable(hbaseNativeBytes); admin.deleteTable(hbaseNativeBytes); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { fail(); } } finally { admin.close(); } }</code><technical_language>need disable delete table name is random</technical_language>

Target:
public void testDropViewKeepsHTable() throws Exception { HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TEST_PROPERTIES).getAdmin(); String hbaseNativeViewName = generateRandomString(); byte[] hbaseNativeBytes = SchemaUtil.getTableNameAsBytes(HBASE_NATIVE_SCHEMA_NAME, hbaseNativeViewName); try { @SuppressWarnings("deprecation") HTableDescriptor descriptor = new HTableDescriptor(hbaseNativeBytes); HColumnDescriptor columnDescriptor = new HColumnDescriptor(FAMILY_NAME); columnDescriptor.setKeepDeletedCells(true); descriptor.addFamily(columnDescriptor); admin.createTable(descriptor); } finally { admin.close(); } Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); conn.createStatement().execute("create view " + hbaseNativeViewName+ " (uint_key unsigned_int not null," + " ulong_key unsigned_long not null," + " string_key varchar not null,\n" + " \"1\".uint_col unsigned_int," + " \"1\".ulong_col unsigned_long" + " CONSTRAINT pk PRIMARY KEY (uint_key, ulong_key, string_key))\n" + HColumnDescriptor.DATA_BLOCK_ENCODING + "='" + DataBlockEncoding.NONE + "'"); conn.createStatement().execute("drop view " + hbaseNativeViewName); }
Source:
<code>public void testFsActionNONE() throws Exception { Assume.assumeTrue(FS_AZURE_ENABLE_CHECK_ACCESS + " is false", isCheckAccessEnabled); Path testFilePath = setupTestDirectoryAndUserAccess("/test2.txt", FsAction.NONE); <START> assertFalse(isAccessible(testFilePath, FsAction.EXECUTE)); <END> assertFalse(isAccessible(testFilePath, FsAction.READ)); assertFalse(isAccessible(testFilePath, FsAction.WRITE)); assertFalse(isAccessible(testFilePath, FsAction.READ_EXECUTE)); assertFalse(isAccessible(testFilePath, FsAction.WRITE_EXECUTE)); assertFalse(isAccessible(testFilePath, FsAction.READ_WRITE)); assertFalse(isAccessible(testFilePath, FsAction.ALL)); }</code><technical_language>prefer custom assertAccessible assertInaccessible assertions, e.g. void assertInaccessible(Path, flag) { assertFalse("should denied access " + flag + " " + path, isAccessible(path, flag); } This a meaningful error message copy-and-past</technical_language>

Target:
public void testFsActionNONE() throws Exception { assumeHNSAndCheckAccessEnabled(); Path testFilePath = setupTestDirectoryAndUserAccess("/test2.txt", FsAction.NONE); assertInaccessible(testFilePath, FsAction.EXECUTE); assertInaccessible(testFilePath, FsAction.READ); assertInaccessible(testFilePath, FsAction.WRITE); assertInaccessible(testFilePath, FsAction.READ_EXECUTE); assertInaccessible(testFilePath, FsAction.WRITE_EXECUTE); assertInaccessible(testFilePath, FsAction.READ_WRITE); assertInaccessible(testFilePath, FsAction.ALL); }
Source:
<code>private void createConfigGroup(final Composite parent) { final Group g = createGroup(parent, UIText.CloneDestinationPage_groupConfiguration); newLabel(g, UIText.CloneDestinationPage_promptRemoteName + ":"); remoteText = new Text(g, SWT.BORDER); remoteText.setText(Constants.DEFAULT_REMOTE_NAME); remoteText.setLayoutData(createFieldGridData()); remoteText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { checkPage(); } }); setRemoteWebAddr = new Button(g, SWT.CHECK); <START> setRemoteWebAddr.setText("Remote Web Login Address"); END> GridDataFactory.swtDefaults().span(2, 1).applyTo(setRemoteWebAddr); setRemoteWebAddr.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { remoteText.setText(uri); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }</code><technical_language>texts shown user need externalized enable translation other languages I understand meaning of this label, better: "Use host name remote name" If I check checkbox remote name switches host name I able back, unchecking checkbox default flip origin (or if user typed flip this value) alternatively editable combobox define remote name prepopulate default proposals origin <host name></technical_language>

Target:
private void createConfigGroup(final Composite parent) { final Group g = createGroup(parent, UIText.CloneDestinationPage_groupConfiguration); newLabel(g, UIText.CloneDestinationPage_promptRemoteName + ":"); remoteText = new Combo(g, SWT.NONE); remoteText.setLayoutData(createFieldGridData()); }
Source:
<code>private static void prepareResponseBuilderForPartialRequestWithMultipleRanges(HttpServletResponse response) { response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); <START> response.setHeader(HttpHeaders.PRAGMA, "no-cache"); <END> response.setStatus(PARTIAL_CONTENT.value()); }</code><technical_language>is this required</technical_language>

Target:
private static void prepareResponseBuilderForPartialRequestWithMultipleRanges(HttpServletResponse response) { response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(PARTIAL_CONTENT.value()); }
Source:
<code>private HealthDetailsFreeIpaResponse updateResponse(Stack stack, HealthDetailsFreeIpaResponse response) { response.setEnvironmentCrn(stack.getEnvironmentCrn()); response.setCrn(stack.getResourceCrn()); response.setName(stack.getName()); Set<String> notTermiatedStackInstanceIds = stack.getAllInstanceMetaDataList().stream() .filter(not(InstanceMetaData::isTerminated)) .map(InstanceMetaData::getInstanceId) .filter(Objects::nonNull) .collect(Collectors.toSet()); List<InstanceStatus> nonTerminatedStatuses = response.getNodeHealthDetails().stream() .filter(nodeHealthDetails -> notTermiatedStackInstanceIds.contains(nodeHealthDetails.getInstanceId())) .map(NodeHealthDetails::getStatus) .collect(Collectors.toList()); <START> if (!nonTerminatedStatuses.isEmpty() && areAllStatusTheSame(nonTerminatedStatuses) && !hasMissingStatus(nonTerminatedStatuses, notTermiatedStackInstanceIds)) { <END> response.setStatus(toStatus(nonTerminatedStatuses.get(0))); } else { response.setStatus(Status.UNHEALTHY); } updateResponseWithInstanceIds(response, stack); return response; }</code><technical_language>3 checks here, of fails set status unhealthy. obvious logs while set unhealthy add some extra log here? worried dig deep unhealthy, covered other logs</technical_language>

Target:
private HealthDetailsFreeIpaResponse updateResponse(Stack stack, HealthDetailsFreeIpaResponse response) { response.setEnvironmentCrn(stack.getEnvironmentCrn()); response.setCrn(stack.getResourceCrn()); response.setName(stack.getName()); Set<String> notTermiatedStackInstanceIds = stack.getAllInstanceMetaDataList().stream() .filter(not(InstanceMetaData::isTerminated)) .map(InstanceMetaData::getInstanceId) .filter(Objects::nonNull) .collect(Collectors.toSet()); List<InstanceStatus> nonTerminatedStatuses = response.getNodeHealthDetails().stream() .filter(nodeHealthDetails -> notTermiatedStackInstanceIds.contains(nodeHealthDetails.getInstanceId())) .map(NodeHealthDetails::getStatus) .collect(Collectors.toList()); if (nonTerminatedStatuses.isEmpty()) { LOGGER.debug("FreeIPA is unhealthy because all instances are terminated"); response.setStatus(Status.UNHEALTHY); } else if (!areAllStatusTheSame(nonTerminatedStatuses)) { LOGGER.debug("There are different health statuses for FreeIPA so the the overall health is unhealthy"); response.setStatus(Status.UNHEALTHY); } else if (hasMissingStatus(nonTerminatedStatuses, notTermiatedStackInstanceIds)) { LOGGER.debug("There are missing health checks for some instances of FreeIPA so the overall health is unhealthy"); response.setStatus(Status.UNHEALTHY); } else { response.setStatus(toStatus(nonTerminatedStatuses.get(0))); } updateResponseWithInstanceIds(response, stack); return response; }
Source:
<code>public H3IndexFilterOperator(Predicate predicate, IndexSegment indexSegment, int numDocs) { FunctionContext function = predicate.getLhs().getFunction(); String columnName; if (function.getArguments().get(0).getType() == ExpressionContext.Type.IDENTIFIER) { columnName = function.getArguments().get(0).getIdentifier(); byte[] bytes = BytesUtils.toBytes(function.getArguments().get(1).getLiteral()); <START> _geometry = GeometrySerializer.deserialize(bytes); <END> } else if (function.getArguments().get(1).getType() == ExpressionContext.Type.IDENTIFIER) { columnName = function.getArguments().get(1).getIdentifier(); byte[] bytes = BytesUtils.toBytes(function.getArguments().get(0).getLiteral()); _geometry = GeometrySerializer.deserialize(bytes); } else { throw new RuntimeException("Expecting one of the arguments of ST_DISTANCE to be an identifier"); } DataSource dataSource = indexSegment.getDataSource(columnName); _h3IndexReader = dataSource.getH3Index(); switch (predicate.getType()) { case EQ: break; case NOT_EQ: break; case IN: break; case NOT_IN: break; case RANGE: RangePredicate rangePredicate = (RangePredicate) predicate; _distance = Double.parseDouble(rangePredicate.getUpperBound()); break; case REGEXP_LIKE: break; case TEXT_MATCH: break; case IS_NULL: break; case IS_NOT_NULL: break; } _numDocs = numDocs; try { _h3Core = H3Core.newInstance(); } catch (IOException e) { throw new RuntimeException("Unable to instantiate H3", e); } }</code><technical_language>describe condition shape supported? For example, this handle composite expression</technical_language>

Target:
public H3IndexFilterOperator(Predicate predicate, IndexSegment indexSegment, int numDocs) { _predicate = predicate; _segment = indexSegment; FunctionContext function = predicate.getLhs().getFunction(); String columnName; if (function.getArguments().get(0).getType() == ExpressionContext.Type.IDENTIFIER) { columnName = function.getArguments().get(0).getIdentifier(); byte[] bytes = BytesUtils.toBytes(function.getArguments().get(1).getLiteral()); _geometry = GeometrySerializer.deserialize(bytes); } else if (function.getArguments().get(1).getType() == ExpressionContext.Type.IDENTIFIER) { columnName = function.getArguments().get(1).getIdentifier(); byte[] bytes = BytesUtils.toBytes(function.getArguments().get(0).getLiteral()); _geometry = GeometrySerializer.deserialize(bytes); } else { throw new RuntimeException("Expecting one of the arguments of ST_DISTANCE to be an identifier"); } _dataSource = indexSegment.getDataSource(columnName); _h3IndexReader = _dataSource.getH3Index(); _resolution = _h3IndexReader.getH3IndexResolution(); switch (predicate.getType()) { case RANGE: RangePredicate rangePredicate = (RangePredicate) predicate; _distance = Double.parseDouble(rangePredicate.getUpperBound()); break; default: throw new RuntimeException(String.format("H3 index does not support predicate type %s", predicate.getType())); } _numDocs = numDocs; try { _h3Core = H3Core.newInstance(); } catch (IOException e) { throw new RuntimeException("Unable to instantiate H3 instance", e); } }
Source:
<code>protected final Properties[] extractConsumerProducerProperties(Module module) { Properties consumerProperties = new Properties(); Properties producerProperties = new Properties(); String consumerKeyPrefix = "consumer."; String producerKeyPrefix = "producer."; String partitionPrefix = "partition."; if (module.getDeploymentProperties() != null) { for (Map.Entry<String, String> entry : module.getDeploymentProperties().entrySet()) { String key = entry.getKey(); if (key.startsWith(consumerKeyPrefix)) { consumerProperties.put(key.substring(consumerKeyPrefix.length()), entry.getValue()); } else if (key.startsWith(producerKeyPrefix)) { producerProperties.put(key.substring(producerKeyPrefix.length()), entry.getValue()); } <START> else if (key.startsWith(partitionPrefix)) { <END> consumerProperties.put(key, entry.getValue()); producerProperties.put(key, entry.getValue()); } } } return new Properties[] { consumerProperties, producerProperties }; }</code><technical_language>Originally I thinking "producer.partitionKey" "producer.moduleCount" (which needed for send) "consumer.partition" (which is needed for binding of a consumer). simpler consider "partition" group of properties shared, individual property values needed producer consumer</technical_language>

Target:
protected final Properties[] extractConsumerProducerProperties(Module module) { Properties consumerProperties = new Properties(); Properties producerProperties = new Properties(); String consumerKeyPrefix = "consumer."; String producerKeyPrefix = "producer."; if (module.getDeploymentProperties() != null) { for (Map.Entry<String, String> entry : module.getDeploymentProperties().entrySet()) { if (entry.getKey().startsWith(consumerKeyPrefix)) { consumerProperties.put(entry.getKey().substring(consumerKeyPrefix.length()), entry.getValue()); } else if (entry.getKey().startsWith(producerKeyPrefix)) { producerProperties.put(entry.getKey().substring(producerKeyPrefix.length()), entry.getValue()); } } } return new Properties[] { consumerProperties, producerProperties }; }
Source:
<code>public void setStatus(final TaskStatus status) { Preconditions.checkNotNull(status, "status"); log.info("Updating task %s to status: %s", status.getId(), status); int updated = dbi.withHandle( new HandleCallback<Integer>() { @Override public Integer withHandle(Handle handle) throws Exception { return handle.createStatement( String.format( <START> "UPDATE %s SET active = :active, status_payload = :status_payload WHERE id = :id AND active = 1", <END> dbConnectorConfig.getTaskTable() ) ) .bind("id", status.getId()) .bind("active", status.isRunnable() ? 1 : 0) .bind("status_payload", jsonMapper.writeValueAsString(status)) .execute(); } } ); if(updated != 1) { throw new IllegalStateException(String.format("Active task not found: %s", status.getId())); } }</code><technical_language>addition of "active = 1" check, is expect id=:id potentially return multiple rows is uber explicit</technical_language>

Target:
public void setStatus(final TaskStatus status) { Preconditions.checkNotNull(status, "status"); log.info("Updating task %s to status: %s", status.getId(), status); int updated = dbi.withHandle( new HandleCallback<Integer>() { @Override public Integer withHandle(Handle handle) throws Exception { return handle.createStatement( String.format( "UPDATE %s SET active = :active, status_payload = :status_payload WHERE id = :id AND active = 1", dbConnectorConfig.getTaskTable() ) ) .bind("id", status.getId()) .bind("active", status.isRunnable() ? 1 : 0) .bind("status_payload", jsonMapper.writeValueAsBytes(status)) .execute(); } } ); if(updated != 1) { throw new IllegalStateException(String.format("Active task not found: %s", status.getId())); } }
Source:
<code>private JsonNode evalValue(ObjectNode local, String code) throws TemplateException { Config scopedParams = params.deepCopy(); for (Map.Entry<String, JsonNode> pair : ImmutableList.copyOf(local.fields())) { scopedParams.set(pair.getKey(), pair.getValue()); } String resultText = null; <START> if (requireInvokedTemplate(code)) { <END> resultText = invokeTemplate(lazyGetTemplateInvocable(), code, scopedParams); } else { resultText = code; } if (resultText == null) { return jsonMapper.getNodeFactory().nullNode(); } else { return jsonMapper.getNodeFactory().textNode(resultText); } }</code><technical_language>This is minor reconsider this method name. boolean methods in digdag code <LINK_0></technical_language>

Target:
private JsonNode evalValue(ObjectNode local, String code) throws TemplateException { Config scopedParams = params.deepCopy(); for (Map.Entry<String, JsonNode> pair : ImmutableList.copyOf(local.fields())) { scopedParams.set(pair.getKey(), pair.getValue()); } String resultText = null; if (isInvokeTemplateRequired(code)) { resultText = invokeTemplate(lazyGetTemplateInvocable(), code, scopedParams); } else { resultText = code; } if (resultText == null) { return jsonMapper.getNodeFactory().nullNode(); } else { return jsonMapper.getNodeFactory().textNode(resultText); } }
Source:
<code>public int compareTo(Object o) { AbstractMetadataInputSplit other = (AbstractMetadataInputSplit) o; long myLength = getTotalSize(); long otherLength = other.getTotalSize(); <START> if (myLength < otherLength) { <END> return -1; } else if (myLength == otherLength) { return 0; } else { return 1; } }</code><technical_language>slightly easier do Long.compare(x, y)</technical_language>

Target:
public int compareTo(Object o) { return Long.compare(getTotalBytes(), ((AbstractMetadataInputSplit) o).getTotalBytes()); }
Source:
<code>public Set<NameKey> getWatchedProjects() { if (watchedProjects == null) { if (dbProvider == null) { throw new OutOfScopeException("Not in request scoped user"); } final Set<Project.NameKey> h = new HashSet<Project.NameKey>(); try { for (AccountProjectWatch projectWatch : dbProvider.get().accountProjectWatches().byAccount(getAccountId()).toList()) { h.add(projectWatch.getProjectNameKey()); } <START> } catch (ProvisionException e) { <END> log.warn("Cannot query project watches of a user", e); } catch (OrmException e) { log.warn("Cannot query project watches of a user", e); } watchedProjects = Collections.unmodifiableSet(h); } return watchedProjects; }</code><technical_language>Exceptions logged. (re)throwing? In case of exception user empty list why. a gerrit admin log files find out error</technical_language>

Target:
public Set<Project.NameKey> getWatchedProjects() { if (watchedProjects == null) { if (dbProvider == null) { throw new OutOfScopeException("Not in request scoped user"); } final Set<Project.NameKey> h = new HashSet<Project.NameKey>(); try { for (AccountProjectWatch projectWatch : dbProvider.get() .accountProjectWatches().byAccount(getAccountId())) { h.add(projectWatch.getProjectNameKey()); } } catch (OrmException e) { log.warn("Cannot query project watches of a user", e); } watchedProjects = Collections.unmodifiableSet(h); } return watchedProjects; }
Source:
<code>public Encounter deserialize(final JsonElement src, final Type typeOfT, final JsonDeserializationContext context) { final JsonObject jsonEncounter = src.getAsJsonObject(); final JsonElement jsonProvider = jsonEncounter.get("provider"); <START> Person provider; <END> provider = (Person) JsonUtils.readJson(jsonProvider.toString(), Person.class); List<Person> encounterProviders = new ArrayList<>(); encounterProviders.add(provider); Encounter encounter; encounter = (Encounter) JsonUtils.readJson(src.toString(), Encounter.class); encounter.setEncounterProviders(encounterProviders); return encounter; }</code><technical_language>this variable declaration is redundant, do assignment in line</technical_language>

Target:
public Encounter deserialize(final JsonElement src, final Type typeOfT, final JsonDeserializationContext context) { final JsonObject jsonEncounter = src.getAsJsonObject(); final JsonElement jsonProvider = jsonEncounter.get("provider"); Person provider = (Person) JsonUtils.readJson(jsonProvider.toString(), Person.class); Encounter encounter = (Encounter) JsonUtils.readJson(src.toString(), Encounter.class); encounter.setEncounterProviders(Collections.singletonList(provider)); return encounter; }
Source:
<code>public Response deleteFields(@PathParam("typeId") final String typeId, final String[] fieldsID, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, false, req, false, null); final User user = initData.getUser(); Response response = null; try { final List<String> deletedIds = new ArrayList<>(); for (final String fieldId : fieldsID) { try { Field field = fieldAPI.find(fieldId); fieldAPI.delete(field, user); deletedIds.add(fieldId); } catch (NotFoundInDbException e) { continue; } } final List<Field> contentTypeFields = fieldAPI.byContentTypeId(typeId); response = Response.ok(new ResponseEntityView(imap("deletedIds", deletedIds, "fields", new JsonFieldTransformer(contentTypeFields).mapList()))).build(); <START> }catch (Exception e) { <END> response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Catch a list of specific exception subtypes instead. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public Response deleteFields(@PathParam("typeId") final String typeId, final String[] fieldsID, @Context final HttpServletRequest req) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, false, req, false, null); final User user = initData.getUser(); Response response = null; try { final List<String> deletedIds = new ArrayList<>(); for (final String fieldId : fieldsID) { try { final Field field = fieldAPI.find(fieldId); fieldAPI.delete(field, user); deletedIds.add(fieldId); } catch (NotFoundInDbException e) { continue; } } final List<Field> contentTypeFields = fieldAPI.byContentTypeId(typeId); response = Response.ok(new ResponseEntityView(imap("deletedIds", deletedIds, "fields", new JsonFieldTransformer(contentTypeFields).mapList()))).build(); }catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }
Source:
<code>public void tearDown() { <START> CtfTmfTestTrace.KERNEL.dispose(); <END> }</code><technical_language>for sake of symmetry, do fTrace.dispose() here. (so if decide change test trace, need change in place)</technical_language>

Target:
public void tearDown() { fTrace.dispose(); }
Source:
<code><START> public static ByteBuffer serializeRecord( <END> DataOutputSerializer serializer, IOReadableWritable record) throws IOException { serializer.clear(); serializer.skipBytesToWrite(4); record.write(serializer); int len = serializer.length() - 4; serializer.setPosition(0); serializer.writeInt(len); serializer.skipBytesToWrite(len); return serializer.wrapAsByteBuffer(); }</code><technical_language>great if this method public. Ideally remove this completely, tests this bypass some crucial logic of this class result in meaningless tests. This method is in places: - occurrence in SingleInputGateTest replaced emitting a record. - occurrence in TestPartitionProducer removed adjusting TestProducerSource produce ByteBuffer instead of BufferConsumer, a nice change simplify things. - If change for PartitionTestUtils in theory kept, visibility of method reduced package-private</technical_language>

Target:
public static ByteBuffer serializeRecord( DataOutputSerializer serializer, IOReadableWritable record) throws IOException { serializer.setPositionUnsafe(4); record.write(serializer); serializer.writeIntUnsafe(serializer.length() - 4, 0); return serializer.wrapAsByteBuffer(); }
Source:
<code>public Object [][] substructureToReadStructureData() { return new Object[][] { {new ReadStructure("10T10T").templates, "10T10T" }, {new ReadStructure("10T4M10T").templates, "10T10T" }, {new ReadStructure("10T8B10T").nonSkips, "10T8B10T"}, {new ReadStructure("10T8B5M10T").nonSkips, "10T8B5M10T"}, {new ReadStructure("8S10T8B8S10T").nonSkips, "10T8B10T"}, {new ReadStructure("10T8S8S10T").skips, "8S8S" }, {new ReadStructure("10T8S8S3M10T").skips, "8S8S" }, {new ReadStructure("10T8S8M10T").molecularBarcode, "8M" }, <START> {new ReadStructure("8B").sampleBarcodes, "8B" } <END> }; }</code><technical_language>column vertically aligned before, now</technical_language>

Target:
public Object [][] substructureToReadStructureData() { return new Object[][] { {new ReadStructure("10T10T"). templates, "10T10T" }, {new ReadStructure("10T4M10T").templates, "10T10T" }, {new ReadStructure("10T8B10T"). nonSkips, "10T8B10T" }, {new ReadStructure("10T8B5M10T"). nonSkips, "10T8B5M10T"}, {new ReadStructure("8S10T8B8S10T").nonSkips, "10T8B10T" }, {new ReadStructure("10T8S8S10T"). skips, "8S8S" }, {new ReadStructure("10T8S8S3M10T").skips, "8S8S" }, {new ReadStructure("8B").sampleBarcodes, "8B" }, {new ReadStructure("10T8S8M10T").molecularBarcode, "8M" } }; }
Source:
<code><START> protected void markStartTime() { <END> callbackTracker.markOperationStart(); }</code><technical_language>methods private I guess</technical_language>

Target:
void markStartTime() { callbackTracker.markOperationStart(); }
Source:
<code><START> private Expression<?> createExpressionAndPotentionallyAddLeftJoinForReferencedAssociation(Order order, JPQLQuery query) { <END> Assert.notNull(order, "Order must not be null!"); Assert.notNull(query, "JPQLQuery must not be null!"); if (!order.getProperty().contains(".")) { return order.isIgnoreCase() ? builder.getString(order.getProperty()).lower() : builder.get(order.getProperty()); } EntityType<?> entitytype = em.getMetamodel().entity(builder.getType()); Set<Attribute<?, ?>> combinedAttributes = new LinkedHashSet<Attribute<?, ?>>(); combinedAttributes.addAll(entitytype.getSingularAttributes()); combinedAttributes.addAll(entitytype.getPluralAttributes()); for (Attribute<?, ?> attribute : combinedAttributes) { String attributePrefix = attribute.getName() + "."; if (order.getProperty().startsWith(attributePrefix)) { EntityPathBase<?> associationPathRoot = new EntityPathBase<Object>(attribute.getJavaType(), attribute.getName()); query.leftJoin((EntityPath) builder.get(attribute.getName()), associationPathRoot); PathBuilder<Object> attributePathBuilder = new PathBuilder<Object>(attribute.getJavaType(), associationPathRoot.getMetadata()); String nestedAttributePath = order.getProperty().substring(attributePrefix.length()); return order.isIgnoreCase() ? attributePathBuilder.getString(nestedAttributePath).lower() : attributePathBuilder.get(nestedAttributePath); } } throw new IllegalArgumentException( String.format("Could not create property expression for %s", order.getProperty())); }</code><technical_language>Split more fine-grained methods</technical_language>

Target:
private Expression<?> createExpressionAndPotentionallyAddLeftJoinForReferencedAssociation(Order order, JPQLQuery query) { Assert.notNull(order, "Order must not be null!"); Assert.notNull(query, "JPQLQuery must not be null!"); if (!order.getProperty().contains(".")) { return order.isIgnoreCase() ? builder.getString(order.getProperty()).lower() : builder.get(order.getProperty()); } EntityType<?> entitytype = em.getMetamodel().entity(builder.getType()); Set<Attribute<?, ?>> combinedAttributes = new LinkedHashSet<Attribute<?, ?>>(); combinedAttributes.addAll(entitytype.getSingularAttributes()); combinedAttributes.addAll(entitytype.getPluralAttributes()); for (Attribute<?, ?> attribute : combinedAttributes) { if (order.getProperty().startsWith(attribute.getName() + ".")) { switch (attribute.getPersistentAttributeType()) { case EMBEDDED: return builder.get(order.getProperty()); default: return createLeftJoinForAttributeInOrderBy(attribute, order, query); } } } throw new IllegalArgumentException( String.format("Could not create property expression for %s", order.getProperty())); }
Source:
<code>public void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key) { <START> if (channel.getHandler() != null) { <END> channel.getHandler().handleChannelRead(channel, readObject, key); } }</code><technical_language>is this null</technical_language>

Target:
public void onChannelReadEvent(AbstractNioChannel channel, Object readObject, SelectionKey key) { channel.getHandler().handleChannelRead(channel, readObject, key); }
Source:
<code>public final void init(Map<String, Object> conf, SinkContext context) { String path = (String) conf.get(KEY_PATH); String portFile = (String) conf.get(KEY_PORT_FILE); cacheMaxSize = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_MAX_SIZE, DEFAULT_MAX_CACHE_SIZE)); cacheTtlSeconds = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_TTL_SEC, DEFAULT_CACHE_TTL_SECONDS)); topologyName = context.getTopologyName(); initialize(conf, context); int port = TypeUtils.getInteger(conf.getOrDefault(KEY_PORT, 0)); if (port == 0) { if (!Strings.isNullOrEmpty(portFile)) { try { port = TypeUtils.getInteger(Files.lines(Paths.get(portFile)).findFirst() .get().trim()); } catch (IOException | SecurityException | IllegalArgumentException e) { throw new IllegalArgumentException("Could not parse " + KEY_PORT_FILE + " " + portFile + " Make sure the file is readable," + " only contains the port on which the service should run" + " and is UTF8 encoded", e); } } else { throw new IllegalArgumentException("Neither 'port' nor 'port_file' " + "were specified in config for metrics sink " + context.getSinkId()); } } <START> startHttpServer(path, port); <END> }</code><technical_language>is this httpserver for ? send request this server</technical_language>

Target:
public final void init(Map<String, Object> conf, SinkContext context) { String path = (String) conf.get(KEY_PATH); String portFile = (String) conf.get(KEY_PORT_FILE); cacheMaxSize = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_MAX_SIZE, DEFAULT_MAX_CACHE_SIZE)); cacheTtlSeconds = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_TTL_SEC, DEFAULT_CACHE_TTL_SECONDS)); topologyName = context.getTopologyName(); initialize(conf, context); int port = TypeUtils.getInteger(conf.getOrDefault(KEY_PORT, 0)); if (port == 0) { if (!Strings.isNullOrEmpty(portFile)) { try (Stream<String> lines = Files.lines(Paths.get(portFile))) { port = TypeUtils.getInteger(lines.findFirst().get().trim()); } catch (IOException | SecurityException | IllegalArgumentException e) { throw new IllegalArgumentException("Could not parse " + KEY_PORT_FILE + " " + portFile + " Make sure the file is readable," + " only contains the port on which the service should run" + " and is UTF8 encoded", e); } } else { throw new IllegalArgumentException("Neither 'port' nor 'port_file' " + "were specified in config for metrics sink " + context.getSinkId()); } } startHttpServer(path, port); }
Source:
<code><START> private RepeatingTrigger(Long interval, Long delay, Integer repeatCount) { <END> if (interval == null && delay == null) { throw new IllegalArgumentException("Both [interval] and [delay] cannot be null"); } this.interval = interval; this.delay = delay == null ? 0 : delay; this.repeatCount = repeatCount; this.executionCount = 1; triggerTime = getTimeSlice(now.get().getMillis() + this.delay, standardMinutes(1)); }</code><technical_language>schedule a job needs executed cancelled? Basically infinite repeat</technical_language>

Target:
private RepeatingTrigger(Long interval, Long delay, Integer repeatCount) { if (interval == null && delay == null) { this.triggerTime = currentMinute().plusMinutes(1).getMillis(); } this.interval = interval; this.delay = delay == null ? 0 : delay; this.repeatCount = repeatCount; this.executionCount = 1; triggerTime = getTimeSlice(now.get().getMillis() + this.delay, standardMinutes(1)); }
Source:
<code>public APIResult suspend(@PathParam("job-name") String jobName, @Context HttpServletRequest request, @DefaultValue("") @QueryParam("doAs") String doAsUser, @QueryParam("colo") final String coloExpr) { checkIfExtensionServiceIsEnabled(); ExtensionMetaStore metaStore = ExtensionStore.getMetaStore(); ExtensionJobsBean extensionJobsBean = metaStore.getExtensionJobDetails(jobName); if (extensionJobsBean == null) { LOG.error("Extension Job not found:" + jobName); throw FalconWebException.newAPIException("ExtensionJob not found:" + jobName, Response.Status.NOT_FOUND); } try { <START> suspendEntities(extensionJobsBean, coloExpr, request); <END> } catch (FalconException e) { LOG.error("Error while suspending entities of the extension: " + jobName + ": ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } return new APIResult(APIResult.Status.SUCCEEDED, "Extension job " + jobName + " suspended successfully"); }</code><technical_language>entityMap = getJobEntities(extensionJobsBean) is in schedule method</technical_language>

Target:
public APIResult suspend(@PathParam("job-name") String jobName, @Context HttpServletRequest request, @DefaultValue("") @QueryParam("doAs") String doAsUser, @QueryParam("colo") final String coloExpr) { checkIfExtensionServiceIsEnabled(); ExtensionMetaStore metaStore = ExtensionStore.getMetaStore(); ExtensionJobsBean extensionJobsBean = metaStore.getExtensionJobDetails(jobName); if (extensionJobsBean == null) { LOG.error("Extension Job not found:" + jobName); throw FalconWebException.newAPIException("ExtensionJob not found:" + jobName, Response.Status.NOT_FOUND); } try { SortedMap<EntityType, List<String>> entityNameMap = getJobEntities(extensionJobsBean); suspendEntities(entityNameMap, coloExpr, request); } catch (FalconException e) { LOG.error("Error while suspending entities of the extension: " + jobName + ": ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } return new APIResult(APIResult.Status.SUCCEEDED, "Extension job " + jobName + " suspended successfully"); }
Source:
<code>private String getDiskIsBeingMigratedMessage() { if (cachedDiskIsBeingMigratedMessage == null) { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_BEING_MIGRATED.name()); if (getImage() != null) { builder.append(String.format("$DiskName %1$s", getDiskAlias())); } builder.append(String.format("$OperationType %1$s", ImageOperation.Move == getParameters().getOperation() ? "moved" : "copied")); <START> cachedDiskIsBeingMigratedMessage = builder.toString(); <END> } return cachedDiskIsBeingMigratedMessage; }</code><technical_language>caching u</technical_language>

Target:
private String getDiskIsBeingMigratedMessage() { if (cachedDiskIsBeingMigratedMessage == null) { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_BEING_MIGRATED.name()); if (getImage() != null) { builder.append(String.format("$DiskName %1$s", getDiskAlias())); } cachedDiskIsBeingMigratedMessage = builder.toString(); } return cachedDiskIsBeingMigratedMessage; }
Source:
<code>private void getLazyRoutingConfig() { <START> ImportHelper.loadRoutingFiles(app, new ImportHelper.LoadRoutingFilesCallback() { <END> @Override public void onRoutingFilesLoaded() { notifyEvent(InitEvents.ROUTING_CONFIG_INITIALIZED); } }); }</code><technical_language>Do move ImportHelper</technical_language>

Target:
private void getLazyRoutingConfig() { loadRoutingFiles(app, new LoadRoutingFilesCallback() { @Override public void onRoutingFilesLoaded() { notifyEvent(InitEvents.ROUTING_CONFIG_INITIALIZED); } }); }
Source:
<code>public void eventMessageLogger(GlusterAsyncTask task, JobExecutionStatus oldStatus, VDSGroup cluster) { GlusterVolumeEntity volume; <START> if ( getVolumeDao().getVolumeByGlusterTask(task.getTaskId()) != null) { <END> volume = getVolumeDao().getVolumeByGlusterTask(task.getTaskId()); } else { String vol = task.getTaskParameters().getVolumeName(); volume = getVolumeDao().getByName(cluster.getId(), vol); } if (JobExecutionStatus.ABORTED == task.getStatus() || JobExecutionStatus.FINISHED == task.getStatus() || JobExecutionStatus.FAILED == task.getStatus()){ if(oldStatus != task.getStatus()){ logMessage(cluster.getId(), volume , taskTypeStrMap.get(task.getType()), task.getStatus().name().toLowerCase(), taskTypeAuditMsg.get(task.getType())); } } }</code><technical_language>change this GlusterVolumeEntity volume = getVolumeDao().getVolumeByGlusterTask(task.getTaskId(); if (volume == null) ..</technical_language>

Target:
public void eventMessageLogger(GlusterAsyncTask task, JobExecutionStatus oldStatus, VDSGroup cluster) { GlusterVolumeEntity volume = getVolumeDao().getVolumeByGlusterTask(task.getTaskId()); if ( volume == null){ if(task.getTaskParameters() != null) { String vol = task.getTaskParameters().getVolumeName(); volume = getVolumeDao().getByName(cluster.getId(), vol); } else { return; } } if (JobExecutionStatus.ABORTED == task.getStatus() || JobExecutionStatus.FINISHED == task.getStatus() || JobExecutionStatus.FAILED == task.getStatus()){ if(oldStatus != task.getStatus()){ logMessage(cluster.getId(), volume , taskTypeStrMap.get(task.getType()), task.getStatus().name().toLowerCase(), taskTypeAuditMsg.get(task.getType())); } } }
Source:
<code>public void testBasicSyntaxError() { assertEquals(InterpreterResult.Code.ERROR, repl.interpret("val a:Int = 'ds'", context).code()); <START> } <END></code><technical_language>nice verify message user right error message in frontend</technical_language>

Target:
public void testBasicSyntaxError() { InterpreterResult error = repl.interpret("val a:Int = 'ds'", context); assertEquals(InterpreterResult.Code.ERROR, error.code()); assertEquals("Interpreter error", error.message()); }