auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public RemoteXBeeDevice discoverDevice(String id) throws XBeeException { <END> logger.debug("{}ND for device.", toString(), id); performNodeDiscovery(null, id); XBeeNetwork network = xbeeDevice.getNetwork(); RemoteXBeeDevice rDevice = null; if (deviceList != null && deviceList.size() > 0) { rDevice = deviceList.get(0); if (rDevice != null) rDevice = network.addRemoteDevice(rDevice); } return rDevice; }</code><technical_language>if id == null if id.length() == 0? discovering a device Node Identifier allow pass a null value, empty string configured in XBee device NI. java /** * Discovers reports remote XBee device matches * supplied identifier. * * [...] * * @throws IllegalArgumentException If {@code id.length() == 0}. * @throws InterfaceNotOpenException If device is open. * @throws NullPointerException If {@code id == null}. * @throws XBeeException If is error sending discovery command. */ public RemoteXBeeDevice discoverDevice(String id) throws XBeeException { if (id == null) throw new NullPointerException("Device identifier null."); if (id.length() == 0) throw new IllegalArgumentException("Device identifier empty string."); logger.debug("{}ND for device.", toString(), id); [...] }</technical_language>

Target:
public RemoteXBeeDevice discoverDevice(String id) throws XBeeException { if (!xbeeDevice.isOpen()) throw new InterfaceNotOpenException(); logger.debug("{}ND for device.", xbeeDevice.toString(), id); running = true; discovering = true; performNodeDiscovery(null, id); XBeeNetwork network = xbeeDevice.getNetwork(); RemoteXBeeDevice rDevice = null; if (deviceList != null && deviceList.size() > 0) { rDevice = deviceList.get(0); if (rDevice != null) rDevice = network.addRemoteDevice(rDevice); } return rDevice; }
Source:
<code><START> public static <T extends HelixProperty> Map<PropertyKey, T> updateReloadProperties( <END> HelixDataAccessor accessor, List<PropertyKey> reloadKeys, List<PropertyKey> cachedKeys, Map<PropertyKey, T> cachedPropertyMap) { Map<PropertyKey, T> refreshedPropertyMap = Maps.newHashMap(); List<HelixProperty.Stat> stats = accessor.getPropertyStats(cachedKeys); for (int i = 0; i < cachedKeys.size(); i++) { PropertyKey key = cachedKeys.get(i); HelixProperty.Stat stat = stats.get(i); if (stat != null) { T property = cachedPropertyMap.get(key); if (property != null && property.getBucketSize() == 0 && property.getStat().equals(stat)) { refreshedPropertyMap.put(key, property); } else { reloadKeys.add(key); } } else { LOG.warn("stat is null for key: " + key); reloadKeys.add(key); } } List<T> reloadedProperty = accessor.getProperty(reloadKeys, true); Iterator<PropertyKey> csKeyIter = reloadKeys.iterator(); for (T property : reloadedProperty) { PropertyKey key = csKeyIter.next(); if (property != null) { refreshedPropertyMap.put(key, property); } else { LOG.warn("CurrentState null for key: " + key); } } return refreshedPropertyMap; }</code><technical_language>If this is a public static method, is this in this class</technical_language>

Target:
public static <T extends HelixProperty> Map<PropertyKey, T> updateReloadProperties( HelixDataAccessor accessor, List<PropertyKey> reloadKeys, List<PropertyKey> cachedKeys, Map<PropertyKey, T> cachedPropertyMap) { Map<PropertyKey, T> refreshedPropertyMap = Maps.newHashMap(); List<HelixProperty.Stat> stats = accessor.getPropertyStats(cachedKeys); for (int i = 0; i < cachedKeys.size(); i++) { PropertyKey key = cachedKeys.get(i); HelixProperty.Stat stat = stats.get(i); if (stat != null) { T property = cachedPropertyMap.get(key); if (property != null && property.getBucketSize() == 0 && property.getStat().equals(stat)) { refreshedPropertyMap.put(key, property); } else { reloadKeys.add(key); } } else { LOG.warn("Stat is null for key: " + key); reloadKeys.add(key); } } List<T> reloadedProperty = accessor.getProperty(reloadKeys, true); Iterator<PropertyKey> reloadKeyIter = reloadKeys.iterator(); for (T property : reloadedProperty) { PropertyKey key = reloadKeyIter.next(); if (property != null) { refreshedPropertyMap.put(key, property); } else { LOG.warn("Reload property is null for key: " + key); } } return refreshedPropertyMap; }
Source:
<code>public String toString() { <START> final List<String> batchNumbers = this.cdmaBatches.values().stream().map(x -> x.getBatchNumber().toString()) <END> .collect(Collectors.toList()); return "CdmaMastSegment [mastSegmentName=" + this.mastSegmentName + ", cdmaBatches=" + String.join(",", batchNumbers) + "]"; }</code><technical_language>Consider keySet in stead of values</technical_language>

Target:
public String toString() { return "CdmaMastSegment [mastSegmentName=" + this.mastSegmentName + ", cdmaBatches=" + this.cdmaBatches.keySet() + "]"; }
Source:
<code>private void executeSyncOperation(final PlanOperation syncOp) { final String serverId = syncOp.getEvalId().get(); LOG.log(Level.FINE, "SYNC: server {0}", serverId); <START> routingTableManager.waitUntilWorkersReadyForServerDelete(serverId); <END> onOperationComplete(syncOp); }</code><technical_language>Making this call non-blocking enhance plan operation execution performance introducing more parallelism</technical_language>

Target:
private void executeSyncOperation(final PlanOperation syncOp) { final String serverId = syncOp.getEvalId().get(); LOG.log(Level.FINE, "SYNC: server {0}", serverId); routingTableManager.checkWorkersTobeReadyForServerDelete(serverId, new SyncHandler(syncOp)); }
Source:
<code>public Optional<RelDataType> getReturnRelDataType() { if (returnType == null) { return Optional.empty(); } else { JavaTypeFactoryImpl typeFactory = new JavaTypeFactoryImpl(new HiveTypeSystemImpl()); <START> Type type = returnType; <END> if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType() == List.class) { final RelDataType componentRelType = typeFactory.createType(parameterizedType.getActualTypeArguments()[0]); return Optional .of(typeFactory.createArrayType(typeFactory.createTypeWithNullability(componentRelType, true), -1)); } } return Optional.of(typeFactory.createType(returnType)); } }</code><technical_language>Is this variable needed? returnType</technical_language>

