auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> private List getSubjectNotifications(Subject subject) { <END> String userid = subjectIdentity.getUniqueIdentifier(subject); try { String filter = String.format("user = '%s'", userid); List<Map<String, Object>> notificationsList = persistentStore.get(PersistenceType.NOTIFICATION_TYPE.toString(), filter, 0, 999); return notificationsList.stream().map(this::mapAttributes).collect(Collectors.toList()); } catch (PersistenceException e) { LOGGER.info( "PersistenceException while trying to retrieve persisted notifications for user {}", userid, e); } return Collections.emptyList(); }</code><technical_language>List of what? List<Map<String, Object>>? List<Object>? List<?></technical_language>

Target:
private List<Map<String, Object>> getSubjectNotifications(Subject subject) { String userid = subjectIdentity.getUniqueIdentifier(subject); try { String filter = String.format("user = '%s'", userid); List<Map<String, Object>> notificationsList = persistentStore.get( PersistenceType.NOTIFICATION_TYPE.toString(), filter, 0, MAX_PAGE_SIZE); return notificationsList.stream().map(this::mapAttributes).collect(Collectors.toList()); } catch (PersistenceException e) { LOGGER.debug( "PersistenceException while trying to retrieve persisted notifications for user {}", userid, e); } return Collections.emptyList(); }
Source:
<code>private TypeDTO(Builder builder) { if (builder.id != null) { if (builder.id.matches("^[a-zA-Z0-9]+$")) { this.id = builder.id; } else { LOGGER.warn( <START> String.format("Category ID (%s) contains invalid characters, will remove them.", builder.id)); <END> this.id = builder.id.replaceAll("[^a-zA-Z0-9]", ""); } } else { this.id = null; } this.name = builder.name == null ? builder.id : builder.name; this.categories = Collections.unmodifiableList(builder.categories); this.icon = builder.icon; }</code><technical_language>I Type ID right</technical_language>

Target:
private TypeDTO(Builder builder) { if (builder.id != null) { if (builder.id.matches("^[a-zA-Z0-9]+$")) { this.id = builder.id; } else { LOGGER.warn( String.format("Type ID (%s) contains invalid characters, will remove them.", builder.id)); this.id = builder.id.replaceAll("[^a-zA-Z0-9]", ""); } } else { this.id = null; } this.name = builder.name == null ? builder.id : builder.name; this.categories = Collections.unmodifiableList(builder.categories); this.icon = builder.icon; }
Source:
<code>public void setupRoutes() { path(controllerBasePath(), () -> { <START> before(Routes.PipelineConfig.NAME + "/edit", authenticationHelper::checkAdminUserAnd403); <END> get(Routes.PipelineConfig.NAME + "/edit", this::index, engine); }); }</code><technical_language>apiAuthenticationHelper::checkPipelineGroupAdminOfPipelineOrGroupInURLUserAnd403</technical_language>

Target:
public void setupRoutes() { path(controllerBasePath(), () -> { before(Routes.PipelineConfig.NAME + "/edit", authenticationHelper::checkPipelineGroupAdminOfPipelineOrGroupInURLUserAnd403); get(Routes.PipelineConfig.NAME + "/edit", this::index, engine); }); }
Source:
<code>protected void checkWithWaitStrategy(CoreEvent event) throws FlowBackPressureException { boolean accepted = false; while (!accepted) { try { abstractPipeline.getProcessingStrategy().checkBackpressureAccepting(event); accepted = true; } catch (RejectedExecutionException ree) { try { <START> Thread.sleep(EVENT_LOOP_SCHEDULER_BUSY_RETRY_INTERVAL_MS); <END> } catch (InterruptedException e) { FlowBackPressureException exception = new FlowBackPressureException(abstractPipeline.getName(), ree); throw exception; } } } }</code><technical_language>static import</technical_language>

Target:
protected void checkWithWaitStrategy(CoreEvent event) throws FlowBackPressureException { boolean accepted = false; while (!accepted) { try { abstractPipeline.getProcessingStrategy().checkBackpressureAccepting(event); accepted = true; } catch (RejectedExecutionException ree) { try { sleep(EVENT_LOOP_SCHEDULER_BUSY_RETRY_INTERVAL_MS); } catch (InterruptedException e) { currentThread().interrupt(); throw new FlowBackPressureException(abstractPipeline.getName(), ree); } } } }
Source:
<code>public List<Symbol> outputs() { <START> return List.copyOf(outputs); <END> }</code><technical_language>is this required? AnalyzedView</technical_language>

Target:
public List<Symbol> outputs() { return outputs; }
Source:
<code>Request toRequest() { return new RequestTemplate() .method(request.method()) <START> .appendDirectly(getUri().toASCIIString()) <END> .headers(request.headers()) .body(request.body(), request.charset()) .request(); }</code><technical_language>wait.. this easier making a request</technical_language>

Target:
Request toRequest() { final byte[] body = request.body(); final int bodyLength = body != null ? body.length : 0; Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>(); headers.putAll(request.headers()); headers.put(Util.CONTENT_LENGTH, Arrays.asList(String.valueOf(bodyLength))); return Request.create(request.method(), getUri().toASCIIString(), headers, body, request.charset()); }
Source:
<code>private void setItemToCache(final AuthenticationRequest request, AuthenticationResult result, boolean afterPrompt) throws AuthenticationException { if (mTokenCacheStore != null) { Logger.v(TAG, "Setting item to cache" + getCorrelationLogInfo()); logReturnedToken(request, result); if (afterPrompt) { if (result.getUserInfo() != null && !StringExtensions.IsNullOrBlank(result.getUserInfo().getDisplayableId())) { Logger.v(TAG, "Updating cache for username:" + result.getUserInfo().getDisplayableId() + getCorrelationLogInfo()); setItemToCacheForUser(request, result, result.getUserInfo().getDisplayableId()); } } else { String userKey = request.getUserId(); if (StringExtensions.IsNullOrBlank(userKey)) { userKey = request.getLoginHint(); } setItemToCacheForUser(request, result, userKey); } <START> <END> if (result.getUserInfo() != null && !StringExtensions.IsNullOrBlank(result.getUserInfo().getUserId())) { Logger.v(TAG, "Updating userId:" + result.getUserInfo().getUserId() + getCorrelationLogInfo()); setItemToCacheForUser(request, result, result.getUserInfo().getUserId()); } } }</code><technical_language>if id token is empty</technical_language>

