auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public PlatformRestrictionsResult checkPlatformRestrictions( ImmutableList<ConfiguredTarget> topLevelTargets, ImmutableSet<String> explicitTargetPatterns, boolean keepGoing) throws ViewCreationFailedException { ImmutableSet.Builder<ConfiguredTarget> incompatibleTargets = ImmutableSet.builder(); ImmutableSet.Builder<ConfiguredTarget> incompatibleButRequestedTargets = ImmutableSet.builder(); for (ConfiguredTarget target : topLevelTargets) { IncompatiblePlatformProvider incompatibleProvider = target.getProvider(IncompatiblePlatformProvider.class); if (incompatibleProvider == null) { continue; } String labelString = target.getLabel().getUnambiguousCanonicalForm(); if (explicitTargetPatterns.contains(labelString)) { if (!keepGoing) { String targetIncompatibleMessage = ("Target " + target.getLabel().toString() + " is incompatible and cannot be built, but was explicitly requested."); targetIncompatibleMessage += reportOnIncompatibility(target); throw new ViewCreationFailedException( targetIncompatibleMessage, FailureDetail.newBuilder() .setMessage(targetIncompatibleMessage) .setAnalysis(Analysis.newBuilder().setCode(Code.INCOMPATIBLE_TARGET_REQUESTED)) .build()); } this.eventHandler.handle( Event.warn( "Incompatible target " + labelString + " was explicitly requested: it will not be built")); incompatibleButRequestedTargets.add(target); } else { incompatibleTargets.add(target); } } return new PlatformRestrictionsResult( ImmutableSet.copyOf(incompatibleTargets.build()), ImmutableSet.copyOf(incompatibleButRequestedTargets.build())); }

Target:
public PlatformRestrictionsResult checkPlatformRestrictions( ImmutableList<ConfiguredTarget> topLevelTargets, ImmutableSet<String> explicitTargetPatterns, boolean keepGoing) throws ViewCreationFailedException { ImmutableSet.Builder<ConfiguredTarget> incompatibleTargets = ImmutableSet.builder(); ImmutableSet.Builder<ConfiguredTarget> incompatibleButRequestedTargets = ImmutableSet.builder(); for (ConfiguredTarget target : topLevelTargets) { IncompatiblePlatformProvider incompatibleProvider = target.getProvider(IncompatiblePlatformProvider.class); if (incompatibleProvider == null) { continue; } String labelString = target.getLabel().getUnambiguousCanonicalForm(); if (explicitTargetPatterns.contains(labelString)) { if (!keepGoing) { String targetIncompatibleMessage = String.format( TARGET_INCOMPATIBLE_ERROR_TEMPLATE, target.getLabel().toString(), reportOnIncompatibility(target)); throw new ViewCreationFailedException( targetIncompatibleMessage, FailureDetail.newBuilder() .setMessage(targetIncompatibleMessage) .setAnalysis(Analysis.newBuilder().setCode(Code.INCOMPATIBLE_TARGET_REQUESTED)) .build()); } this.eventHandler.handle( Event.warn(String.format(TARGET_INCOMPATIBLE_ERROR_TEMPLATE, labelString, ""))); incompatibleButRequestedTargets.add(target); } else { incompatibleTargets.add(target); } } return PlatformRestrictionsResult.builder() .targetsToSkip(ImmutableSet.copyOf(incompatibleTargets.build())) .targetsWithErrors(ImmutableSet.copyOf(incompatibleButRequestedTargets.build())) .build(); }
Source:
public void testGetErrorResponse() { int throttleTimeMs = 10; WriteTxnMarkersRequest.Builder builder = new WriteTxnMarkersRequest.Builder(markers); for (short version = 0; version <= ApiKeys.WRITE_TXN_MARKERS.latestVersion(); version++) { WriteTxnMarkersRequest request = builder.build(version); WriteTxnMarkersResponse errorResponse = request.getErrorResponse(throttleTimeMs, Errors.UNKNOWN_PRODUCER_ID.exception()); assertEquals(Collections.singletonMap( topicPartition, Errors.UNKNOWN_PRODUCER_ID), errorResponse.errors(producerId)); assertEquals(Collections.singletonMap(Errors.UNKNOWN_PRODUCER_ID, 1), errorResponse.errorCounts()); assertEquals(0, errorResponse.throttleTimeMs()); } }

Target:
public void testGetErrorResponse() { WriteTxnMarkersRequest.Builder builder = new WriteTxnMarkersRequest.Builder(markers); for (short version = 0; version <= ApiKeys.WRITE_TXN_MARKERS.latestVersion(); version++) { WriteTxnMarkersRequest request = builder.build(version); WriteTxnMarkersResponse errorResponse = request.getErrorResponse(throttleTimeMs, Errors.UNKNOWN_PRODUCER_ID.exception()); assertEquals(Collections.singletonMap( topicPartition, Errors.UNKNOWN_PRODUCER_ID), errorResponse.errors(producerId)); assertEquals(Collections.singletonMap(Errors.UNKNOWN_PRODUCER_ID, 1), errorResponse.errorCounts()); assertEquals(0, errorResponse.throttleTimeMs()); } }
Source:
public static void startup(Properties p) { applyLogLevels(); setupLogAppenders(); }

Target:
public static void startup(Properties p) { String val = p.getProperty("obscure_patients", null); if (val != null && "true".equalsIgnoreCase(val)) { OpenmrsConstants.OBSCURE_PATIENTS = true; } val = p.getProperty("obscure_patients.family_name", null); if (val != null) { OpenmrsConstants.OBSCURE_PATIENTS_FAMILY_NAME = val; } val = p.getProperty("obscure_patients.given_name", null); if (val != null) { OpenmrsConstants.OBSCURE_PATIENTS_GIVEN_NAME = val; } val = p.getProperty("obscure_patients.middle_name", null); if (val != null) { OpenmrsConstants.OBSCURE_PATIENTS_MIDDLE_NAME = val; } val = p.getProperty("connection.database_name", null); if (val == null) { val = p.getProperty("connection.url", null); if (val != null) { try { int endIndex = val.lastIndexOf("?"); if (endIndex == -1) { endIndex = val.length(); } int startIndex = val.lastIndexOf("/", endIndex); val = val.substring(startIndex + 1, endIndex); OpenmrsConstants.DATABASE_NAME = val; } catch (Exception e) { log.error(MarkerFactory.getMarker("FATAL"), "Database name cannot be configured from 'connection.url' ." + "Either supply 'connection.database_name' or correct the url", e); } } } val = p.getProperty("connection.database_business_name", null); if (val == null) { val = OpenmrsConstants.DATABASE_NAME; } OpenmrsConstants.DATABASE_BUSINESS_NAME = val; applyLogLevels(); setupLogAppenders(); }
Source:
private CreationStatus getJobIdStatus(VdcReturnValueBase result) { NGuid jobId = result.getJobId(); if (jobId ==null || jobId.getValue().equals(NGuid.Empty)) { return CreationStatus.COMPLETE; } else { GetJobByJobIdQueryParameters params = new GetJobByJobIdQueryParameters(); params.setJobId(jobId.getValue()); VdcQueryReturnValue queryResult = backend.RunQuery(VdcQueryType.GetJobByJobId, sessionize(params)); if (queryResult != null && queryResult.getSucceeded() && queryResult.getReturnValue() != null) { Job job = (Job)queryResult.getReturnValue(); return job.getStatus()==JobExecutionStatus.STARTED ? CreationStatus.IN_PROGRESS : CreationStatus.COMPLETE; } else { return CreationStatus.COMPLETE; } } }