Target:
public Optional<RelDataType> getReturnRelDataType() { if (returnType == null) { return Optional.empty(); } else { JavaTypeFactoryImpl typeFactory = new JavaTypeFactoryImpl(new HiveTypeSystemImpl()); if (returnType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) returnType; if (parameterizedType.getRawType() == List.class) { final RelDataType componentRelType = typeFactory.createType(parameterizedType.getActualTypeArguments()[0]); return Optional .of(typeFactory.createArrayType(typeFactory.createTypeWithNullability(componentRelType, true), -1)); } return Optional.empty(); } return Optional.of(typeFactory.createType(returnType)); } }
Source:
<code>private RexNode simplifyNotEqual(RexNode e) { final Comparison comparison = Comparison.of(e); if (comparison == null || comparison.literal.getValue() == null) { return e; } for (RexNode node: predicates.pulledUpPredicates) { final Comparison predicate = Comparison.of(node); if (predicate == null || predicate.kind != SqlKind.EQUALS || predicate.literal.getValue() == null || !predicate.ref.equals(comparison.ref)) { continue; } final RelDataType type = comparison.ref.getType(); <START> final boolean nullable = type.isNullable(); <END> if (predicate.literal.equals(comparison.literal)) { return nullable ? rexBuilder.makeCall(SqlStdOperatorTable.AND, rexBuilder.makeNullLiteral(type), rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, comparison.ref)) : rexBuilder.makeLiteral(false); } else { return nullable ? rexBuilder.makeCall(SqlStdOperatorTable.OR, rexBuilder.makeNullLiteral(type), rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, comparison.ref)) : rexBuilder.makeLiteral(true); } } return e; }</code><technical_language>please remove this "nullable" boolean - other parts of RexSimplify do tricks; please note UnknownAs.FALSE case is handled; I in case of a invokation of RexSimplify; done - ideally; RexSimplify able do more simplification a result of a previously simplification. construct ; call simplifyUnknownAs(andNode, unknownAs)</technical_language>

Target:
private RexNode simplifyNotEqual(RexNode e) { final Comparison comparison = Comparison.of(e); if (comparison == null) { return e; } for (RexNode node: predicates.pulledUpPredicates) { final Comparison predicate = Comparison.of(node); if (predicate == null || predicate.kind != SqlKind.EQUALS || !predicate.ref.equals(comparison.ref)) { continue; } RexNode simplified; if (predicate.literal.equals(comparison.literal)) { simplified = rexBuilder.makeCall(SqlStdOperatorTable.AND, rexBuilder.makeNullLiteral(e.getType()), rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, comparison.ref)); } else { simplified = rexBuilder.makeCall(SqlStdOperatorTable.OR, rexBuilder.makeNullLiteral(e.getType()), rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, comparison.ref)); } return simplify(simplified); } return e; }
Source:
<code>public void insertAfter(E request, E after) { <START> this.requests.add(this.requests.indexOf(after) + 1, request); <END> }</code><technical_language>this.</technical_language>

Target:
public AbstractBulkLightblueRequest<E> insertAfter(E request, E after) { this.requests.add(requests.indexOf(after) + 1, request); return this; }
Source:
<code>private ObserveResponse createObserveResponse(Observation observation, LwM2mModel model, Response coapResponse) { if (coapResponse.getCode() != CoAP.ResponseCode.CHANGED && coapResponse.getCode() != CoAP.ResponseCode.CONTENT) { throw new InvalidResponseException(String.format("Unexpected response code [%s]", coapResponse.getCode())); } ContentFormat contentFormat = null; if (coapResponse.getOptions().hasContentFormat()) { contentFormat = ContentFormat.fromCode(coapResponse.getOptions().getContentFormat()); } else { throw new InvalidResponseException("Content Format is mandatory"); } try { List<TimestampedLwM2mNode> timestampedNodes = decoder.decodeTimestampedData(coapResponse.getPayload(), contentFormat, observation.getPath(), model); if (timestampedNodes.size() == 1 && !timestampedNodes.get(0).isTimestamped()) { return new ObserveResponse(ResponseCode.CONTENT, timestampedNodes.get(0).getNode(), null, observation, null, coapResponse); } else { return new ObserveResponse(ResponseCode.CONTENT, null, timestampedNodes, observation, null, coapResponse); } } catch (CodecException e) { byte[] payload = coapResponse.getPayload() == null ? new byte[0] : coapResponse.getPayload(); throw new InvalidResponseException( String.format("Unable to decode notification payload [%s] of observation [%s] ", <START> Hex.encodeHexString(payload), <END> observation), e); } }</code><technical_language>debug long for payload</technical_language>

Target:
private ObserveResponse createObserveResponse(Observation observation, LwM2mModel model, Response coapResponse) { if (coapResponse.getCode() != CoAP.ResponseCode.CHANGED && coapResponse.getCode() != CoAP.ResponseCode.CONTENT) { throw new InvalidResponseException(String.format("Unexpected response code [%s]", coapResponse.getCode())); } ContentFormat contentFormat = null; if (coapResponse.getOptions().hasContentFormat()) { contentFormat = ContentFormat.fromCode(coapResponse.getOptions().getContentFormat()); } try { List<TimestampedLwM2mNode> timestampedNodes = decoder.decodeTimestampedData(coapResponse.getPayload(), contentFormat, observation.getPath(), model); if (timestampedNodes.size() == 1 && !timestampedNodes.get(0).isTimestamped()) { return new ObserveResponse(ResponseCode.CONTENT, timestampedNodes.get(0).getNode(), null, observation, null, coapResponse); } else { return new ObserveResponse(ResponseCode.CONTENT, null, timestampedNodes, observation, null, coapResponse); } } catch (CodecException e) { if (LOG.isDebugEnabled()) { byte[] payload = coapResponse.getPayload() == null ? new byte[0] : coapResponse.getPayload(); LOG.debug(String.format("Unable to decode notification payload [%s] of observation [%s] ", Hex.encodeHexString(payload), observation), e); } throw new InvalidResponseException( String.format("Unable to decode notification payload of observation [%s] ", observation), e); } }
Source:
<code>public void objectNames() { List<network> list = new ArrayList<network>(); network n1 = new network(); n1.setname("network1"); network n2 = new network(); n2.setname("network2"); list.add(n1); list.add(n2); Set<String> names = Entities.objectNames(list); Assert.assertTrue(names.size() == 2); Assert.assertTrue(names.contains("network1")); Assert.assertTrue(names.contains("network2")); <START> Assert.assertTrue(!names.contains("network3")); <END> Assert.assertTrue(Entities.objectNames(null).equals(Collections.emptySet())); Assert.assertTrue(Entities.objectNames(new ArrayList<network>()).equals(Collections.emptySet())); }</code><technical_language>please replace assertFalse negate condition</technical_language>