Target:
private void setItemToCache(final AuthenticationRequest request, AuthenticationResult result, boolean afterPrompt) throws AuthenticationException { if (mTokenCacheStore != null) { Logger.v(TAG, "Setting item to cache" + getCorrelationLogInfo()); logReturnedToken(request, result); String userKey = request.getUserId(); if (afterPrompt) { if (result.getUserInfo() != null && !StringExtensions.IsNullOrBlank(result.getUserInfo().getDisplayableId())) { Logger.v(TAG, "Updating cache for username:" + result.getUserInfo().getDisplayableId() + getCorrelationLogInfo()); userKey = result.getUserInfo().getDisplayableId(); } } else if (StringExtensions.IsNullOrBlank(userKey)) { userKey = request.getLoginHint(); } setItemToCacheForUser(request, result, userKey); if (result.getUserInfo() != null && !StringExtensions.IsNullOrBlank(result.getUserInfo().getUserId())) { Logger.v(TAG, "Updating userId:" + result.getUserInfo().getUserId() + getCorrelationLogInfo()); setItemToCacheForUser(request, result, result.getUserInfo().getUserId()); } } }
Source:
<code>private void flushRedo(IUndoContext context) { if (DEBUG_OPERATION_HISTORY_DISPOSE) { Tracing.printTrace("OPERATIONHISTORY", "Flushing redo history for " + context); } synchronized (undoRedoHistoryLock) { Object[] filtered = filter(redoList, context); for (Object element : filtered) { IUndoableOperation operation = (IUndoableOperation) element; if (context == GLOBAL_UNDO_CONTEXT || operation.getContexts().length == 1) { redoList.remove(operation); internalRemove(operation); } else { IUndoContext[] contexts = operation.getContexts(); for (IUndoContext <START> context2 : <END> contexts) { if (context2.matches(context)) { operation.removeContext(context2); } } if (operation.getContexts().length == 0) { redoList.remove(operation); internalRemove(operation); } } } } }</code><technical_language>rename 'otherContext' 'assignedContext'</technical_language>

Target:
private void flushRedo(IUndoContext context) { if (DEBUG_OPERATION_HISTORY_DISPOSE) { Tracing.printTrace("OPERATIONHISTORY", "Flushing redo history for " + context); } synchronized (undoRedoHistoryLock) { Object[] filtered = filter(redoList, context); for (Object element : filtered) { IUndoableOperation operation = (IUndoableOperation) element; if (context == GLOBAL_UNDO_CONTEXT || operation.getContexts().length == 1) { redoList.remove(operation); internalRemove(operation); } else { for (IUndoContext undoContext : operation.getContexts()) { if (undoContext.matches(context)) { operation.removeContext(undoContext); } } if (operation.getContexts().length == 0) { redoList.remove(operation); internalRemove(operation); } } } } }
Source:
<code>private void addRoundResetStep(final List<IExecutable> steps) { final IExecutable loop = new IExecutable() { private static final long serialVersionUID = 3118458517320468680L; @Override public void execute(final ExecutionStack stack, final IDelegateBridge bridge) { pushFightLoopOnStack(); } }; steps.add( new IExecutable() { private static final long serialVersionUID = -3993599528368570254L; @Override public void execute(final ExecutionStack stack, final IDelegateBridge bridge) { if (!isOver) { round++; if (round > MAX_INFINITE_ROUNDS) { throw new IllegalStateException( <START> "Round 10,000 reached in a battle. Something must be wrong." <END> + " Attacking unit types: " + attackingUnits.stream() .map(Unit::getType) .collect(Collectors.toSet()) .stream() .map(UnitType::getName) .collect(Collectors.joining(",")) + ", Defending unit types: " + defendingUnits.stream() .map(Unit::getType) .collect(Collectors.toSet()) .stream() .map(UnitType::getName) .collect(Collectors.joining(","))); } updateOffensiveAaUnits(); updateDefendingAaUnits(); stepStrings = determineStepStrings(); final IDisplay display = bridge.getDisplayChannelBroadcaster(); display.listBattleSteps(battleId, stepStrings); if (!MustFightBattle.this.stack.isEmpty()) { throw new IllegalStateException("Stack not empty:" + MustFightBattle.this.stack); } MustFightBattle.this.stack.push(loop); } } }); }</code><technical_language>do of adding message "Please report this TripleA"? A line break this line unit listing easier message read well</technical_language>

Target:
private void addRoundResetStep(final List<IExecutable> steps) { final IExecutable loop = new IExecutable() { private static final long serialVersionUID = 3118458517320468680L; @Override public void execute(final ExecutionStack stack, final IDelegateBridge bridge) { pushFightLoopOnStack(); } }; steps.add( new IExecutable() { private static final long serialVersionUID = -3993599528368570254L; @Override public void execute(final ExecutionStack stack, final IDelegateBridge bridge) { if (!isOver) { round++; if (round > MAX_ROUNDS) { throw new IllegalStateException( "Round 10,000 reached in a battle. Something must be wrong." + " Please report this to TripleA.\n" + " Attacking unit types: " + attackingUnits.stream() .map(Unit::getType) .collect(Collectors.toSet()) .stream() .map(UnitType::getName) .collect(Collectors.joining(",")) + ", Defending unit types: " + defendingUnits.stream() .map(Unit::getType) .collect(Collectors.toSet()) .stream() .map(UnitType::getName) .collect(Collectors.joining(","))); } updateOffensiveAaUnits(); updateDefendingAaUnits(); stepStrings = determineStepStrings(); final IDisplay display = bridge.getDisplayChannelBroadcaster(); display.listBattleSteps(battleId, stepStrings); if (!MustFightBattle.this.stack.isEmpty()) { throw new IllegalStateException("Stack not empty:" + MustFightBattle.this.stack); } MustFightBattle.this.stack.push(loop); } } }); }
Source:
<code>public int getStreamIndex() { <START> return streamIndex; <END> }</code><technical_language>this private</technical_language>