Target:
private CreationStatus getJobIdStatus(VdcReturnValueBase result) { NGuid jobId = result.getJobId(); if (jobId ==null || jobId.getValue().equals(NGuid.Empty)) { return CreationStatus.COMPLETE; } else { GetJobByJobIdQueryParameters params = new GetJobByJobIdQueryParameters(); params.setJobId(jobId.getValue()); VdcQueryReturnValue queryResult = runQuery(VdcQueryType.GetJobByJobId, params); if (queryResult != null && queryResult.getSucceeded() && queryResult.getReturnValue() != null) { Job job = (Job)queryResult.getReturnValue(); return job.getStatus()==JobExecutionStatus.STARTED ? CreationStatus.IN_PROGRESS : CreationStatus.COMPLETE; } else { return CreationStatus.COMPLETE; } } }
Source:
public void imageLink(Attributes linkAttributes, Attributes imageAttributes, String href, String imageUrl) { link(linkAttributes, href, "{{" + Strings.nullToEmpty(imageUrl) + "}}"); }

Target:
public void imageLink(Attributes linkAttributes, Attributes imageAttributes, String href, String imageUrl) { String altText = ""; if (imageAttributes instanceof ImageAttributes && !Strings.isNullOrEmpty(((ImageAttributes) imageAttributes).getAlt())) { altText = ((ImageAttributes) imageAttributes).getAlt(); } link(linkAttributes, href, "{{" + Strings.nullToEmpty(imageUrl) + "}}" + altText); }
Source:
public static String convertStorageExceptionMessage(String message, HttpResponse response) { if (response != null) { if (response.getStatusCode() == 403) { return String.format("If you are using a StorageSharedKeyCredential, and the server returned an " + "error message that says 'Signature did not match', you can compare the string to sign with" + " the one generated by the SDK. To log the string to sign, pass in the context key value pair " + "'%s': true to the appropriate method call.%n" + "If you are using a SAS token, and the server returned an error message that says " + "'Signature did not match', you can compare the string to sign with" + " the one generated by the SDK. To log the string to sign, pass in the context key value " + "pair '%s': true to the appropriate generateSas method call.%n" + "Please remember to disable '%s' before going to production as this string can potentially " + "contain PII.%n", Constants.STORAGE_LOG_STRING_TO_SIGN, Constants.STORAGE_LOG_STRING_TO_SIGN, Constants.STORAGE_LOG_STRING_TO_SIGN) + message; } if (response.getRequest() != null && response.getRequest().getHttpMethod() != null && response.getRequest().getHttpMethod().equals(HttpMethod.HEAD) && response.getHeaders().getValue(ERROR_CODE) != null) { return message.replaceFirst("(empty body)", response.getHeaders().getValue(ERROR_CODE)); } } return message; }

Target:
public static String convertStorageExceptionMessage(String message, HttpResponse response) { if (response != null) { if (response.getStatusCode() == 403) { return STORAGE_EXCEPTION_LOG_STRING_TO_SIGN_MESSAGE + message; } if (response.getRequest() != null && response.getRequest().getHttpMethod() != null && response.getRequest().getHttpMethod().equals(HttpMethod.HEAD) && response.getHeaders().getValue(ERROR_CODE) != null) { return message.replaceFirst("(empty body)", response.getHeaders().getValue(ERROR_CODE)); } } return message; }
Source:
private void assertExpiredEvents(int count) { eventually("Last count was :" + listener.getInvocationCount(), () -> count == listener.getInvocationCount()); listener.getEvents().forEach(event -> { assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType()); assertEquals(cache, event.getCache()); assertFalse(event.isPre()); assertNotNull(event.getKey()); assertNotNull(event.getValue()); assertNotNull(event.getMetadata()); }); }

Target:
private void assertExpiredEvents(int count) { eventuallyEquals(count, () -> listener.getInvocationCount()); listener.getEvents().forEach(event -> { assertEquals(Event.Type.CACHE_ENTRY_EXPIRED, event.getType()); assertEquals(cache, event.getCache()); assertFalse(event.isPre()); assertNotNull(event.getKey()); assertNotNull(event.getValue()); assertNotNull(event.getMetadata()); }); }
Source:
private void rectifyCreatedTime(WorkspaceActivity activity) throws ServerException { if (activity.getCreated() == null) { try { Workspace workspace = workspaceManager.getWorkspace(activity.getWorkspaceId()); long createdTime = Long.parseLong(workspace.getAttributes().get(Constants.CREATED_ATTRIBUTE_NAME)); LOG.warn( "Workspace doesn't have any information about when it was created or last seen" + " starting. Setting the created time to {}.", activity.getWorkspaceId(), createdTime); activityDao.setCreatedTime(activity.getWorkspaceId(), createdTime); activity.setCreated(createdTime); } catch (NumberFormatException e) { LOG.error( "Failed to read the created time of the workspace from its attributes.", activity.getWorkspaceId(), e); } catch (NotFoundException e) { LOG.error( "Detected a running workspace but could not find" + " its record.", activity.getWorkspaceId(), e); } } }