Target:
public void objectNames() { List<network> list = new ArrayList<network>(); network n1 = new network(); n1.setname("network1"); network n2 = new network(); n2.setname("network2"); list.add(n1); list.add(n2); Set<String> names = Entities.objectNames(list); Assert.assertTrue(names.size() == 2); Assert.assertTrue(names.contains("network1")); Assert.assertTrue(names.contains("network2")); Assert.assertFalse(names.contains("network3")); Assert.assertTrue(Entities.objectNames(null).equals(Collections.emptySet())); Assert.assertTrue(Entities.objectNames(new ArrayList<network>()).equals(Collections.emptySet())); }
Source:
<code>protected void append(final ILoggingEvent event) { if (bugsnag != null) { Throwable throwable = extractThrowable(event); final Callback reportCallback; <START> if (event.getMarker() != null && event.getMarker() instanceof BugsnagMarker) { <END> reportCallback = ((BugsnagMarker) event.getMarker()).getCallback(); } else { reportCallback = null; } if (throwable != null && !detectLogFromBugsnag(throwable) && !isExcludedLogger(event.getLoggerName())) { bugsnag.notify( throwable, calculateSeverity(event), new Callback() { @Override public void beforeNotify(Report report) { report.addToTab("Log event data", "Message", event.getMessage()); report.addToTab("Log event data", "Timestamp", event.getTimeStamp()); if (reportCallback != null) { reportCallback.beforeNotify(report); } } }); } } }</code><technical_language>instanceof automatically performs a null check. Extracting event.getMarker() a local variable allow simplify this expression</technical_language>

Target:
protected void append(final ILoggingEvent event) { if (bugsnag != null) { Throwable throwable = extractThrowable(event); final Callback reportCallback; Marker marker = event.getMarker(); if (marker instanceof BugsnagMarker) { reportCallback = ((BugsnagMarker) marker).getCallback(); } else { reportCallback = null; } if (throwable != null && !detectLogFromBugsnag(throwable) && !isExcludedLogger(event.getLoggerName())) { bugsnag.notify( throwable, calculateSeverity(event), new Callback() { @Override public void beforeNotify(Report report) { report.addToTab("Log event data", "Message", event.getMessage()); report.addToTab("Log event data", "Timestamp", event.getTimeStamp()); populateContextData(report, event); if (reportCallback != null) { reportCallback.beforeNotify(report); } } }); } } }
Source:
<code>private boolean isAnotherBuildWithSameParametersRunningOnNode(Node node, Queue.Item item) { ThrottleJobProperty tjp = getThrottleJobProperty(item.task); Computer computer = node.toComputer(); List<String> paramsToCompare = tjp.getParamsToCompare(); List<ParameterValue> itemParams = getParametersFromQueueItem(item); if (paramsToCompare.size() > 0) { itemParams = doFilterParams(paramsToCompare, itemParams); } if (computer != null) { for (Executor exec : computer.getExecutors()) { if (item != null && item.task != null) { if (exec.getCurrentExecutable() != null && exec.getCurrentExecutable().getParent() != null && exec.getCurrentExecutable().getParent().getOwnerTask() != null && <START> exec.getCurrentExecutable().getParent().getOwnerTask().getName().equals(item.task.getDisplayName())) { <END> List<ParameterValue> executingUnitParams = getParametersFromWorkUnit(exec.getCurrentWorkUnit()); executingUnitParams = doFilterParams(paramsToCompare, executingUnitParams); if (executingUnitParams.containsAll(itemParams)) { LOGGER.log(Level.FINE, "build (" + exec.getCurrentWorkUnit() + ") with identical parameters (" + executingUnitParams + ") is already running."); return true; } } } } } return false; }</code><technical_language>do compare name displayName. - name is unique. Please name for a project in a folder if know. - comparing task work</technical_language>

Target:
private boolean isAnotherBuildWithSameParametersRunningOnNode(Node node, Queue.Item item) { ThrottleJobProperty tjp = getThrottleJobProperty(item.task); Computer computer = node.toComputer(); List<String> paramsToCompare = tjp.getParamsToCompare(); List<ParameterValue> itemParams = getParametersFromQueueItem(item); if (paramsToCompare.size() > 0) { itemParams = doFilterParams(paramsToCompare, itemParams); } if (computer != null) { for (Executor exec : computer.getExecutors()) { if (item != null && item.task != null) { if (exec.getCurrentExecutable() != null && exec.getCurrentExecutable().getParent() != null && exec.getCurrentExecutable().getParent().getOwnerTask() != null && exec.getCurrentExecutable().getParent().getOwnerTask().getName().equals(item.task.getName())) { List<ParameterValue> executingUnitParams = getParametersFromWorkUnit(exec.getCurrentWorkUnit()); executingUnitParams = doFilterParams(paramsToCompare, executingUnitParams); if (executingUnitParams.containsAll(itemParams)) { LOGGER.log(Level.FINE, "build (" + exec.getCurrentWorkUnit() + ") with identical parameters (" + executingUnitParams + ") is already running."); return true; } } } } } return false; }
Source:
<code>private void compare() { gitService.diff(workspaceId, project, Collections.singletonList(selectedFile), NAME_STATUS, false, 0, selectedRevision.getId(), false, new AsyncRequestCallback<String>(new StringUnmarshaller()) { @Override protected void onSuccess(String result) { if (result.isEmpty()) { dialogFactory.createMessageDialog(locale.compareMessageIdenticalContentTitle(), locale.compareMessageIdenticalContentText(), new ConfirmCallback() { @Override public void accepted() { } }).show(); } else { comparePresenter.show(result.substring(2), result.substring(0, 1), selectedRevision.getId()); } } @Override protected void onFailure(Throwable exception) { <START> notificationManager.notify(exception.getMessage(), FAIL, false); <END> } }); }</code><technical_language>org.eclipse.che.ide.ext.git.client.GitLocalizationConstant#diffFailed instead of exception.getMessage()</technical_language>