Target:
private int getStreamIndex() { return streamIndex; }
Source:
<code>public void close() { <START> if (context != null) { <END> try { context.dispose(); } catch (GSSException e) { throw new AuthenticationException(e); } } }</code><technical_language>This check is unnecessary. context null for a properly constructed object</technical_language>

Target:
public void close() { try { try { context.dispose(); } finally { loginContext.logout(); } } catch (GSSException | LoginException e) { throw new AuthenticationException(e); } }
Source:
<code>public void setCapabilities(@NetCapability int[] capabilities) { mNetworkCapabilities = BitUtils.packBits(capabilities); <START> mUnwantedNetworkCapabilities &= ~(mNetworkCapabilities & mUnwantedNetworkCapabilities); <END> }</code><technical_language>double & ? want mUnwantedNetworkCapabilities &= ~mNetworkCapabilities ? I mean, A & ~(B & A) = A & (~B | ~A) = (A & ~B) | (A & ~A) = A & ~B ...or I missing</technical_language>

Target:
public void setCapabilities(@NetCapability int[] capabilities) { mNetworkCapabilities = BitUtils.packBits(capabilities); mUnwantedNetworkCapabilities &= ~mNetworkCapabilities; }
Source:
<code>protected Backup snapshotTable(String snapshotId, TableName tableName) throws IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(snapshotId)); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableName.getNameAsString())); CreateBackupRequest request = CreateBackupRequest.of(getBackupClusterName().getClusterId(), snapshotId) .setSourceTableId(tableName.getNameAsString()); int ttlSecs = configuration.getInt( BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY, BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_VALUE); <START> if (ttlSecs > 0) { <END> Instant expireTime = Instant.now().plus(ttlSecs, ChronoUnit.SECONDS); request.setExpireTime(expireTime); } return Futures.getChecked( tableAdminClientWrapper.createBackupAsync(request), IOException.class); }</code><technical_language>ttlSecs < 0</technical_language>

Target:
protected Backup snapshotTable(String snapshotId, TableName tableName) throws IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(snapshotId)); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableName.getNameAsString())); CreateBackupRequest request = CreateBackupRequest.of(getBackupClusterName().getClusterId(), snapshotId) .setSourceTableId(tableName.getNameAsString()); int ttlSecs = configuration.getInt( BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY, BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_VALUE); if (ttlSecs <= 0) { throw new IllegalArgumentException( BigtableOptionsFactory.BIGTABLE_SNAPSHOT_DEFAULT_TTL_SECS_KEY + " must be > 0"); } Instant expireTime = Instant.now().plus(ttlSecs, ChronoUnit.SECONDS); request.setExpireTime(expireTime); return Futures.getChecked( tableAdminClientWrapper.createBackupAsync(request), IOException.class); }
Source:
<code>void testWithCsvSource(String first, int second) { <START> assertNotNull(Objects.toString(first, "<null>")); <END> assertNotEquals(0, second); }</code><technical_language>missing something, Objects.toString(first, "<null>") return null. So, intending assert else</technical_language>

Target:
void testWithCsvSource(String first, int second) { assertNotNull(first); assertNotEquals(0, second); }
Source:
<code>public SubTabHostInterfacePresenter(EventBus eventBus, ViewDef view, ProxyDef proxy, PlaceManager placeManager, HostMainSelectedItems selectedItems, HostInterfaceActionPanelPresenterWidget actionPanel, ExpandAllButtonPresenterWidget expandAll, SearchableDetailModelProvider<HostInterfaceLineModel, HostListModel<Void>, HostInterfaceListModel> modelProvider) { super(eventBus, view, proxy, placeManager, modelProvider, selectedItems, actionPanel, HostSubTabPanelPresenter.TYPE_SetTabContent); expandAll.setTarget(this); actionPanel.addSearchPanel(expandAll); actionPanel.addSearchPanel(new ToggleActionButtonView(constants.showVfLabel(), constants.hideVfLabel()) { <START> @Override <END> public void handleOnClick(ClickEvent event, boolean isDefault) { getModelProvider().getModel().onShowHideVirtualFunction(isDefault); } }); }</code><technical_language>> shrink this</technical_language>

Target:
public SubTabHostInterfacePresenter(EventBus eventBus, ViewDef view, ProxyDef proxy, PlaceManager placeManager, HostMainSelectedItems selectedItems, HostInterfaceActionPanelPresenterWidget actionPanel, ExpandAllButtonPresenterWidget expandAll, SearchableDetailModelProvider<HostInterfaceLineModel, HostListModel<Void>, HostInterfaceListModel> modelProvider) { super(eventBus, view, proxy, placeManager, modelProvider, selectedItems, actionPanel, HostSubTabPanelPresenter.TYPE_SetTabContent); expandAll.setTarget(this); actionPanel.addSearchPanel(expandAll); actionPanel.addSearchPanel(ToggleActionButtonView.of(constants.showVfLabel(), constants.hideVfLabel(), (event, isHidden) -> getModelProvider().getModel().onShowHideVirtualFunction(!isHidden))); }
Source:
<code>boolean verify() throws Exception { <START> byte[] data = UUID.randomUUID().toString().getBytes(); <END> byte[] digitalSignature = signData(data); return verifySig(data, digitalSignature); }</code><technical_language>Another getBytes(StandardCharsets.UTF_8) opportunity</technical_language>

Target:
boolean verify() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { byte[] data = new byte[16]; SecureRandom.getInstanceStrong().nextBytes(data); byte[] digitalSignature = signData(data); Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM_NAME); signer.initVerify(publicKey); signer.update(data); return signer.verify(digitalSignature); }
Source:
<code><START> private String createContentString() { <END> return "distanceInfluence=" + distanceInfluence + ", speedFactor=" + speedFactorMap + ", maxSpeed=" + maxSpeedMap + ", maxSpeedFallback=" + maxSpeedFallback + ", priorityMap=" + priorityMap + ", areas=" + areas; }</code><technical_language>createContentString in getVersion() (instead of toString()) it</technical_language>