Target:
private void rectifyCreatedTime(WorkspaceActivity activity) throws ServerException { if (activity.getCreated() != null) { return; } try { Workspace workspace = workspaceManager.getWorkspace(activity.getWorkspaceId()); long createdTime; try { createdTime = Long.parseLong(workspace.getAttributes().get(Constants.CREATED_ATTRIBUTE_NAME)); LOG.warn( "Workspace '{}' doesn't have any information about when it was created or last seen" + " starting. Setting the created time to {}.", activity.getWorkspaceId(), createdTime); } catch (NumberFormatException e) { Long oldestActivityTime = getOldestActivityTime(activity); if (oldestActivityTime == null) { long now = clock.millis(); LOG.error( "Failed to read the created time of the workspace '{}' from its attributes. Using" + " the current time ({}) for it because no other activity was ever recorded on" + " the workspace.", activity.getWorkspaceId(), now, e); createdTime = now; } else { LOG.error( "Failed to read the created time of the workspace '{}' from its attributes. Using" + " the oldest activity time found on it ({}) as its created time.", activity.getWorkspaceId(), oldestActivityTime, e); createdTime = oldestActivityTime; } } activityDao.setCreatedTime(activity.getWorkspaceId(), createdTime); activity.setCreated(createdTime); } catch (NotFoundException e) { LOG.error( "Detected a running workspace '{}' but could not find" + " its record.", activity.getWorkspaceId(), e); } }
Source:
public static List<String> getAllPaths(InputStream in) throws IOException { Assert.notNull(in); List<String> paths = new ArrayList<String>(); TarArchiveInputStream archiveIn = new TarArchiveInputStream(new GZIPInputStream(in)); try { for (ArchiveEntry nextEntry; (nextEntry = archiveIn.getNextEntry()) != null;) { paths.add(nextEntry.getName()); } return paths; } finally { StreamUtils.close(archiveIn); } }

Target:
public static List<String> getAllPaths(InputStream in) throws IOException { Assert.notNull(in); List<String> paths = new ArrayList<String>(); TarArchiveInputStream archiveIn = new TarArchiveInputStream(new GZIPInputStream(in)); try { for (ArchiveEntry nextEntry = null; (nextEntry = archiveIn.getNextEntry()) != null;) { paths.add(nextEntry.getName()); } return paths; } finally { StreamUtils.close(archiveIn); } }
Source:
private List<ConstrainedTerm> fastComputeRewriteStep(ConstrainedTerm subject, boolean computeOne) { List<ConstrainedTerm> results = new ArrayList<>(); List<Pair<Substitution<Variable, Term>, Integer>> matches = theFastMatcher.mainMatch(subject.term(), definition.automaton.leftHandSide(), allRuleBits); for (Pair<Substitution<Variable, Term>, Integer> pair : matches) { Rule rule = definition.ruleTable.get(pair.getRight()); Substitution<Variable, Term> substitution = RewriteEngineUtils.evaluateConditions(rule, pair.getLeft(), subject.termContext()); if (substitution != null) { Map<scala.collection.immutable.List<Integer>, Term> rewrites = theFastMatcher.getRewrites()[pair.getRight()]; List<Pair<scala.collection.immutable.List<Integer>, Term>> cleanedUpRewrites = rewrites.entrySet().stream().map(e -> Pair.of(e.getKey().reverse(), e.getValue())).collect(Collectors.toList()); Term theNew; if (cleanedUpRewrites.size() == 1) theNew = buildRHS(subject.term(), substitution, cleanedUpRewrites.get(0).getLeft(), cleanedUpRewrites.get(0).getRight(), subject.termContext()); else theNew = buildRHS((KItem) subject.term(), substitution, cleanedUpRewrites, subject.termContext()); results.add(new ConstrainedTerm(theNew, subject.termContext())); if (computeOne) { break; } } } return results; }

Target:
private List<ConstrainedTerm> fastComputeRewriteStep(ConstrainedTerm subject, boolean computeOne) { List<ConstrainedTerm> results = new ArrayList<>(); List<Pair<Substitution<Variable, Term>, Integer>> matches = theFastMatcher.mainMatch(subject.term(), definition.automaton.leftHandSide(), allRuleBits); for (Pair<Substitution<Variable, Term>, Integer> pair : matches) { Rule rule = definition.ruleTable.get(pair.getRight()); Substitution<Variable, Term> substitution = RewriteEngineUtils.evaluateConditions(rule, pair.getLeft(), subject.termContext()); if (substitution != null) { Map<scala.collection.immutable.List<Integer>, Term> rewrites = theFastMatcher.getRewrites()[pair.getRight()]; assert (rewrites.size() > 0); Term theNew; if (rewrites.size() == 1) theNew = buildRHS(subject.term(), substitution, rewrites.keySet().iterator().next(), rewrites.values().iterator().next(), subject.termContext()); else theNew = buildRHS(subject.term(), substitution, rewrites.entrySet().stream().map(e -> Pair.of(e.getKey(), e.getValue())).collect(Collectors.toList()), subject.termContext()); results.add(new ConstrainedTerm(theNew, subject.termContext())); if (computeOne) { break; } } } return results; }
Source:
public void theGetFirmwareVersionRequestIsReceived(final Map<String, String> requestData) throws Throwable { final Map<String, String> settings = new HashMap<>(); settings.put(PlatformSmartmeteringKeys.KEY_DEVICE_IDENTIFICATION, requestData.get(PlatformSmartmeteringKeys.KEY_DEVICE_IDENTIFICATION)); final GetFirmwareVersionRequest getFirmwareVersionRequest = GetFirmwareVersionRequestFactory .fromParameterMap(settings); final GetFirmwareVersionAsyncResponse getFirmwareVersionAsyncResponse = this.smartMeteringConfigurationClient .getFirmwareVersion(getFirmwareVersionRequest); LOGGER.info("Get firmware version asyncResponse is received {}", getFirmwareVersionAsyncResponse); assertNotNull("Get firmware version asyncResponse should not be null", getFirmwareVersionAsyncResponse); ScenarioContext.current().put(PlatformSmartmeteringKeys.KEY_CORRELATION_UID, getFirmwareVersionAsyncResponse.getCorrelationUid()); }

Target:
public void theGetFirmwareVersionRequestIsReceived(final Map<String, String> requestData) throws Throwable { final GetFirmwareVersionRequest getFirmwareVersionRequest = GetFirmwareVersionRequestFactory .fromParameterMap(requestData); final GetFirmwareVersionAsyncResponse getFirmwareVersionAsyncResponse = this.smartMeteringConfigurationClient .getFirmwareVersion(getFirmwareVersionRequest); assertNotNull("Get firmware version asyncResponse should not be null", getFirmwareVersionAsyncResponse); LOGGER.info("Get firmware version asyncResponse is received {}", getFirmwareVersionAsyncResponse); ScenarioContext.current().put(PlatformSmartmeteringKeys.KEY_CORRELATION_UID, getFirmwareVersionAsyncResponse.getCorrelationUid()); }
Source:
public boolean isFocusControl () { checkWidget(); if ((text != null && text.isFocusControl ()) || (arrow != null && arrow.isFocusControl ()) || (list != null && list.isFocusControl ()) || (popup != null && popup.isFocusControl ())) { return true; } return super.isFocusControl (); }