Target:
private void compare() { gitService.diff(workspaceId, project, Collections.singletonList(selectedFile), NAME_STATUS, false, 0, selectedRevision.getId(), false, new AsyncRequestCallback<String>(new StringUnmarshaller()) { @Override protected void onSuccess(String result) { if (result.isEmpty()) { dialogFactory.createMessageDialog(locale.compareMessageIdenticalContentTitle(), locale.compareMessageIdenticalContentText(), new ConfirmCallback() { @Override public void accepted() { } }).show(); } else { comparePresenter.show(result.substring(2), result.substring(0, 1), selectedRevision.getId()); } } @Override protected void onFailure(Throwable exception) { notificationManager.notify(locale.diffFailed(), FAIL, false); } }); }
Source:
<code>protected Type visitDereferenceExpression(DereferenceExpression node, StackableAstVisitorContext<Context> context) { QualifiedName qualifiedName = DereferenceExpression.getQualifiedName(node); if (qualifiedName != null) { Scope scope = context.getContext().getScope(); Optional<ResolvedField> resolvedField = scope.tryResolveField(node, qualifiedName); if (resolvedField.isPresent()) { <START> if (!context.getContext().isInLambda() || !context.getContext().getFieldToLambdaArgumentDeclaration().containsKey(FieldId.from(resolvedField.get()))) { <END> return handleResolvedField(node, resolvedField.get(), context); } } if (!scope.isColumnReference(qualifiedName)) { throw missingAttributeException(node, qualifiedName); } } Type baseType = process(node.getBase(), context); if (!(baseType instanceof RowType)) { throw new SemanticException(TYPE_MISMATCH, node.getBase(), "Expression %s is not of type ROW", node.getBase()); } RowType rowType = (RowType) baseType; Type rowFieldType = null; for (RowField rowField : rowType.getFields()) { if (node.getField().getValue().equalsIgnoreCase(rowField.getName().orElse(null))) { rowFieldType = rowField.getType(); break; } } if (rowFieldType == null) { throw missingAttributeException(node); } return setExpressionType(node, rowFieldType); }</code><technical_language>I this special case is required lambda resolve entire deference expression</technical_language>

Target:
protected Type visitDereferenceExpression(DereferenceExpression node, StackableAstVisitorContext<Context> context) { QualifiedName qualifiedName = DereferenceExpression.getQualifiedName(node); if (qualifiedName != null) { Scope scope = context.getContext().getScope(); Optional<ResolvedField> resolvedField = scope.tryResolveField(node, qualifiedName); if (resolvedField.isPresent()) { return handleResolvedField(node, resolvedField.get(), context); } if (!scope.isColumnReference(qualifiedName)) { throw missingAttributeException(node, qualifiedName); } } Type baseType = process(node.getBase(), context); if (!(baseType instanceof RowType)) { throw new SemanticException(TYPE_MISMATCH, node.getBase(), "Expression %s is not of type ROW", node.getBase()); } RowType rowType = (RowType) baseType; Type rowFieldType = null; for (RowField rowField : rowType.getFields()) { if (node.getField().getValue().equalsIgnoreCase(rowField.getName().orElse(null))) { rowFieldType = rowField.getType(); break; } } if (rowFieldType == null) { throw missingAttributeException(node); } return setExpressionType(node, rowFieldType); }
Source:
<code>public static ClientContext create(final ClientConfiguration clientConfiguration) { Assert.requireNonNull(clientConfiguration, "clientConfiguration"); <START> Logger openDolphinLogger = LoggerFactory.getLogger("org.opendolphin"); <END> return new ClientContextImpl(clientConfiguration, new Function<ClientModelStore, AbstractClientConnector>() { @Override public AbstractClientConnector call(final ClientModelStore clientModelStore) { return new DolphinPlatformHttpClientConnector(clientConfiguration, clientModelStore, new OptimizedJsonCodec(), clientConfiguration.getRemotingExceptionHandler()); } }); }</code><technical_language>why</technical_language>

Target:
public static ClientContext create(final ClientConfiguration clientConfiguration) { Assert.requireNonNull(clientConfiguration, "clientConfiguration"); return new ClientContextImpl(clientConfiguration, new Function<ClientModelStore, AbstractClientConnector>() { @Override public AbstractClientConnector call(final ClientModelStore clientModelStore) { return new DolphinPlatformHttpClientConnector(clientConfiguration, clientModelStore, new OptimizedJsonCodec(), clientConfiguration.getRemotingExceptionHandler()); } }); }
Source:
<code>public static void main(String[] args) throws IOException { Schema schema = new Parser().parse(new File("./../user.avsc")); GenericRecord user1 = new GenericData.Record(schema); user1.put("name", "Alyssa"); user1.put("favorite_number", 256); GenericRecord user2 = new GenericData.Record(schema); user2.put("name", "Ben"); user2.put("favorite_number", 7); user2.put("favorite_color", "red"); File file = new File("users.avro"); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter); dataFileWriter.create(schema, file); dataFileWriter.append(user1); dataFileWriter.append(user2); dataFileWriter.close(); DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema); DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader); GenericRecord user = null; while (dataFileReader.hasNext()) { user = dataFileReader.next(user); System.out.println(user); } <START> dataFileReader.close(); <END> }</code><technical_language>a try-with-resource pattern here</technical_language>