Target:
private String createContentString() { return "distanceInfluence=" + distanceInfluence + "|speedFactor=" + speedFactorMap + "|maxSpeed=" + maxSpeedMap + "|maxSpeedFallback=" + maxSpeedFallback + "|priorityMap=" + priorityMap + "|areas=" + areas; }
Source:
<code>public static void addHeaders(final HttpMessage httpMessage, final Header... headers) { Validate.notNull(httpMessage, "HttpMessage must not be null"); for (final Header header : headers) { <START> if (header.getName().equals(MantaHttpHeaders.REQUEST_ID)) { <END> continue; } httpMessage.addHeader(header); } }</code><technical_language>a paranoia sufferer, I invert equals avoid remote possibility of a NPE: java if (MantaHttpHeaders.REQUEST_ID.equals(header.getName())) {</technical_language>

Target:
public static void addHeaders(final HttpMessage httpMessage, final Header... headers) { Validate.notNull(httpMessage, "HttpMessage must not be null"); for (final Header header : headers) { if (MantaHttpHeaders.REQUEST_ID.equals(header.getName())) { continue; } httpMessage.addHeader(header); } }
Source:
<code>private Collection<EObject> getFeatureExtensionsData(final EObject associatedInstance, Collection<Resource> resources) { final Collection<EObject> datas = new ArrayList<>(); Collection<Resource> allResources = new HashSet<>(); allResources.addAll(resources); if (associatedInstance != null) { Resource associatedInstanceResource = associatedInstance.eResource(); if (associatedInstanceResource != null) { allResources.add(associatedInstanceResource); } } else { for (Resource resource : resources) { <START> if (resource instanceof AirdResource) { AirdResource aird = (AirdResource) resource; for (Resource res : aird.getResourceSet().getResources()) { if (res instanceof SiriusRepresentationXMIResourceImpl) { allResources.add(res); } } } allResources.addAll(session.getAllSessionResources()); <END> } } for (final Resource res : allResources) { for (final EObject object : res.getContents()) { if (object instanceof DFeatureExtension) { datas.add(object); } } } return datas; }</code><technical_language>resource.getResourceSet().getResources().stream().filter(res-> new ResourceQuery(res).isSrmResource()).collect(Collector.toList());</technical_language>

Target:
private Collection<EObject> getFeatureExtensionsData(final EObject associatedInstance, Collection<Resource> resources) { final Collection<EObject> datas = new ArrayList<>(); Collection<Resource> allResources = new HashSet<>(); allResources.addAll(resources); if (associatedInstance != null) { Resource associatedInstanceResource = associatedInstance.eResource(); if (associatedInstanceResource != null) { allResources.add(associatedInstanceResource); } } else { for (Resource resource : resources) { List<Resource> srms = resource.getResourceSet().getResources().stream().filter(res -> new ResourceQuery(res).isSrmResource()).collect(Collectors.toList()); allResources.addAll(srms); break; } allResources.addAll(session.getAllSessionResources()); } for (final Resource res : allResources) { for (final EObject object : res.getContents()) { if (object instanceof DFeatureExtension) { datas.add(object); } } } return datas; }
Source:
<code>private boolean isValidCwl(String content, Yaml yaml) { try { Map<String, Object> mapping = yaml.loadAs(content, Map.class); final Object cwlVersion = mapping.get("cwlVersion"); if (cwlVersion != null) { <START> final boolean equals = cwlVersion.toString().startsWith(CWLHandler.CWL_VERSION_PREFIX); <END> if (!equals) { LOG.error("detected invalid version: " + cwlVersion.toString()); } return equals; } } catch (ClassCastException | YAMLException e) { return false; } return false; }</code><technical_language>equals != startsWith</technical_language>

Target:
private boolean isValidCwl(String content, Yaml yaml) { try { Map<String, Object> mapping = yaml.loadAs(content, Map.class); final Object cwlVersion = mapping.get("cwlVersion"); if (cwlVersion != null) { final boolean startsWith = cwlVersion.toString().startsWith(CWLHandler.CWL_VERSION_PREFIX); if (!startsWith) { LOG.error("detected invalid version: " + cwlVersion.toString()); } return startsWith; } } catch (ClassCastException | YAMLException e) { return false; } return false; }
Source:
<code>private RevCommit tryFastForward(String headName, RevCommit oldCommit, <START> RevCommit newCommit) throws IOException, JGitInternalException, <END> GitAPIException { boolean tryRebase = false; for (RevCommit parentCommit : newCommit.getParents()) if (parentCommit.equals(oldCommit)) tryRebase = true; if (!tryRebase) return null; CheckoutCommand co = new CheckoutCommand(repo); try { co.setName(newCommit.name()).call(); if (headName.startsWith(Constants.R_HEADS)) { RefUpdate rup = repo.updateRef(headName); rup.setExpectedOldObjectId(oldCommit); rup.setNewObjectId(newCommit); rup.setRefLogMessage("Fast-foward from " + oldCommit.name() + " to " + newCommit.name(), false); Result res = rup.update(walk); switch (res) { case FAST_FORWARD: case NO_CHANGE: case FORCED: break; default: throw new IOException("Could not fast-forward"); } } return newCommit; } catch (RefAlreadyExistsException e) { throw new JGitInternalException(e.getMessage(), e); } catch (RefNotFoundException e) { throw new JGitInternalException(e.getMessage(), e); } catch (InvalidRefNameException e) { throw new JGitInternalException(e.getMessage(), e); } catch (CheckoutConflictException e) { throw new JGitInternalException(e.getMessage(), e); } }</code><technical_language>declare JGitInternalException</technical_language>

Target:
private RevCommit tryFastForward(String headName, RevCommit oldCommit, RevCommit newCommit) throws IOException, GitAPIException { boolean tryRebase = false; for (RevCommit parentCommit : newCommit.getParents()) if (parentCommit.equals(oldCommit)) tryRebase = true; if (!tryRebase) return null; CheckoutCommand co = new CheckoutCommand(repo); try { co.setName(newCommit.name()).call(); if (headName.startsWith(Constants.R_HEADS)) { RefUpdate rup = repo.updateRef(headName); rup.setExpectedOldObjectId(oldCommit); rup.setNewObjectId(newCommit); rup.setRefLogMessage("Fast-foward from " + oldCommit.name() + " to " + newCommit.name(), false); Result res = rup.update(walk); switch (res) { case FAST_FORWARD: case NO_CHANGE: case FORCED: break; default: throw new IOException("Could not fast-forward"); } } return newCommit; } catch (RefAlreadyExistsException e) { throw new JGitInternalException(e.getMessage(), e); } catch (RefNotFoundException e) { throw new JGitInternalException(e.getMessage(), e); } catch (InvalidRefNameException e) { throw new JGitInternalException(e.getMessage(), e); } catch (CheckoutConflictException e) { throw new JGitInternalException(e.getMessage(), e); } }
Source:
<code>public void resolveSuppressedMuleExceptionLoggingCause() { ErrorType expected = DISPATCH; Throwable exception = new DispatchException(createStaticMessage("DISPATCH PROBLEM"), new ValidateResponse(), suppressIfPresent(CONNECTION_EXCEPTION, CONNECTION_EXCEPTION.getClass(), true)); MessagingException me = newMessagingException(exception, event, processor); MessagingExceptionResolver anotherResolver = new MessagingExceptionResolver(new TestProcessor()); MessagingException resolved = anotherResolver.resolve(me, locator, emptyList()); assertExceptionErrorType(resolved, expected); assertExceptionMessage(resolved.getMessage(), "DISPATCH PROBLEM"); <START> assertExceptionMessage(resolved.getInfo().get(MuleExceptionInfo.INFO_CAUSED_BY_KEY).toString(), "CONNECTION PROBLEM"); <END> }</code><technical_language>static import</technical_language>

Target:
public void resolveSuppressedMuleExceptionLoggingCause() { ErrorType expected = DISPATCH; Throwable exception = new DispatchException(createStaticMessage("DISPATCH PROBLEM"), new ValidateResponse(), suppressIfPresent(CONNECTION_EXCEPTION, CONNECTION_EXCEPTION.getClass())); MessagingException me = newMessagingException(exception, event, processor); MessagingExceptionResolver anotherResolver = new MessagingExceptionResolver(new TestProcessor()); MessagingException resolved = anotherResolver.resolve(me, locator, emptyList()); assertExceptionErrorType(resolved, expected); assertExceptionMessage(resolved.getMessage(), "DISPATCH PROBLEM"); assertExceptionMessage(resolved.getInfo().get(INFO_CAUSED_BY_KEY).toString(), "CONNECTION PROBLEM"); }
Source:
<code>public void testScheduledPoolGC() throws Exception { ActiveMQServer server = new ActiveMQServerImpl(); server.start(); WeakReference<Runnable> scheduledRunnableRef; { Runnable scheduledRunnable = new Runnable() { @Override public void run() { } }; scheduledRunnableRef = new WeakReference<>(scheduledRunnable); ScheduledFuture scheduledFuture = server.getScheduledPool().schedule(scheduledRunnable, 5000, TimeUnit.MILLISECONDS); scheduledFuture.cancel(true); } Assert.assertNotEquals(null, scheduledRunnableRef.get()); long timeout = System.currentTimeMillis() + 3000; while (timeout > System.currentTimeMillis() && scheduledRunnableRef.get() != null) { ThreadLeakCheckRule.forceGC(); } <START> <END> Assert.assertEquals(null, scheduledRunnableRef.get()); }</code><technical_language>GC is precise (when out of scope/not referenced collected immediately) depend type of GC chosen: need issue (full) GC right check weak reference, is reliable enough. other tests do similar ad-hoc call GC, point Monday</technical_language>

Target:
public void testScheduledPoolGC() throws Exception { ActiveMQServer server = createServer(false); server.start(); Runnable scheduledRunnable = new Runnable() { @Override public void run() { Assert.fail(); } }; WeakReference<Runnable> scheduledRunnableRef = new WeakReference<>(scheduledRunnable); ScheduledExecutorService scheduledPool = server.getScheduledPool(); ScheduledFuture scheduledFuture = scheduledPool.schedule(scheduledRunnable, 5000, TimeUnit.MILLISECONDS); Assert.assertFalse(scheduledFuture.isCancelled()); Assert.assertTrue(scheduledFuture.cancel(true)); Assert.assertTrue(scheduledFuture.isCancelled()); Assert.assertNotEquals(null, scheduledRunnableRef.get()); scheduledRunnable = null; forceGC(); Assert.assertEquals(null, scheduledRunnableRef.get()); server.stop(); }
Source:
<code>protected double scoreForNullFormat(Object planData, RegisteredType type, RegisteredTypeLoadingContext context) { <START> return 0; END> }</code><technical_language>implementation of this? TOSCA's spec > In TOSCA Simple Profile, TOSCA Service Templates have, line of YAML, keyword "tosca_definitions_version" TOSCA Namespace Alias value. CampTypePlanTransformer again, call RegisteredTypes.getAsYamlMap(planData)and return 1 if map contains tosca_definitions_version 0 otherwise</technical_language>

Target:
protected double scoreForNullFormat(Object planData, RegisteredType type, RegisteredTypeLoadingContext context) { Maybe<Map<?, ?>> yamlMap = RegisteredTypes.getAsYamlMap(planData); if (yamlMap.isAbsent() || !yamlMap.get().containsKey("tosca_definitions_version")) { return 0; } return 1; }
Source:
<code>public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = true; fEvents = Collections.singletonList(event); } else { if (fEvents.equals(Collections.EMPTY_LIST)) { fEvents = new ArrayList<>(); } if (fEvents.size() > id && fEvents.get(id) != null) { throw new ParseException("Event id already exists"); } <START> while (fEvents.size() <= id) { <END> fEvents.add(null); } fEvents.set(id, event); } }</code><technical_language>Indeed! However, reading it, I ensureCapacity() loop more efficient avoid growing list times add(). worth though</technical_language>