Target:
public boolean isFocusControl () { checkWidget(); boolean notNull = (text != null || arrow != null || list != null || popup != null); if (notNull && (text.isFocusControl () || arrow.isFocusControl () || list.isFocusControl () || popup.isFocusControl ())) { return true; } return super.isFocusControl (); }
Source:
public boolean setBranchSameAsAccess(boolean branchSameAsAccess) { return this.branchSameAsAccess = branchSameAsAccess; }

Target:
public void setBranchSameAsAccess(boolean branchSameAsAccess) { this.branchSameAsAccess = branchSameAsAccess; }
Source:
public boolean isRebootCommandExecutionAllowed(List<VM> vms) { if (vms.isEmpty() || !VdcActionUtils.canExecute(vms, VM.class, VdcActionType.RebootVm)) { return false; } for (VM vm : vms) { Version version = vm.getVdsGroupCompatibilityVersion(); Version anyDcVersion = new Version(); if (!isCommandCompatible(VdcActionType.RebootVm, version, anyDcVersion) || (StringHelper.isNullOrEmpty(vm.getVmIp()) && Boolean.FALSE.equals(vm.getAcpiEnable()))) { return false; } } return true; }

Target:
public boolean isRebootCommandExecutionAllowed(List<VM> vms) { if (vms.isEmpty() || !VdcActionUtils.canExecute(vms, VM.class, VdcActionType.RebootVm)) { return false; } for (VM vm : vms) { Version version = vm.getVdsGroupCompatibilityVersion(); Version anyDcVersion = new Version(); boolean compatibleCluster = isCommandCompatible(VdcActionType.RebootVm, version, anyDcVersion); boolean guestAgentPresent = !StringHelper.isNullOrEmpty(vm.getVmIp()); boolean acpiEnabled = Boolean.FALSE.equals(vm.getAcpiEnable()); if (!(compatibleCluster && (guestAgentPresent || acpiEnabled))) { return false; } } return true; }
Source:
public IBoundaryStrategy getStrategy(){ if (proxy == null) { try { proxy = (IBoundaryStrategy)configElement.createExecutableExtension("class"); } catch (CoreException e) { e.printStackTrace(); } } return proxy; }

Target:
public IBoundaryStrategy getStrategy(){ if (strategy == null) { try { strategy = (IBoundaryStrategy)configElement.createExecutableExtension("class"); } catch (CoreException e) { e.printStackTrace(); } } return strategy; }
Source:
void sendUnsub(NatsSubscription sub, int after) { ByteArrayBuilder bab = new ByteArrayBuilder(OP_UNSUB_PROTOCOL_LEN + 29) .append(OP_UNSUB_PROTOCOL_BYTES, OP_UNSUB_PROTOCOL_LEN) .append(sub.getSID()); if (after > 0) { bab.appendSpace().append(after); } NatsMessage unsubMsg = new NatsMessage(bab.toByteArray()); queueInternalOutgoing(unsubMsg); }

Target:
void sendUnsub(NatsSubscription sub, int after) { ByteArrayBuilder bab = new ByteArrayBuilder(OP_UNSUB_SP_LEN + 29) .append(UNSUB_SP_BYTES) .append(sub.getSID()); if (after > 0) { bab.appendSpace().append(after); } NatsMessage unsubMsg = new NatsMessage(bab.toByteArray()); queueInternalOutgoing(unsubMsg); }
Source:
RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { try { for (;;) { final RevCommit c = pending.next(); if (c == null) { return null; } final boolean produce; if ((c.flags & UNINTERESTING) != 0) produce = false; else { if (filter.requiresCommitBody()) c.parseBody(walker); produce = filter.include(walker, c); } for (int i = 0; i < c.parents.length; i++) { RevCommit p = c.parents[i]; if (firstParent && i > 0 && (c.flags & UNINTERESTING) == 0) break; if ((p.flags & SEEN) != 0) continue; if ((p.flags & PARSED) == 0) p.parseHeaders(walker); p.flags |= SEEN; pending.add(p); } walker.carryFlagsImpl(c); if ((c.flags & UNINTERESTING) != 0) { if (pending.everbodyHasFlag(UNINTERESTING)) { final RevCommit n = pending.peek(); if (n != null && n.commitTime >= last.commitTime) { overScan = OVER_SCAN; } else if (--overScan == 0) throw StopWalkException.INSTANCE; } else { overScan = OVER_SCAN; } if (canDispose) c.disposeBody(); continue; } if (produce) return last = c; else if (canDispose) c.disposeBody(); } } catch (StopWalkException swe) { pending.clear(); return null; } }

Target:
RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { try { for (;;) { final RevCommit c = pending.next(); if (c == null) { return null; } final boolean produce; if ((c.flags & UNINTERESTING) != 0) produce = false; else { if (filter.requiresCommitBody()) c.parseBody(walker); produce = filter.include(walker, c); } for (int i = 0; i < c.parents.length; i++) { RevCommit p = c.parents[i]; if (firstParent && i > 0 && (c.flags & UNINTERESTING) == 0) { continue; } if ((p.flags & SEEN) != 0) continue; if ((p.flags & PARSED) == 0) p.parseHeaders(walker); p.flags |= SEEN; pending.add(p); } walker.carryFlagsImpl(c); if ((c.flags & UNINTERESTING) != 0) { if (pending.everbodyHasFlag(UNINTERESTING)) { final RevCommit n = pending.peek(); if (n != null && n.commitTime >= last.commitTime) { overScan = OVER_SCAN; } else if (--overScan == 0) throw StopWalkException.INSTANCE; } else { overScan = OVER_SCAN; } if (canDispose) c.disposeBody(); continue; } if (produce) return last = c; else if (canDispose) c.disposeBody(); } } catch (StopWalkException swe) { pending.clear(); return null; } }
Source:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf"); Log.d("OpenActivity", this.getClass().getName()); }

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf"); }
Source:
public void testDeleteAction() throws Exception { String courseId = "CCAddUiTest.course1"; coursesPage.getDeleteLink(courseId).click(); coursesPage.waitForConfirmationModalAndClickCancel(); assertNotNull(BackDoor.getCourseAsJson(courseId)); coursesPage.getDeleteLink(courseId).click(); coursesPage.waitForConfirmationModalAndClickOk(); coursesPage.verifyHtmlMainContent("/instructorCoursesDeleteSuccessful.html"); }