Target:
public static void main(String[] args) throws IOException { Schema schema = new Parser().parse(new File("./../user.avsc")); GenericRecord user1 = new GenericData.Record(schema); user1.put("name", "Alyssa"); user1.put("favorite_number", 256); GenericRecord user2 = new GenericData.Record(schema); user2.put("name", "Ben"); user2.put("favorite_number", 7); user2.put("favorite_color", "red"); File file = new File("users.avro"); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter); dataFileWriter.create(schema, file); dataFileWriter.append(user1); dataFileWriter.append(user2); dataFileWriter.close(); DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema); GenericRecord user = null; try(DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader)){ while (dataFileReader.hasNext()) { user = dataFileReader.next(user); System.out.println(user); } } }
Source:
<code>protected void ExecuteVmCommand() { VmDeviceUtils.updateVmDevices(getVm().getStaticData()); setActionReturnValue(VMStatus.Down); if (InitVm()) { if (getVm().getstatus() == VMStatus.Paused) { ResumeVm(); <START> } else { END> if (getParameters().getRunAsStateless()) { for (Disk disk : getVm().getDiskMap().values()) { if (!disk.isAllowSnapshot()) { AuditLogDirector.log(this, AuditLogType.USER_RUN_VM_AS_STATELESS_WITH_DISKS_NOT_ALLOWING_SNAPSHOT); break; } } } if (!_isRerun && Boolean.TRUE.equals(getParameters().getRunAsStateless()) && !getVm().getDiskList().isEmpty() && getVm().getstatus() != VMStatus.Suspended) { StatelessVmTreatment(); } else if (!getParameters().getIsInternal() && !_isRerun && getVm().getstatus() != VMStatus.Suspended && statelessSnapshotExistsForVm()) { removeVmStatlessImages(); } else { RunVm(); } } } else { setActionReturnValue(getVm().getstatus()); } }</code><technical_language>method a method name StatelessVmTreatment()</technical_language>

Target:
protected void ExecuteVmCommand() { VmDeviceUtils.updateVmDevices(getVm().getStaticData()); setActionReturnValue(VMStatus.Down); if (InitVm()) { if (getVm().getstatus() == VMStatus.Paused) { ResumeVm(); } else { if (!_isRerun && Boolean.TRUE.equals(getParameters().getRunAsStateless()) && !getVm().getDiskList().isEmpty() && getVm().getstatus() != VMStatus.Suspended) { StatelessVmTreatment(); } else if (!getParameters().getIsInternal() && !_isRerun && getVm().getstatus() != VMStatus.Suspended && statelessSnapshotExistsForVm()) { removeVmStatlessImages(); } else { RunVm(); } } } else { setActionReturnValue(getVm().getstatus()); } }
Source:
<code>public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) { if (HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY))) { if (request.get("commits") instanceof Collection) { Set<String> paths = new HashSet<>(); @SuppressWarnings("unchecked") Collection<Map<String, Object>> commits = (Collection<Map<String, Object>>) request .get("commits"); for (Map<String, Object> commit : commits) { addAllPaths(paths, commit, "added"); addAllPaths(paths, commit, "removed"); addAllPaths(paths, commit, "modified"); } if (!paths.isEmpty()) { <START> return new PropertyPathNotification(paths.toArray(new String[0])); <END> } } } return null; }</code><technical_language>Shouldnt size of String array size of paths</technical_language>

Target:
public PropertyPathNotification extract(MultiValueMap<String, String> headers, Map<String, Object> request) { if (HEADERS_VALUE.equals(headers.getFirst(HEADERS_KEY))) { if (request.get("commits") instanceof Collection) { Set<String> paths = new HashSet<>(); @SuppressWarnings("unchecked") Collection<Map<String, Object>> commits = (Collection<Map<String, Object>>) request .get("commits"); for (Map<String, Object> commit : commits) { addAllPaths(paths, commit, "added"); addAllPaths(paths, commit, "removed"); addAllPaths(paths, commit, "modified"); } if (!paths.isEmpty()) { return new PropertyPathNotification(paths.toArray(new String[paths.size()])); } } } return null; }
Source:
<code>public boolean hasMappingTargetParameter() { <START> for ( Parameter param : getParameterBindings() ) { <END> if ( param.isMappingTarget() ) { return true; } } return false; }</code><technical_language>do parameters bind? simply getParameters a name</technical_language>

Target:
public boolean hasMappingTargetParameter() { for ( ParameterBinding param : getParameterBindings() ) { if ( param.isMappingTarget() ) { return true; } } return false; }
Source:
<code>public short sizeInBytes() { switch (version) { case BLOB_ID_V1: <START> return (short) (VERSION_FIELD_LENGTH_IN_BYTES + partitionId.getBytes().length + UUID_SIZE_FIELD_LENGTH_IN_BYTES <END> + uuid.length()); case BLOB_ID_V2: return (short) (VERSION_FIELD_LENGTH_IN_BYTES + FLAG_FIELD_LENGTH_IN_BYTES + DATACENTER_ID_FIELD_LENGTH_IN_BYTES + ACCOUNT_ID_FIELD_LENGTH_IN_BYTES + CONTAINER_ID_FIELD_LENGTH_IN_BYTES + partitionId.getBytes().length + UUID_SIZE_FIELD_LENGTH_IN_BYTES + uuid.length()); default: throw new IllegalArgumentException("blobId version=" + version + " not supported"); } }</code><technical_language>try save size in a variable. Incase of V1, return right away. Incase of V2, build same</technical_language>