Target:
public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = true; fEvents = Collections.singletonList(event); } else { if (fEvents.equals(Collections.EMPTY_LIST)) { fEvents = new ArrayList<>(); } if (fEvents.size() > id && fEvents.get(id) != null) { throw new ParseException("Event id already exists"); } ensureSize(id); fEvents.set(id, event); } }
Source:
<code>protected void executeCommand() { addCustomValue(AUDIT_LOG_VAR_VM_NAME, getVmName()); addCustomValue(AUDIT_LOG_VAR_MEMORY_SIZE_MB, String.valueOf(getUnpluggedDeviceSize())); addCustomValue(AUDIT_LOG_VAR_DEVICE_ID, getParameters().getDeviceId().toString()); final VDSReturnValue vdsReturnValue = runVdsCommand( VDSCommandType.HotUnplugMemory, new HotUnplugMemoryVDSCommand.Params(getVm().getRunOnVds(), getDeviceToHotUnplug(), <START> getVm().getMinAllocatedMem())); <END> if (!vdsReturnValue.getSucceeded()) { addCustomValue(AUDIT_LOG_VAR_ERROR_MESSAGE, vdsReturnValue.getVdsError().getMessage()); setReturnValueFailure(vdsReturnValue); return; } if (getVm().getMemSizeMb() - getUnpluggedDeviceSize() >= getVm().getMinAllocatedMem()) { updateVm(); } setSucceeded(true); }</code><technical_language>please give a hint is of vm.minAllocatedMem changed? is changed hot-setting VDSM a NOOP</technical_language>