Target:
public void testDeleteAction() throws Exception { String courseId = "CCAddUiTest.course1"; coursesPage.clickAndCancel(coursesPage.getDeleteLink(courseId)); assertNotNull(BackDoor.getCourseAsJson(courseId)); coursesPage.clickAndConfirm(coursesPage.getDeleteLink(courseId)) .verifyHtmlMainContent("/instructorCoursesDeleteSuccessful.html"); }
Source:
public DynamicTableSink createDynamicTableSink(Context context) { ElasticsearchValidationUtils.validatePrimaryKey(context.getCatalogTable().getSchema()); final FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); final SinkFormat<SerializationSchema<RowData>> format = helper.discoverSinkFormat( SerializationFormatFactory.class, FORMAT_OPTION); helper.validate(); Configuration configuration = new Configuration(); context.getCatalogTable() .getOptions() .forEach(configuration::setString); Elasticsearch6Configuration config = new Elasticsearch6Configuration(configuration, context.getClassLoader()); validate(config, configuration); return new Elasticsearch6DynamicSink( format, config, context.getCatalogTable().getSchema()); }

Target:
public DynamicTableSink createDynamicTableSink(Context context) { TableSchema tableSchema = context.getCatalogTable().getSchema(); ElasticsearchValidationUtils.validatePrimaryKey(tableSchema); final FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); final SinkFormat<SerializationSchema<RowData>> format = helper.discoverSinkFormat( SerializationFormatFactory.class, FORMAT_OPTION); helper.validate(); Configuration configuration = new Configuration(); context.getCatalogTable() .getOptions() .forEach(configuration::setString); Elasticsearch6Configuration config = new Elasticsearch6Configuration(configuration, context.getClassLoader()); validate(config, configuration); return new Elasticsearch6DynamicSink( format, config, TableSchemaUtils.getPhysicalSchema(tableSchema)); }
Source:
private LiteralSuggestion getMgrsSuggestion(String query) { List<String> matches = coordinateStringsFromQuery(query); StringBuilder nameBuilder = new StringBuilder("MGRS: "); matches.forEach(mgrs -> nameBuilder.append("[ ").append(mgrs).append(" ] ")); if (matches.isEmpty()) { return null; } if (matches.size() == 1) { String mgrs = matches.get(0); UsngCoordinate mgrsCoord = parseMgrsString(mgrs); BoundingBox bb = translator.toBoundingBox(mgrsCoord); return new LiteralSuggestion("LITERAL", nameBuilder.toString(), latLonFromBoundingBox(bb)); } List<LatLon> geo = matches .stream() .distinct() .map(this::parseMgrsString) .filter(Objects::nonNull) .map(translator::toLatLon) .map(d -> from(d.getLat(), d.getLon())) .collect(Collectors.toList()); return new LiteralSuggestion("LITERAL", nameBuilder.toString(), geo); }

Target:
private LiteralSuggestion getMgrsSuggestion(String query) { final List<String> matches = getMgrsCoordinateStrings(query); if (matches.isEmpty()) { LOGGER.debug("No valid MGRS strings were found or could be inferred from query [{}]", query); return null; } final List<UsngCoordinate> mgrsCoordinates = new ArrayList<>(); final StringBuilder nameBuilder = new StringBuilder("MGRS:"); for (String match : matches) { final UsngCoordinate coordinate = parseMgrsString(match); if (coordinate == null || mgrsCoordinates.contains(coordinate)) { continue; } mgrsCoordinates.add(coordinate); nameBuilder.append(" [ ").append(coordinate.toMgrsString()).append(" ]"); } if (mgrsCoordinates.size() == 1) { final UsngCoordinate mgrsCoord = mgrsCoordinates.get(0); final BoundingBox bb = translator.toBoundingBox(mgrsCoord); return new LiteralSuggestion( LITERAL_SUGGESTION_ID, nameBuilder.toString(), latLonFromBoundingBox(bb)); } return new LiteralSuggestion( LITERAL_SUGGESTION_ID, nameBuilder.toString(), mgrsCoordinates .stream() .map(translator::toLatLon) .map(d -> new LatLon(d.getLat(), d.getLon())) .collect(Collectors.toList())); }
Source:
createRecordReader(InputSplit split, TaskAttemptContext taskAttempt) throws IOException, InterruptedException { Configuration conf = taskAttempt.getConfiguration(); if (typeRef == null) { setTypeRef(conf); } Class<?> recordClass = typeRef.getRawClass(); Format fileFormat = determineFileFormat(split, conf); ThriftToPig.LOG.info("XXX " + ((FileSplit)split).getPath() + " == " + fileFormat); if (TBase.class.isAssignableFrom(recordClass)) { switch (fileFormat) { case LZO_BLOCK: return new LzoThriftBlockRecordReader(typeRef); case LZO_B64LINE: return new LzoThriftB64LineRecordReader(typeRef); } } if (Message.class.isAssignableFrom(recordClass)) { switch (fileFormat) { case LZO_BLOCK: return new LzoProtobufBlockRecordReader(typeRef); case LZO_B64LINE: return new LzoProtobufBlockRecordReader(typeRef); } } throw new IOException( "could not determine reader for " + ((FileSplit)split).getPath() + " with class " + recordClass.getName()); }

Target:
createRecordReader(InputSplit split, TaskAttemptContext taskAttempt) throws IOException, InterruptedException { Configuration conf = taskAttempt.getConfiguration(); if (typeRef == null) { setTypeRef(conf); } Class<?> recordClass = typeRef.getRawClass(); Format fileFormat = determineFileFormat(split, conf); if (TBase.class.isAssignableFrom(recordClass)) { switch (fileFormat) { case LZO_BLOCK: return new LzoThriftBlockRecordReader(typeRef); case LZO_B64LINE: return new LzoThriftB64LineRecordReader(typeRef); } } if (Message.class.isAssignableFrom(recordClass)) { switch (fileFormat) { case LZO_BLOCK: return new LzoProtobufBlockRecordReader(typeRef); case LZO_B64LINE: return new LzoProtobufBlockRecordReader(typeRef); } } throw new IOException( "could not determine reader for " + ((FileSplit)split).getPath() + " with class " + recordClass.getName()); }
Source:
void initializeShallowCommits() throws IOException { if (shallowCommitsInitialized) throw new IllegalStateException(JGitText.get().outputHasAlreadyBeenStarted); shallowCommitsInitialized = true; if (reader == null) return; for (ObjectId id : reader.getShallowCommits()) lookupCommit(id).parents = RevCommit.NO_PARENTS; }