Target:
public short sizeInBytes() { short sizeForBlobIdV1 = (short) (VERSION_FIELD_LENGTH_IN_BYTES + partitionId.getBytes().length + UUID_SIZE_FIELD_LENGTH_IN_BYTES + uuid.getBytes().length); switch (version) { case BLOB_ID_V1: return sizeForBlobIdV1; case BLOB_ID_V2: return (short) (FLAG_FIELD_LENGTH_IN_BYTES + DATACENTER_ID_FIELD_LENGTH_IN_BYTES + ACCOUNT_ID_FIELD_LENGTH_IN_BYTES + CONTAINER_ID_FIELD_LENGTH_IN_BYTES + sizeForBlobIdV1); default: throw new IllegalArgumentException("blobId version=" + version + " not supported"); } }
Source:
<code>protected OAuth20Credentials getOAuthCredentials(final WebContext context) { if (configuration.isWithState()) { final Optional<String> stateParameter = context.getRequestParameter(OAuth20Configuration.STATE_REQUEST_PARAMETER); if (CommonHelper.isNotBlank(stateParameter.orElse(null))) { final String stateSessionAttributeName = this.configuration.getStateSessionAttributeName(client.getName()); final Optional<String> sessionState = context.getSessionStore().get(context, stateSessionAttributeName); context.getSessionStore().set(context, stateSessionAttributeName, null); logger.debug("sessionState: / stateParameter: {}", sessionState, stateParameter); if (!stateParameter.equals(sessionState)) { final String message = "State parameter mismatch: session expired or possible threat of cross-site request forgery"; throw new OAuthCredentialsException(message); } } else { final String message = "Missing state parameter: session expired or possible threat of cross-site request forgery"; throw new OAuthCredentialsException(message); } } final Optional<String> codeParameter = context.getRequestParameter(OAuth20Configuration.OAUTH_CODE); if (codeParameter.isPresent()) { <START> final String code = OAuthEncoder.decode(codeParameter.get()); <END> logger.debug("code: {}", code); return new OAuth20Credentials(code); } else { final String message = "No credential found"; throw new OAuthCredentialsException(message); } }</code><technical_language>map orThrow instead of checking of isPresent</technical_language>

Target:
protected OAuth20Credentials getOAuthCredentials(final WebContext context) { if (configuration.isWithState()) { final Optional<String> stateParameter = context.getRequestParameter(OAuth20Configuration.STATE_REQUEST_PARAMETER); if (CommonHelper.isNotBlank(stateParameter.orElse(null))) { final String stateSessionAttributeName = this.configuration.getStateSessionAttributeName(client.getName()); final Optional<String> sessionState = context.getSessionStore().get(context, stateSessionAttributeName); context.getSessionStore().set(context, stateSessionAttributeName, null); logger.debug("sessionState: / stateParameter: {}", sessionState, stateParameter); if (!stateParameter.equals(sessionState)) { final String message = "State parameter mismatch: session expired or possible threat of cross-site request forgery"; throw new OAuthCredentialsException(message); } } else { final String message = "Missing state parameter: session expired or possible threat of cross-site request forgery"; throw new OAuthCredentialsException(message); } } return context.getRequestParameter(OAuth20Configuration.OAUTH_CODE) .map( codeParameter -> { final String code = OAuthEncoder.decode(codeParameter); logger.debug("code: {}", code); return new OAuth20Credentials(code); } ).orElseThrow( () -> new OAuthCredentialsException("No credential found") ); }
Source:
<code>private void checkHomeAndWarnIfNeeded(TaskListener listener) { try { Computer computer = toComputer(); if (computer != null) { String home = computer.getEnvironment().get("HOME"); if ("/".equals(home)) { listener.getLogger().println(Messages.KubernetesSlave_HomeWarning()); } } } catch (IOException e) { e.printStackTrace(listener.error("[WARNING] Unable to retrieve HOME environment variable")); } catch (InterruptedException e) { <START> e.printStackTrace(listener.error("[WARNING] Interrupted while retrieving HOME environment variable")); <END> } }</code><technical_language>collapse catch clause</technical_language>

Target:
private void checkHomeAndWarnIfNeeded(TaskListener listener) { try { Computer computer = toComputer(); if (computer != null) { String home = computer.getEnvironment().get("HOME"); if ("/".equals(home)) { listener.getLogger().println(Messages.KubernetesSlave_HomeWarning()); } } } catch (IOException|InterruptedException e) { e.printStackTrace(listener.error("[WARNING] Unable to retrieve HOME environment variable")); } }
Source:
<code>ValidationResult validateBondMode(Bond modifiedOrNewBond) { <START> if (modifiedOrNewBond.getNetworkName()!=null){ <END> String invalidBondMode = getBondModeIfBondModeIsInvalid(modifiedOrNewBond); return ValidationResult.failWith(EngineMessage.INVALID_BONDMODE_FOR_BOND_WITH_ATTACHMENT, ReplacementUtils.createSetVariableString(VAR_BOND_NAME, modifiedOrNewBond.getName()), ReplacementUtils.createSetVariableString(VAR_BOND_MODE, invalidBondMode), ReplacementUtils.createSetVariableString(VAR_NETWORK_NAME, modifiedOrNewBond.getNetworkName())) .when(invalidBondMode != null); } return ValidationResult.VALID; }</code><technical_language>if false, reader skip a lot of code figure out, next. If turned other around, negative comparison (which if way) positive, return forming readable precondition test. operator, '!=' surrounded spaces</technical_language>

Target:
ValidationResult validateBondMode(Bond modifiedOrNewBond) { if (modifiedOrNewBond.getNetworkName() == null){ return ValidationResult.VALID; } String bondMode = getBondMode(modifiedOrNewBond); return ValidationResult.failWith(EngineMessage.INVALID_BOND_MODE_FOR_BOND_WITH_ATTACHMENT, ReplacementUtils.createSetVariableString(VAR_BOND_NAME, modifiedOrNewBond.getName()), ReplacementUtils.createSetVariableString(VAR_BOND_MODE, bondMode), ReplacementUtils.createSetVariableString(VAR_NETWORK_NAME, modifiedOrNewBond.getNetworkName())) .unless(isBondModeValid(bondMode)); }
Source:
<code>public DataPointProcessingParameters() { <START> super(new Parameter[] {processing, spectraProcessing}); <END> }</code><technical_language>more self-explanatory names processing, spectraProcessing? processingQueue, processingEnabled</technical_language>