Target:
protected void executeCommand() { addCustomValue(AUDIT_LOG_VAR_VM_NAME, getVmName()); addCustomValue(AUDIT_LOG_VAR_MEMORY_SIZE_MB, String.valueOf(getUnpluggedDeviceSize())); addCustomValue(AUDIT_LOG_VAR_DEVICE_ID, getParameters().getDeviceId().toString()); final VDSReturnValue vdsReturnValue = runVdsCommand( VDSCommandType.HotUnplugMemory, new HotUnplugMemoryVDSCommand.Params(getVm().getRunOnVds(), getDeviceToHotUnplug())); if (!vdsReturnValue.getSucceeded()) { addCustomValue(AUDIT_LOG_VAR_ERROR_MESSAGE, vdsReturnValue.getVdsError().getMessage()); setReturnValueFailure(vdsReturnValue); return; } if (getVm().getMemSizeMb() - getUnpluggedDeviceSize() >= getVm().getMinAllocatedMem()) { updateVm(); } setSucceeded(true); }
Source:
<code>public int indexOf(byte[] bytes) { <START> int i = 0; <END> for (byte[] label : labels) { if (Arrays.equals(label, bytes)) { return i; } i++; } return -1; }</code><technical_language>This method call offset 0 length of bytes.length</technical_language>

Target:
public int indexOf(byte[] bytes) { return indexOf(bytes, 0, bytes.length); }
Source:
<code>public void indexSync() { linker.linkTo(this).execute(); final HttpPost httpPost = new HttpPost(linker.get()); <START> final Cookie[] cookies = user.getRequest().getCookies(); <END> LOGGER.info("Running thread to sync solr indexes"); new Thread(new Runnable() { @Override public void run() { LOGGER.info("Solr indexes thread started!"); CookieStore cookieStore = new BasicCookieStore(); for (Cookie c : cookies) { BasicClientCookie bc = new BasicClientCookie(c.getName(), c.getValue()); bc.setDomain("localhost"); cookieStore.addCookie(bc); } try ( CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .build() ) { CloseableHttpResponse response = httpClient.execute(httpPost); LOGGER.info("Index sync received " + response.getStatusLine().getStatusCode()); } catch (IOException e) { LOGGER.info("Couldn't execute post " + httpPost); } } }).start(); result.nothing(); }</code><technical_language>I injecting HttpServletRequest job is creating a getter for loggeduser. more sense for me, do think? :)</technical_language>

Target:
public void indexSync() { linker.linkTo(this).execute(); final HttpPost httpPost = new HttpPost(linker.get()); final Cookie[] cookies = request.getCookies(); LOGGER.info("Running thread to sync solr indexes"); new Thread(new Runnable() { @Override public void run() { LOGGER.info("Solr indexes thread started!"); CookieStore cookieStore = new BasicCookieStore(); for (Cookie c : cookies) { BasicClientCookie bc = new BasicClientCookie(c.getName(), c.getValue()); bc.setDomain("localhost"); cookieStore.addCookie(bc); } try ( CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .build() ) { CloseableHttpResponse response = httpClient.execute(httpPost); LOGGER.info("Index sync received " + response.getStatusLine().getStatusCode()); } catch (IOException e) { LOGGER.info("Couldn't execute post " + httpPost); } } }).start(); result.nothing(); }
Source:
<code>public void onUnityAdsPlacementStateChanged(String placementId, UnityAds.PlacementState oldState, UnityAds.PlacementState newState) { if (newState == UnityAds.PlacementState.WAITING || newState == UnityAds.PlacementState.READY) { <START> for (Listener listener : mListeners) { <END> listener.onInitializeSuccess(); } mListeners.clear(); UnityAds.removeListener(getInstance().getUnitySingletonListenerInstance()); } }</code><technical_language>This callback is for 1 placement WAITING READY state, of them. This list of listeners for multiple placements though. This is adapter previously wait for initialization complete start loading ads -- a concept of "init complete". If goal is call UnityAds.load() a placement is WAITING READY state, this code necessarily accomplish goal. accomplish this refactor</technical_language>

Target:
public void onUnityAdsPlacementStateChanged(String placementId, UnityAds.PlacementState oldState, UnityAds.PlacementState newState) { if (mPlacementsInUse.containsKey(placementId) && mPlacementsInUse.get(placementId).get() != null) { mPlacementsInUse.get(placementId).get().onUnityAdsPlacementStateChanged(placementId, oldState, newState); } }
Source:
<code><START> private static Class<Map> getMapClass(String className) { <END> return Util.<Map>loadClass(className, Map.class.getClassLoader()); }</code><technical_language>I this return a Class<? extends Map></technical_language>