Target:
void initializeShallowCommits() throws IOException { if (shallowCommitsInitialized) throw new IllegalStateException( JGitText.get().shallowCommitsAlreadyInitialized); shallowCommitsInitialized = true; if (reader == null) return; for (ObjectId id : reader.getShallowCommits()) lookupCommit(id).parents = RevCommit.NO_PARENTS; }
Source:
public void stop() { observers.clear(); try { send("quit"); } catch (NodeJsDebuggerException e) { LOG.warn(e.getMessage()); } executor.shutdown(); try { if (!executor.awaitTermination(10, TimeUnit.SECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(10, TimeUnit.SECONDS)) { LOG.warn("Unable to terminate main pool."); } } } catch (InterruptedException e) { if (!executor.isShutdown()) { LOG.warn("Unable to terminate main pool."); } } process.destroy(); try { if (!process.waitFor(10, TimeUnit.SECONDS)) { LOG.error("Unable to terminate NodeJs."); } } catch (InterruptedException e) { if (!process.isAlive()) { LOG.error("Unable to terminate NodeJs."); } } try { processWriter.close(); } catch (IOException e) { LOG.warn("Failed to close NodeJs process output stream", e); } }

Target:
public void stop() { boolean interrupted = false; observers.clear(); try { send("quit"); } catch (NodeJsDebuggerException e) { LOG.warn("Failed to execute 'quit' command. " + e.getMessage()); } try { processWriter.close(); } catch (IOException ignored) { } executor.shutdown(); try { if (!executor.awaitTermination(10, TimeUnit.SECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(10, TimeUnit.SECONDS)) { LOG.error("Unable to terminate pool of NodeJs debugger tasks."); } } } catch (InterruptedException e) { interrupted = true; if (!executor.isShutdown()) { LOG.error("Unable to terminate pool of NodeJs debugger tasks."); } } process.destroy(); try { if (!process.waitFor(10, TimeUnit.SECONDS)) { LOG.error("Unable to terminate NodeJs process."); } } catch (InterruptedException e) { interrupted = true; if (!process.isAlive()) { LOG.error("Unable to terminate NodeJs process."); } } if (interrupted) { Thread.currentThread().interrupt(); } }
Source:
public void testGetInvalidityInfoForEmailContent_null_throwException() { AdminEmailAttributes adminEmailAttributes = new AdminEmailAttributes( subject, addressReceiverListString, groupReceiverListFileKey, null, date); String errorMessage = "Did not throw the expected AssertionError for null Email Content"; try { fieldValidator.getInvalidityInfoForEmailContent(adminEmailAttributes.content); signalFailureToDetectException(errorMessage); } catch (AssertionError e) { ignoreExpectedException(); } }

Target:
public void testGetInvalidityInfoForEmailContent_null_throwException() { AdminEmailAttributes adminEmailAttributes = new AdminEmailAttributes( subject, addressReceiverListString, groupReceiverListFileKey, null, date); try { fieldValidator.getInvalidityInfoForEmailContent(adminEmailAttributes.content); signalFailureToDetectException("Did not throw the expected AssertionError for null Email Content"); } catch (AssertionError e) { ignoreExpectedException(); } }
Source:
public static OperatorSymbol parse(String string) { Operator operator = Convert.stringToOperator(string); if(operator != null) return new OperatorSymbol(operator); else throw new RuntimeException(MessageFormat.format( "Cannot parse {0} into an OperatorSymbol", string)); }

Target:
public static OperatorSymbol parse(String string) { Operator operator = Convert.stringToOperator(string); if(operator != null) { return new OperatorSymbol(operator); } else { throw new RuntimeException(MessageFormat.format( "Cannot parse {0} into an OperatorSymbol", string)); } }
Source:
public ProjectileSource getShooter() { if (this.projectileSource != null && this.projectileSource instanceof ProjectileSource) { return (ProjectileSource) this.projectileSource; } else if (this.getThrower() != null && this.getThrower() instanceof ProjectileSource) { return (ProjectileSource) this.getThrower(); } return new UnknownProjectileSource(); }

Target:
public ProjectileSource getShooter() { if (this.projectileSource != null) { return this.projectileSource; } else if (this.getThrower() != null && this.getThrower() instanceof ProjectileSource) { return (ProjectileSource) this.getThrower(); } return new UnknownProjectileSource(); }
Source:
public long getStartTime(String partitionName) { return _record.getLongField(CustomizedStateProperty.START_TIME.name(), NON_EXIST); }

Target:
public long getStartTime(String partitionName) { String startTime = getProperty(partitionName, CustomizedStateProperty.START_TIME); return startTime == null ? -1L : Long.parseLong(startTime); }
Source:
protected void removeVmNetwork() { if (getInterfaces() != null) { final MacPoolManagerStrategy macPool = getMacPoolForVm(); for (VmNic iface : getInterfaces()) { macPool.freeMac(iface.getMacAddress()); } } }

Target:
protected void removeVmNetwork() { if (getInterfaces() != null) { for (VmNic iface : getInterfaces()) { getMacPool().freeMac(iface.getMacAddress()); } } }
Source:
public UriUploaderResultCode uploadUris() { try { List<Uri> contentUris = new ArrayList<>(); List<String> contentRemotePaths = new ArrayList<>(); int schemeFileCounter = 0; for (Parcelable sourceStream : mUrisToUpload) { Uri sourceUri = (Uri) sourceStream; if (sourceUri != null) { String displayName = UriUtils.getDisplayNameForUri(sourceUri, mActivity); if (displayName == null) { displayName = generateDiplayName(); } String remotePath = mUploadPath + displayName; if (ContentResolver.SCHEME_CONTENT.equals(sourceUri.getScheme())) { contentUris.add(sourceUri); contentRemotePaths.add(remotePath); } else if (ContentResolver.SCHEME_FILE.equals(sourceUri.getScheme())) { requestUpload(sourceUri.getPath(), remotePath); schemeFileCounter++; } } } if (!contentUris.isEmpty()) { copyThenUpload(contentUris.toArray(new Uri[contentUris.size()]), contentRemotePaths.toArray(new String[contentRemotePaths.size()])); } else if (schemeFileCounter == 0) { mCode = UriUploaderResultCode.ERROR_NO_FILE_TO_UPLOAD; } } catch (SecurityException e) { mCode = UriUploaderResultCode.ERROR_READ_PERMISSION_NOT_GRANTED; Log_OC.e(TAG, "Permissions fail", e); } catch (Exception e) { mCode = UriUploaderResultCode.ERROR_UNKNOWN; Log_OC.e(TAG, "Unexpted error", e); } finally { PreferenceManager.setLastUploadPath(mUploadPath, mActivity); } return mCode; }