Target:
public DataPointProcessingParameters() { super(new Parameter[] {processingParameters, enableProcessing}); }
Source:
<code><START> private static boolean copyFile(File src, File target) { <END> boolean ret = true; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (IOException ex) { ret = false; } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(System.err); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(System.err); } } return ret; }</code><technical_language>is need this isstatic</technical_language>

Target:
private boolean copyFile(File src, File target) { boolean ret = true; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (IOException ex) { ret = false; } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(System.err); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(System.err); } } return ret; }
Source:
<code>public void testVCFModeIsConcordantWithGATK3_5ResultsAlleleSpecificAnnotations() throws Exception { Utils.resetRandomGenerator(); final File output = createTempFile("testVCFModeIsConcordantWithGATK3_5ResultsAlleleSpecificAnnotations", ".vcf"); final File gatk3Output = new File(TEST_FILES_DIR + "expected.testVCFMode.gatk3.5.alleleSpecific.vcf"); final String[] args = new String[] { "-I", NA12878_20_21_WGS_bam, "-R", b37_reference_20_21, "-L", "20:10000000-10100000", "-O", output.getAbsolutePath(), "-G", "StandardAnnotation", "-G", "AS_StandardAnnotation", "-pairHMM", "AVX_LOGLESS_CACHING" }; runCommandLine(args); final double concordance = calculateConcordance(output, gatk3Output); <START> Assert.assertTrue(concordance >= 0.99, "Concordance with GATK 3.5 in VCF mode is < 99%"); <END> }</code><technical_language>in VCF mode -> in VCF mode</technical_language>

Target:
public void testVCFModeIsConcordantWithGATK3_5ResultsAlleleSpecificAnnotations() throws Exception { Utils.resetRandomGenerator(); final File output = createTempFile("testVCFModeIsConcordantWithGATK3_5ResultsAlleleSpecificAnnotations", ".vcf"); final File gatk3Output = new File(TEST_FILES_DIR + "expected.testVCFMode.gatk3.5.alleleSpecific.vcf"); final String[] args = { "-I", NA12878_20_21_WGS_bam, "-R", b37_reference_20_21, "-L", "20:10000000-10100000", "-O", output.getAbsolutePath(), "-G", "StandardAnnotation", "-G", "AS_StandardAnnotation", "-pairHMM", "AVX_LOGLESS_CACHING" }; runCommandLine(args); final double concordance = calculateConcordance(output, gatk3Output); Assert.assertTrue(concordance >= 0.99, "Concordance with GATK 3.5 in AS VCF mode is < 99%"); }
Source:
<code>public static ClassStub parseClass(URL url) throws IOException { SoftReference<ClassStub> ref = StubCache.map.get(url); ClassStub stub = ref == null ? null : ref.get(); if (stub == null) { DecompilingVisitor visitor = new DecompilingVisitor(); <START> new ClassReader(new BufferedInputStream(url.openStream())).accept(visitor, ClassReader.SKIP_FRAMES); <END> stub = visitor.result; StubCache.map.put(url, new SoftReference<ClassStub>(stub)); } return stub; }</code><technical_language>care of closing streams? (potential resource leak)</technical_language>

Target:
public static ClassStub parseClass(URL url) throws IOException { SoftReference<ClassStub> ref = StubCache.map.get(url); ClassStub stub = ref == null ? null : ref.get(); if (stub == null) { DecompilingVisitor visitor = new DecompilingVisitor(); InputStream stream = url.openStream(); try { new ClassReader(new BufferedInputStream(stream)).accept(visitor, ClassReader.SKIP_FRAMES); } finally { stream.close(); } stub = visitor.result; StubCache.map.put(url, new SoftReference<ClassStub>(stub)); } return stub; }
Source:
<code>private void cacheOrWriteItem(ModelWithPayload<Content> content, OwlTelescopeReporter telescope) { ModelWithPayload<Item> item = content.asModelType(Item.class); ParentRef parent = item.getModel().getContainer(); if (parent != null && !seenContainer.containsKey(parent.getUri())) { cached.put(parent.getUri(), item); } else { writer.createOrUpdate(content.asModelType(Item.class).getModel()); if(content.getModel().getId() != null){ telescope.reportSuccessfulEvent( content.getModel().getId(), content.getModel().getAliases(), EntityType.CONTENT, content.getPayload() <START> ); <END> } else { telescope.reportFailedEvent( "Atlas did not return an id after attempting to create or update this Content", EntityType.CONTENT, content.getPayload() ); } } }</code><technical_language>potentially of report successful event autoTypeDiscovery able pinpoint a bit type of Content this is</technical_language>

Target:
private void cacheOrWriteItem(ModelWithPayload<Content> content, OwlTelescopeReporter telescope) { ModelWithPayload<Item> item = content.asModelType(Item.class); ParentRef parent = item.getModel().getContainer(); if (parent != null && !seenContainer.containsKey(parent.getUri())) { cached.put(parent.getUri(), item); } else { writer.createOrUpdate(content.asModelType(Item.class).getModel()); if(content.getModel().getId() != null){ telescope.reportSuccessfulEvent( content.getModel().getId(), content.getModel().getAliases(), content.getModel(), content.getPayload() ); } else { telescope.reportFailedEvent( "Atlas did not return an id after attempting to create or update this Content", EntityType.CONTENT, content.getPayload() ); } } }
Source:
<code>KafkaConsumer contentBootstrapWorker() { ContentBootstrapWorker worker = ContentBootstrapWorker.create( persistence.legacyContentResolver(), persistence.contentStore(), <START> metricsModule.metrics().timer("ContentBootstrapWorker"), <END> metricsModule.metrics().meter("ContentBootstrapWorker.notWritten"), metricsModule.metrics().meter("ContentBootstrapWorker.errorRate"), ColumbusTelescopeReporter.create(getTelescopeClient(), reportingEnvironment) ); return bootstrapQueueFactory() .createConsumer( worker, new EntityUpdatedLegacyMessageSerializer(), contentChanges, "ContentBootstrap" ) .withConsumerSystem(consumerSystem) .withDefaultConsumers(contentChangesNumOfConsumers) .withMaxConsumers(contentChangesNumOfConsumers) .withPersistentRetryPolicy(persistence.databasedWriteMongo()) .build(); }</code><technical_language>metricsModule.metrics() creates a new registry time. Store value</technical_language>