Target:
private static Class<? extends Map> getMapClass(String className) { return Util.<Map>loadClass(className, Map.class.getClassLoader()); }
Source:
<code>public void test() { final CatalogDescriptor catalogDescriptor = new JDBCCatalogDescriptor(PostgresCatalog.DEFAULT_DATABASE, TEST_USERNAME, TEST_PWD, baseUrl); final Map<String, String> properties = catalogDescriptor.toProperties(); final Catalog actualCatalog = TableFactoryService.find(CatalogFactory.class, properties) .createCatalog(TEST_CATALOG_NAME, properties); <START> checkEquals(catalog, (JDBCCatalog) actualCatalog); <END> }</code><technical_language>minor: assert internal catalog is instance of PostgresCatalog</technical_language>

Target:
public void test() { final CatalogDescriptor catalogDescriptor = new JDBCCatalogDescriptor(PostgresCatalog.DEFAULT_DATABASE, TEST_USERNAME, TEST_PWD, baseUrl); final Map<String, String> properties = catalogDescriptor.toProperties(); final Catalog actualCatalog = TableFactoryService.find(CatalogFactory.class, properties) .createCatalog(TEST_CATALOG_NAME, properties); checkEquals(catalog, (JDBCCatalog) actualCatalog); assertTrue(((JDBCCatalog) actualCatalog).getInternal() instanceof PostgresCatalog); }
Source:
<code>public RespondingGatewayPatientLocationQueryResponseType processPatientLocationQuery( PatientLocationQueryRequestType request, AssertionType assertion, NhinTargetCommunitiesType targets) { LOG.debug("Begin EntityPatientLocationQueryProxyWebServiceSecuredImpl.processPatientLocationQuery"); RespondingGatewayPatientLocationQueryResponseType response = new RespondingGatewayPatientLocationQueryResponseType(); try { <START> String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.ENTITY_XDS_SECURED_SERVICE_NAME); <END> ServicePortDescriptor<EntityPatientLocationQuerySecuredPortType> portDescriptor = getServicePortDescriptor(); CONNECTClient<EntityPatientLocationQuerySecuredPortType> client = getCONNECTClient(portDescriptor, url, assertion); RespondingGatewayPatientLocationQueryRequestType securedRequest = new RespondingGatewayPatientLocationQueryRequestType(); securedRequest.setNhinTargetCommunities(targets); securedRequest.setPatientLocationQueryRequest(request); response = (RespondingGatewayPatientLocationQueryResponseType) client .invokePort(EntityPatientLocationQuerySecuredPortType.class, "respondingGatewayPatientLocationQuery", securedRequest); } catch (Exception e) { LOG.error("Error calling respondingGatewayPatientLocationQuery: {}", e.getMessage(), e); throw new IllegalStateException("Error calling respondingGatewayPatientLocationQuery", e); } LOG.debug("End EntityPatientLocationQueryProxyWebServiceSecuredImpl.processPatientLocationQuery"); return response; }</code><technical_language>ENTITY_XDS_SECURED_SERVICE_NAME for PLQ</technical_language>

Target:
public RespondingGatewayPatientLocationQueryResponseType processPatientLocationQuery( PatientLocationQueryRequestType request, AssertionType assertion, NhinTargetCommunitiesType targets) { LOG.debug("Begin EntityPatientLocationQueryProxyWebServiceSecuredImpl.processPatientLocationQuery"); RespondingGatewayPatientLocationQueryResponseType response = new RespondingGatewayPatientLocationQueryResponseType(); try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.PLQ_ENTITYSECURED_SERVICE_NAME); ServicePortDescriptor<EntityPatientLocationQuerySecuredPortType> portDescriptor = getServicePortDescriptor(); CONNECTClient<EntityPatientLocationQuerySecuredPortType> client = getCONNECTClient(portDescriptor, url, assertion); RespondingGatewayPatientLocationQueryRequestType securedRequest = new RespondingGatewayPatientLocationQueryRequestType(); securedRequest.setNhinTargetCommunities(targets); securedRequest.setPatientLocationQueryRequest(request); response = (RespondingGatewayPatientLocationQueryResponseType) client .invokePort(EntityPatientLocationQuerySecuredPortType.class, "respondingGatewayPatientLocationQuery", securedRequest); } catch (Exception e) { LOG.error("Error calling respondingGatewayPatientLocationQuery: {}", e.getMessage(), e); throw new IllegalStateException("Error calling respondingGatewayPatientLocationQuery", e); } LOG.debug("End EntityPatientLocationQueryProxyWebServiceSecuredImpl.processPatientLocationQuery"); return response; }
Source:
<code><START> public static void reportEvent(String category, String action, String label, int value) { <END> if (analyticsDisabled()) { return; } getTracker().send(new HitBuilders.EventBuilder() .setCategory(category) .setAction(action) .setLabel(label) .setValue(value) .build()); }</code><technical_language>instances of reportEvent private</technical_language>

Target:
private static void reportEvent(String category, String action, String label, int value) { if (analyticsDisabled() || versionIncompatible()) { return; } getTracker().send(new HitBuilders.EventBuilder() .setCategory(category) .setAction(action) .setLabel(label) .setValue(value) .build()); }
Source:
<code>public void run() { try { while (!Thread.currentThread().isInterrupted()) { operatorChainManager.pickOperatorChain().processNextEvent(); <START> if (threadManager.reapCheck()) { <END> return; } } } catch (final InterruptedException e) { return; } }</code><technical_language>create a close method in EventProcessor call this method ThreadManager? Then, a reference of ThreadManager in EventProcessor</technical_language>