Target:
public UriUploaderResultCode uploadUris() { try { List<Uri> contentUris = new ArrayList<>(); List<String> contentRemotePaths = new ArrayList<>(); int schemeFileCounter = 0; for (Parcelable sourceStream : mUrisToUpload) { Uri sourceUri = (Uri) sourceStream; if (sourceUri != null) { String displayName = UriUtils.getDisplayNameForUri(sourceUri, mActivity); if (displayName == null) { displayName = generateDiplayName(); } String remotePath = mUploadPath + displayName; if (ContentResolver.SCHEME_CONTENT.equals(sourceUri.getScheme())) { contentUris.add(sourceUri); contentRemotePaths.add(remotePath); } else if (ContentResolver.SCHEME_FILE.equals(sourceUri.getScheme())) { requestUpload(sourceUri.getPath(), remotePath); schemeFileCounter++; } } } if (!contentUris.isEmpty()) { copyThenUpload(contentUris.toArray(new Uri[contentUris.size()]), contentRemotePaths.toArray(new String[contentRemotePaths.size()])); } else if (schemeFileCounter == 0) { mCode = UriUploaderResultCode.ERROR_NO_FILE_TO_UPLOAD; } } catch (SecurityException e) { mCode = UriUploaderResultCode.ERROR_READ_PERMISSION_NOT_GRANTED; Log_OC.e(TAG, "Permissions fail", e); } catch (Exception e) { mCode = UriUploaderResultCode.ERROR_UNKNOWN; Log_OC.e(TAG, "Unexpected error", e); } return mCode; }
Source:
public synchronized void pollAllSources() { try { final Set<Source> sources = Stream.of(connectedSources, federatedSources, catalogProviders, catalogStores) .flatMap(Collection::stream) .collect(Collectors.toSet()); LOGGER.trace("Found sources", sources.size()); final Map<SourceKey, Source> sourceKeyMap = sources .stream() .collect( Collectors.toMap( SourceKey::new, source -> source, (source, anotherSourceWithTheSameSourceKey) -> { LOGGER.warn( "Found different sources with the same SourceKey with id={}. This means that the SourcePoller might not report accurate availability for these sources in the CatalogFramework. Confirm that every source has a unique id, and try restarting.", source.getId()); return source; })); final Set<SourceKey> currentSourceKeys = sourceKeyMap.keySet(); final Set<SourceKey> sourceKeysInTheCache = cache.asMap().keySet(); final Set<SourceKey> sourceKeysToRemove = new HashSet<>(sourceKeysInTheCache); sourceKeysToRemove.removeAll(currentSourceKeys); if (CollectionUtils.isNotEmpty(sourceKeysToRemove)) { LOGGER.debug( "Found SourceKeys to remove from the cache. This is caused by when sources are destroyed or modified in a way that their SourceKey changes. Removing these from the cache now", sourceKeysToRemove.size()); sourceKeysToRemove.forEach(cache::invalidate); } Map<SourceKey, Future<SourceAvailability>> availabilityFutures = startAvailabilityChecks(sourceKeyMap); CacheResults(availabilityFutures); } catch (Throwable throwable) { LOGGER.warn("Scheduled polling of sources failed", throwable); } }

Target:
public void pollAllSources() { try { final List<Source> sources = Stream.of(connectedSources, federatedSources, catalogProviders, catalogStores) .flatMap(Collection::stream) .collect(Collectors.toList()); LOGGER.trace("Found sources", sources.size()); final Map<SourceKey, Source> sourceKeyMap = sources .stream() .collect( Collectors.toMap( SourceKey::new, source -> source, (source, anotherSourceWithTheSameSourceKey) -> { LOGGER.warn( "Found different sources with the same SourceKey with id={}. This means that the SourcePoller might not report accurate availability for these sources in the CatalogFramework. Confirm that every source has a unique id, and try restarting.", source.getId()); return source; })); removeExtraneousSourcesFromCache(sourceKeyMap); addMissingSourcesToCache(sourceKeyMap); Map<SourceKey, Future<SourceStatus>> sourceStatusFutures = startAvailabilityChecks(sourceKeyMap); cacheResults(sourceStatusFutures); } catch (VirtualMachineError e) { throw e; } catch (Throwable throwable) { LOGGER.warn("Scheduled polling of sources failed", throwable); } }
Source:
private static String uniqueName(final Collection<String> names, final String n) { if (!names.contains(n)) { return n; } int c = 0; while (names.contains(n + "[" + c + "]")) { c++; } return n + "[" + c + "]"; }

Target:
protected static String uniqueName(final Collection<String> names, final String n) { if (!names.contains(n)) { return n; } int c = 0; while (names.contains(n + "[" + c + "]")) { c++; } return n + "[" + c + "]"; }
Source:
protected boolean amendDiskRequested() { if (getNewDisk().getDiskStorageType() == DiskStorageType.IMAGE) { QcowCompat qcowCompat = ((DiskImage) getNewDisk()).getQcowCompat(); DiskImage unmatchedQcowCompatDisk = getDiskImages(getOldDisk().getId()).stream() .filter(disk -> disk.isQcowFormat() && disk.getQcowCompat() == qcowCompat) .findFirst() .get(); return unmatchedQcowCompatDisk != null; } return false; }

Target:
protected boolean amendDiskRequested() { if (getNewDisk().getDiskStorageType() == DiskStorageType.IMAGE) { QcowCompat qcowCompat = ((DiskImage) getNewDisk()).getQcowCompat(); return getDiskImages(getOldDisk().getId()).stream().anyMatch(disk -> disk.isQcowFormat() && disk.getQcowCompat() != qcowCompat); } return false; }
Source:
void resetPlot(boolean forceReset, boolean newPlot) { boolean fixed = getPlotPreferences().getFixed(); setupForPlotDisplayChange(newPlot); setupPlotComponents(); if (fixed && !forceReset) { PlaneAspect existingAspect = getPlotPreferences().getAspect(); if ((getPlotPreferences().getXlog() && existingAspect.getXMin() > 0) && (getPlotPreferences().getYlog() && existingAspect.getYMin() > 0)) { display.setAspect(existingAspect); } } addPlotToDisplay(); validateModelFunctions(); }