Target:
KafkaConsumer contentBootstrapWorker() { MetricRegistry metricRegistry = metricsModule.metrics(); ContentBootstrapWorker worker = ContentBootstrapWorker.create( persistence.legacyContentResolver(), persistence.contentStore(), metricRegistry.timer("ContentBootstrapWorker"), metricRegistry.meter("ContentBootstrapWorker.notWritten"), metricRegistry.meter("ContentBootstrapWorker.errorRate"), ColumbusTelescopeReporter.create( getTelescopeClient(), reportingEnvironment, getObjectMapper() ) ); return bootstrapQueueFactory() .createConsumer( worker, new EntityUpdatedLegacyMessageSerializer(), contentChanges, "ContentBootstrap" ) .withConsumerSystem(consumerSystem) .withDefaultConsumers(contentChangesNumOfConsumers) .withMaxConsumers(contentChangesNumOfConsumers) .withPersistentRetryPolicy(persistence.databasedWriteMongo()) .build(); }
Source:
<code>public InvokableBuilder<Command> add_nodes(String labelOrId, int node_count) { RequestDetails entity = new RequestDetails(new AddNode(node_count), RequestDetails.Method.POST); <START> System.out.println(entity.getEntity()); <END> return new GenericInvokableBuilderImpl<Command>(client, entity, Command.class, "clusters", labelOrId, "nodes"); }</code><technical_language>println in code (apart tests examples). I hoping this earlier</technical_language>

Target:
public InvokableBuilder<Command> add_nodes(String labelOrId, int node_count) { RequestDetails entity = new RequestDetails(new AddNode(node_count), RequestDetails.Method.POST); return new GenericInvokableBuilderImpl<Command>(client, entity, Command.class, "clusters", labelOrId, "nodes"); }
Source:
<code>protected CartUpdateCommand buildRequest(final Cart cart, final AddDiscountCodeFormData addDiscountCodeFormData) { final AddDiscountCode addDiscountCode = AddDiscountCode.of(addDiscountCodeFormData.code()); <START> return CartUpdateCommand.of(cart, Arrays.asList(addDiscountCode)); <END> }</code><technical_language>asList is necessary, a of method for single action. in this case singletonList suffice :)</technical_language>

Target:
protected CartUpdateCommand buildRequest(final Cart cart, final AddDiscountCodeFormData addDiscountCodeFormData) { final AddDiscountCode addDiscountCode = AddDiscountCode.of(addDiscountCodeFormData.code()); return CartUpdateCommand.of(cart, addDiscountCode); }
Source:
<code>private void checkLine(boolean flush) { String buffer = currentLine.toString(); int i = 0; while ((i = buffer.indexOf('\n')) != -1) { String line = buffer.substring(0, i); <START> if (line.endsWith("\r")) END> line=line.substring(0,line.length()-1); processLine(line); previousLine = line; buffer = buffer.substring(i + 1); } currentLine.setLength(0); if (flush) { if (buffer.length() > 0) { processLine(buffer); previousLine = buffer; } } else { currentLine.append(buffer); } }</code><technical_language>Please bring braces back</technical_language>

Target:
private void checkLine(boolean flush) { String buffer = currentLine.toString(); int i = 0; while ((i = buffer.indexOf('\n')) != -1) { String line = buffer.substring(0, i); if (line.endsWith("\r")) { line=line.substring(0,line.length()-1); } processLine(line); previousLine = line; buffer = buffer.substring(i + 1); } currentLine.setLength(0); if (flush) { if (buffer.length() > 0) { processLine(buffer); previousLine = buffer; } } else { currentLine.append(buffer); } }
Source:
<code>private static StateItem createState(LinuxStyle style) { int rgbInt = (int) style.toMap().getOrDefault(ITimeEventStyle.FILL_COLOR(), 0); RGB color = new RGB(rgbInt >> 24 & 0xff, rgbInt >> 16 & 0xff, rgbInt >> 8 & 0xff); return new StateItem(color, style.getLabel()) { @Override public Map<String, Object> getStyleMap() { <START> return style.toMap(); <END> } }; }</code><technical_language>In stateItem constructor, build a style map fill_color is RGB, style map, here, simply return LinuxStyle's map, fill_color int. A caller of getStyleMap() expect receive here, for fill_color, surprised</technical_language>

Target:
private static StateItem createState(LinuxStyle style) { int rgbInt = (int) style.toMap().getOrDefault(ITimeEventStyleStrings.fillColor(), 0); RGB color = new RGB(rgbInt >> 24 & 0xff, rgbInt >> 16 & 0xff, rgbInt >> 8 & 0xff); return new StateItem(color, style.getLabel()) { @Override public Map<String, Object> getStyleMap() { return style.toMap(); } }; }
Source:
<code>public void openTestShells() { Display.syncExec(() -> { for (int i = 1; i <= TEST_SHELLS_COUNT; i++) { String shellTitle = "shell" + i; ShellTestUtils.createShell(shellTitle); <START> shells.add(new DefaultShell(shellTitle)); <END> } }); }</code><technical_language>do create new DefaultShell syncexec</technical_language>

Target:
public void openTestShells() { for (int i = 1; i <= TEST_SHELLS_COUNT; i++) { String shellTitle = "shell" + i; Display.syncExec(() -> { ShellTestUtils.createShell(shellTitle); }); shells.add(new DefaultShell(shellTitle)); } }
Source:
<code>public VariantContextBuilder filters(final Set<String> filters) { makeFiltersModifiable(); if (filters == null) { <START> unfiltered(); <END> } else { this.filters.clear(); this.filters.addAll(filters); toValidate.add(VariantContext.Validation.FILTERS); } return this; }</code><technical_language>This nulls out filters; if this path is point in calling makeFiltersModifiable()</technical_language>

Target:
public VariantContextBuilder filters(final Set<String> filters) { if (filters == null) { unfiltered(); } else { this.filtersCanBeModified = true; filtersAsIs(new HashSet<>(filters)); } return this; }