Target:
public void run() { try { while (!Thread.currentThread().isInterrupted() && !closed) { operatorChainManager.pickOperatorChain().processNextEvent(); } } catch (final InterruptedException e) { return; } }
Source:
<code>public RelOptCost getLowerBoundCost(RelSubset subset, RelMetadataQuery mq, VolcanoPlanner planner) { if (planner.isLogical(subset)) { return null; } RelOptCost winner = subset.getWinnerCost(); if (winner != null) { return winner; } if (!subset.isExplored()) { return null; } <START> RelOptCost lowerBound = null; <END> for (RelNode relNode : subset.getRels()) { try { RelOptCost lb = mq.getLowerBoundCost(relNode, planner); if (lb == null) { return null; } if (lowerBound == null || lb.isLt(lowerBound)) { lowerBound = lb; } } catch (CyclicMetadataException e) { if (lowerBound == null) { lowerBound = planner.getCostFactory().makeInfiniteCost(); } } } return lowerBound; }</code><technical_language>If current group is fully optimized winner, problems get bound here. current group's optimization affact input groups of current group. E.g., current group's optimization push some require traits of inputs subtrees enhance costs. if get bound here, larger actual bound miss optimal plan</technical_language>

Target:
public RelOptCost getLowerBoundCost(RelSubset subset, RelMetadataQuery mq, VolcanoPlanner planner) { if (planner.isLogical(subset)) { return null; } return subset.getWinnerCost(); }
Source:
<code>public void commit(File stateDir, String objectId, Part part) { log.debug("Attempting to commit part to {}", objectId, part.getPartNumber(), stateDir.toString()); <START> val mapper = new ObjectMapper(); <END> try { byte[] content = mapper.writeValueAsBytes(part); val partFile = new File(getObjectStateDir(stateDir, objectId), getPartName(part)); Files.copy(new ByteArrayInputStream(content), partFile.toPath()); log.debug("Copied part to {}", part.getPartNumber(), partFile.toPath().toString()); } catch (IOException e) { log.error("Failed to create meta file ", stateDir.getAbsolutePath(), e); throw new NotRetryableException(e); } }</code><technical_language>expensive create object mappers. Jackson.DEFAULT instead, create static field</technical_language>

Target:
public void commit(File stateDir, String objectId, Part part) { log.debug("Attempting to commit part to {}", objectId, part.getPartNumber(), stateDir.toString()); try { byte[] content = MAPPER.writeValueAsBytes(part); val partFile = new File(getObjectStateDir(stateDir, objectId), getPartName(part)); Files.copy(new ByteArrayInputStream(content), partFile.toPath()); log.debug("Copied part to {}", part.getPartNumber(), partFile.toPath().toString()); } catch (IOException e) { log.error("Failed to create meta file ", stateDir.getAbsolutePath(), e); throw new NotRetryableException(e); } }
Source:
<code>public void testElementsToSelectExpressionMigration() { copyFilesToTestProject(SiriusTestsPlugin.PLUGIN_ID, PATH, MODELER_FILE_NAME); ResourceSet set = new ResourceSetImpl(); Group vsmRoot = null; try { vsmRoot = (Group) ModelUtils.load(URI.createPlatformResourceURI(TEMPORARY_PROJECT_NAME + "/" + MODELER_FILE_NAME, true), set); } catch (IOException e) { <START> e.printStackTrace(); <END> } AbstractToolDescription tool = getTool(vsmRoot, "Tree_CreateItem"); assertEquals("Bad ElementsToSelect expression", tool.getElementsToSelect(), InitializeCreationToolElementsToSelectExpressionParticipant.ELEMENTS_TO_SELECT_EXPRESSION); tool = getTool(vsmRoot, "Initialized_Tree_CreateItem"); assertEquals("Bad ElementsToSelect expression", tool.getElementsToSelect(), "[instance/]"); try { vsmRoot.eResource().save(Collections.emptyMap()); } catch (IOException e) { e.printStackTrace(); } String version = vsmRoot.getVersion(); assertFalse("The version tag should now be set telling that the migration was done.", VSMMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); }</code><technical_language>A try/catch in test exists if want test exception throwing. a stacktrace displayed in stdout a green test. test throw Exception</technical_language>

Target:
public void testElementsToSelectExpressionMigration() throws Exception { copyFilesToTestProject(SiriusTestsPlugin.PLUGIN_ID, PATH, MODELER_FILE_NAME); ResourceSet set = new ResourceSetImpl(); Group vsmRoot = null; vsmRoot = (Group) ModelUtils.load(URI.createPlatformResourceURI(TEMPORARY_PROJECT_NAME + "/" + MODELER_FILE_NAME, true), set); AbstractToolDescription tool = getTool(vsmRoot, "Tree_CreateItem"); assertEquals("Bad ElementsToSelect expression", tool.getElementsToSelect(), InitializeCreationToolElementsToSelectExpressionParticipant.ELEMENTS_TO_SELECT_EXPRESSION); tool = getTool(vsmRoot, "Initialized_Tree_CreateItem"); assertEquals("Bad ElementsToSelect expression", tool.getElementsToSelect(), "[instance/]"); try { vsmRoot.eResource().save(Collections.emptyMap()); } catch (IOException e) { e.printStackTrace(); } String version = vsmRoot.getVersion(); assertFalse("The version tag should now be set telling that the migration was done.", VSMMigrationService.getInstance().isMigrationNeeded(Version.parseVersion(version))); }
Source:
<code>public URI getExternalUri() { String host = getHostname() .orElseGet(() -> { try { return new NetworkUtils().getNonLoopbackAddressOfThisMachine(); } catch (WebDriverException e) { String name = HostIdentifier.getHostName(); LOG.info("No network connection, guessing name: " + name); return name; } }); int port = getPort(); <START> try { <END> if (isSecure()) { return new URI("https", null, host, port, null, null, null); } else { return new URI("http", null, host, port, null, null, null); } } catch (URISyntaxException e) { throw new ConfigException("Cannot determine external URI: " + e.getMessage()); } }</code><technical_language>Consider: return new URI(isSecure() ? "https" : "http", null, host, port, null, null, null) emphasise changes is scheme</technical_language>

Target:
public URI getExternalUri() { String host = getHostname() .orElseGet(() -> { try { return new NetworkUtils().getNonLoopbackAddressOfThisMachine(); } catch (WebDriverException e) { String name = HostIdentifier.getHostName(); LOG.info("No network connection, guessing name: " + name); return name; } }); int port = getPort(); try { return new URI(isSecure() ? "https" : "http", null, host, port, null, null, null); } catch (URISyntaxException e) { throw new ConfigException("Cannot determine external URI: " + e.getMessage()); } }