Target:
void resetPlot(boolean forceReset, boolean newPlot) { boolean fixed = getPlotPreferences().getFixed(); setupForPlotDisplayChange(newPlot); setupPlotComponents(); if (fixed && !forceReset) { PlaneAspect existingAspect = getPlotPreferences().getAspect(); if ((getPlotPreferences().getXlog() && existingAspect.getXMin() <= 0) || (getPlotPreferences().getYlog() && existingAspect.getYMin() <= 0)) { } else { display.setAspect(existingAspect); } } addPlotToDisplay(); validateModelFunctions(); }
Source:
public void handle(Concept concept, User creator, Date dateCreated, String other) { if (concept.getNames() != null) { for (ConceptName cn : concept.getNames()) { cn.setConcept(concept); } } if (concept.getConceptSets() != null) { for (ConceptSet set : concept.getConceptSets()) { set.setConceptSet(concept); } } if (concept.getAnswers(true) != null) { for (ConceptAnswer ca : concept.getAnswers(true)) { ca.setConcept(concept); } } if (concept.getDescriptions() != null) { for (ConceptDescription cd : concept.getDescriptions()) { if(cd.getLocale()==null) cd.setLocale(Context.getLocale()); if(StringUtils.isEmpty(cd.getDescription())) concept.removeDescription(cd); cd.setConcept(concept); } } if (concept.getConceptMappings() != null) { for (ConceptMap map : concept.getConceptMappings()) { map.setConcept(concept); } } }

Target:
public void handle(Concept concept, User creator, Date dateCreated, String other) { if (concept.getNames() != null) { for (ConceptName cn : concept.getNames()) { cn.setConcept(concept); } } if (concept.getConceptSets() != null) { for (ConceptSet set : concept.getConceptSets()) { set.setConceptSet(concept); } } if (concept.getAnswers(true) != null) { for (ConceptAnswer ca : concept.getAnswers(true)) { ca.setConcept(concept); } } if (concept.getDescriptions() != null) { for (ConceptDescription cd : concept.getDescriptions()) { if(cd.getLocale()==null){ cd.setLocale(Context.getLocale()); } if(StringUtils.isBlank(cd.getDescription())){ concept.removeDescription(cd); } cd.setConcept(concept); } } if (concept.getConceptMappings() != null) { for (ConceptMap map : concept.getConceptMappings()) { map.setConcept(concept); } } }
Source:
private String combineAttributes(String patientAttributeProperty, String userAttributeProperty, PERSON_TYPE personType) { StringBuilder result = new StringBuilder(); if (personType == null || personType == PERSON_TYPE.PERSON) { result.append(patientAttributeProperty).append(",").append(userAttributeProperty); } else if (personType == PERSON_TYPE.PATIENT) { result.append(patientAttributeProperty); } else if (personType == PERSON_TYPE.USER) { result.append(userAttributeProperty); } else { log.error(MarkerFactory.getMarker("FATAL"), "Should not be here."); } return result.toString(); }

Target:
private String combineAttributes(String patientAttributeProperty, String userAttributeProperty, PERSON_TYPE personType) { final StringBuilder result = new StringBuilder(); if (personType == null || personType == PERSON_TYPE.PERSON) { result.append(patientAttributeProperty).append(",").append(userAttributeProperty); } else if (personType == PERSON_TYPE.PATIENT) { result.append(patientAttributeProperty); } else if (personType == PERSON_TYPE.USER) { result.append(userAttributeProperty); } else { log.error(MarkerFactory.getMarker("FATAL"), "Should not be here."); } return result.toString(); }
Source:
public void testIssue244() throws Exception { class P1 class P2 { @Parameter(names = "--hello") private int test; } P1 p1 = new P1(); P2 p2 = new P2(); JCommander j = new JCommander(p1); j.addCommand("wonderful", p2); j.setAllowAbbreviatedOptions(true); j.parse("wond", "--he", "47"); System.out.printf("command %s, test %d\n", j.getParsedCommand(), p2.test); }

Target:
public void testIssue244() throws Exception { class P1 class P2 { @Parameter(names = "--hello") private int test; } P1 p1 = new P1(); P2 p2 = new P2(); JCommander j = new JCommander(p1); j.addCommand("wonderful", p2); j.setAllowAbbreviatedOptions(true); j.parse("wond", "--he", "47"); Assert.assertEquals("wonderful", j.getParsedCommand()); Assert.assertEquals(47, p2.test); }
Source:
static void addControls(EClass rootClass, VElement compositeToFill, Set<EStructuralFeature> features, boolean segmentTooling) { if (!VContainer.class.isInstance(compositeToFill) && !VView.class.isInstance(compositeToFill)) { return; } final Map<EClass, EReference> childParentReferenceMap = new HashMap<EClass, EReference>(); Helper.getReferenceMap(rootClass, childParentReferenceMap); for (final EStructuralFeature feature : features) { final VControl control = VViewFactory.eINSTANCE.createControl(); control.setName("Control " + feature.getName()); control.setReadonly(false); final List<EReference> bottomUpPath = Helper.getReferencePath(rootClass, feature.getEContainingClass(), childParentReferenceMap); final VDomainModelReference modelReference = createDmr(feature, bottomUpPath, segmentTooling); control.setDomainModelReference(modelReference); if (VContainer.class.isInstance(compositeToFill)) { ((VContainer) compositeToFill).getChildren().add(control); } else if (VView.class.isInstance(compositeToFill)) { ((VView) compositeToFill).getChildren().add(control); } } }

Target:
static void addControls(EClass rootClass, VElement compositeToFill, Set<EStructuralFeature> features, boolean segmentTooling) { if (!VContainer.class.isInstance(compositeToFill) && !VView.class.isInstance(compositeToFill)) { return; } final Map<EClass, EReference> childParentReferenceMap = new HashMap<EClass, EReference>(); Helper.getReferenceMap(rootClass, childParentReferenceMap); for (final EStructuralFeature feature : features) { final VControl control = VViewFactory.eINSTANCE.createControl(); control.setName("Control " + feature.getName()); control.setReadonly(false); final List<EReference> bottomUpPath = Helper.getReferencePath(rootClass, feature.getEContainingClass(), childParentReferenceMap); final VDomainModelReference modelReference = segmentTooling ? createSegmentDmr(feature, bottomUpPath) : createLegacyDmr(feature, bottomUpPath); control.setDomainModelReference(modelReference); if (VContainer.class.isInstance(compositeToFill)) { ((VContainer) compositeToFill).getChildren().add(control); } else if (VView.class.isInstance(compositeToFill)) { ((VView) compositeToFill).getChildren().add(control); } } }