auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> default boolean messageIsValid(CorfuMsg msg, ChannelHandlerContext ctx) { if (msg.getMsgType().ignoreEpoch) { return true; } if (!epochIsValid(msg, ctx)) { return false; } return getCurrentLayout() .map(layout -> clusterIdIsValid(msg, ctx, layout)) .orElseGet(() -> { sendNoBootstrapMessage(msg, ctx); return false; }); <END> }</code><technical_language>This incorrect. Imagine a fault detector cluster seal a node another cluster. a seal message is marked ignore epoch, check executed allowing fault detectors cluster reconfigure other's nodes</technical_language>

Target:
default boolean messageIsValid(CorfuMsg msg, ChannelHandlerContext ctx) { if (!msg.getMsgType().ignoreEpoch && !epochIsValid(msg, ctx)) { return false; } if(!msg.getMsgType().ignoreClusterId){ return getCurrentLayout() .map(layout -> clusterIdIsValid(msg, ctx, layout)) .orElseGet(() -> { sendNoBootstrapMessage(msg, ctx); return false; }); } return true; }
Source:
<code>public ScalarUdf createInstance(String clazz, String udfName) { Config udfConfig = udfMetadata.get(udfName).get(0).getUdfConfig(); <START> ScalarUdf scalarUdf = ReflectionUtil.createInstanceOrNull(clazz, ScalarUdf.class, getClass().getClassLoader()); <END> if (scalarUdf == null) { String msg = String.format("Couldn't create udf %s of class %s", udfName, clazz); throw new SamzaException(msg); } scalarUdf.init(udfConfig); return scalarUdf; }</code><technical_language>do ClassLoader use? I noticed ClassLoader of this object is used, ClassLoader of another class is (like in SamzaSqlApplicationConfig) a custom ClassLoader is (like ArrayListOnlyClassLoader)</technical_language>

Target:
public ScalarUdf createInstance(String clazz, String udfName) { Config udfConfig = udfMetadata.get(udfName).get(0).getUdfConfig(); ScalarUdf scalarUdf = ReflectionUtil.getObj(getClass().getClassLoader(), clazz, ScalarUdf.class); scalarUdf.init(udfConfig); return scalarUdf; }
Source:
<code>public boolean updateMessageOnIccEf(int index, int status, byte[] pdu) { if (DBG) log("updateMessageOnIccEf: index=" + index + " status=" + status + " ==> " + "("+ pdu + ")"); enforceReceiveAndSend("Updating message on RUIM"); synchronized(mLock) { mSuccess = false; Message response = mHandler.obtainMessage(EVENT_UPDATE_DONE); if (status == STATUS_ON_ICC_FREE) { <START> mPhone.mCM.deleteSmsOnRuim(index, response); <END> } else { byte[] record = makeSmsRecordData(status, pdu); ((RuimFileHandler)mPhone.getIccFileHandler()).updateEFLinearFixed( IccConstants.EF_SMS, index, record, null, response); } try { mLock.wait(); } catch (InterruptedException e) { log("interrupted while trying to update by index"); } } return mSuccess; }</code><technical_language>Do need deleteSmsOnRuim deleteSmsOnSim pass a parameter instead</technical_language>

Target:
updateMessageOnIccEf(int index, int status, byte[] pdu) { if (DBG) log("updateMessageOnIccEf: index=" + index + " status=" + status + " ==> " + "("+ pdu + ")"); enforceReceiveAndSend("Updating message on RUIM"); synchronized(mLock) { mSuccess = false; Message response = mHandler.obtainMessage(EVENT_UPDATE_DONE); if (status == STATUS_ON_ICC_FREE) { mPhone.mCM.deleteSmsOnRuim(index, response); } else { byte[] record = makeSmsRecordData(status, pdu); ((RuimFileHandler)mPhone.getIccFileHandler()).updateEFLinearFixed( IccConstants.EF_SMS, index, record, null, response); } try { mLock.wait(); } catch (InterruptedException e) { log("interrupted while trying to update by index"); } } return mSuccess; }
Source:
<code>public boolean match(Block block) { boolean ret; if (block instanceof MacroBlock) { ret = ((MacroBlock) block).getId().equals("mention") && Optional.ofNullable(block.getParameter("anchor")) .map(it -> it.equals(this.anchorId)) <START> .orElse(false); <END> } else { ret = false; } return ret; }</code><technical_language>sounds if anchor parameter is null returning false here</technical_language>

Target:
public boolean match(Block block) { boolean ret; if (block instanceof MacroBlock) { ret = ((MacroBlock) block).getId().equals("mention") && Objects.equals(Objects.toString(block.getParameter("anchor"), ""), this.anchorId); } else { ret = false; } return ret; }
Source:
<code>public void changeStateOfProgramEnrollment(String configName, String programEnrollmentUuid, DateTime programCompletedDate, String stateUuid, DateTime startDate) { ProgramEnrollment programEnrollment = new ProgramEnrollment(); programEnrollment.setUuid(programEnrollmentUuid); programEnrollment.setDateCompleted(Objects.nonNull(programCompletedDate) ? programCompletedDate.toDate() : null); <START> if (!Strings.isNullOrEmpty(stateUuid)) { <END> Program.State state = new Program.State(); state.setUuid(stateUuid); ProgramEnrollment.StateStatus stateStatus = new ProgramEnrollment.StateStatus(); stateStatus.setState(state); stateStatus.setStartDate(startDate.toDate()); programEnrollment.setStates(Collections.singletonList(stateStatus)); } programEnrollmentService.updateProgramEnrollment(configName, programEnrollment); }</code><technical_language>StringUtils apache.commons, this class is imported I this</technical_language>

Target:
public void changeStateOfProgramEnrollment(String configName, String programEnrollmentUuid, DateTime programCompletedDate, String stateUuid, DateTime startDate) { ProgramEnrollment programEnrollment = new ProgramEnrollment(); programEnrollment.setUuid(programEnrollmentUuid); programEnrollment.setDateCompleted(Objects.nonNull(programCompletedDate) ? programCompletedDate.toDate() : null); if (StringUtils.isNotBlank(stateUuid)) { Program.State state = new Program.State(); state.setUuid(stateUuid); ProgramEnrollment.StateStatus stateStatus = new ProgramEnrollment.StateStatus(); stateStatus.setState(state); stateStatus.setStartDate(startDate.toDate()); programEnrollment.setStates(Collections.singletonList(stateStatus)); } programEnrollmentService.updateProgramEnrollment(configName, programEnrollment); }
Source:
<code>public Iterable<Image> listImages() { final ImmutableList.Builder<Image> images = ImmutableList.builder(); final List<String> availableLocationNames = newArrayList( transform(listLocations(), new Function<Region, String>() { @Override public String apply(Region location) { return location.id(); } <START> })); <END> for (String regionId : availableLocationNames) { images.addAll(api.imageApi().list(regionId).concat()); } return images.build(); }</code><technical_language>This availableLocation refactored method, lines in places</technical_language>

Target:
public Iterable<ImageInRegion> listImages() { final ImmutableList.Builder<ImageInRegion> imagesInRegion = ImmutableList.builder(); for (final String regionId : getAvailableLocationNames()) { imagesInRegion.addAll(api.imageApi().list(regionId).concat() .transform(new Function<Image, ImageInRegion>() { @Override public ImageInRegion apply(Image image) { return ImageInRegion.create(regionId, image); } }) ); } return imagesInRegion.build(); }
Source:
<code>public void checkRegularExecution() { System.setProperty("kie.maven.offline.force", "false"); final M2ServletContextListener listener = spy(new M2ServletContextListener()); final ServletContextEvent contextEvent = mock(ServletContextEvent.class); final ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath(any())).thenReturn("."); when(contextEvent.getServletContext()).thenReturn(servletContext); listener.contextInitialized(contextEvent); <START> System.clearProperty("kie.maven.offline.force"); <END> verify(listener, times(0)).deployJarsFromWar(any()); }</code><technical_language>Please move this clearProperty call @After guarantee cleanup if test fails</technical_language>

Target:
public void checkRegularExecution() { System.setProperty("kie.maven.offline.force", "false"); final M2ServletContextListener listener = spy(new M2ServletContextListener()); final ServletContextEvent contextEvent = mock(ServletContextEvent.class); final ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath(any())).thenReturn("."); when(contextEvent.getServletContext()).thenReturn(servletContext); listener.contextInitialized(contextEvent); verify(listener, times(0)).deployJarsFromWar(any()); }
Source:
<code>public List<Comment> getComments(CoreSession session, String documentId) { DocumentModel commentedDoc = session.getDocument(new IdRef(documentId)); return getComments(commentedDoc).stream().map(commentModel -> { <START> Comment comment = new CommentImpl(); <END> comment.setAuthor((String) commentModel.getPropertyValue(COMMENT_AUTHOR)); comment.setText((String) commentModel.getPropertyValue(COMMENT_TEXT)); comment.setDocumentId(documentId); comment.setCreationDate((Instant) commentModel.getPropertyValue(COMMENT_CREATION_DATE)); return comment; }).collect(Collectors.toList()); }</code><technical_language>IllegalArgumentException</technical_language>

Target:
public List<Comment> getComments(CoreSession session, String documentId) throws IllegalArgumentException { DocumentRef docRef = new IdRef(documentId); if (!session.exists(docRef)) { throw new IllegalArgumentException("The document " + documentId + " does not exist."); } DocumentModel commentedDoc = session.getDocument(new IdRef(documentId)); return getComments(commentedDoc).stream().map(commentModel -> { Comment comment = new CommentImpl(); comment.setAuthor((String) commentModel.getPropertyValue(COMMENT_AUTHOR)); comment.setText((String) commentModel.getPropertyValue(COMMENT_TEXT)); comment.setDocumentId(documentId); comment.setCreationDate((Instant) commentModel.getPropertyValue(COMMENT_CREATION_DATE)); return comment; }).collect(Collectors.toList()); }
Source:
<code>public ServiceBusManagementClientBuilder endpoint(String endpoint) { <START> try { <END> new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; }</code><technical_language>check for endpoint null throw NPE</technical_language>

Target:
public ServiceBusManagementClientBuilder endpoint(String endpoint) { final URL url; try { url = new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null.")); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = url.getHost(); return this; }
Source:
<code>public EventType mapRow(ResultSet rs, int rowNum) throws SQLException { try { return jsonMapper.readValue(rs.getString(2), EventType.class); } catch (IOException e) { <START> return null; <END> } }</code><technical_language>I log this means corrupted data in db</technical_language>

Target:
public EventType mapRow(ResultSet rs, int rowNum) throws SQLException { try { return jsonMapper.readValue(rs.getString("et_event_type_object"), EventType.class); } catch (IOException e) { throw new SQLException(e); } }
Source:
<code>public void clientConfiguredForDomain() throws IOException { <START> System.out.println("==================================="); <END> ManagementClient.online(OnlineOptions.domain().build() .localDefault() .protocol(ManagementProtocol.HTTPS) .ssl(sslOptions) .auth(USERNAME, PASSWORD) .connectionTimeout(5000) .build() ); }</code><technical_language>Please :-)</technical_language>

Target:
public void clientConfiguredForDomain() throws IOException { ManagementClient.online(OnlineOptions.domain().build() .localDefault() .protocol(ManagementProtocol.HTTPS) .ssl(sslOptions) .auth(USERNAME, PASSWORD) .connectionTimeout(5000) .build() ); }
Source:
<code>public ResourceAlreadyExistsException(String resourceName, String resourceId) { <START> super(format("%s resource with id \'%s\' already exists.", resourceName, resourceId)); <END> }</code><technical_language>I is need escape single quote double quotes</technical_language>

Target:
public ResourceAlreadyExistsException(String resourceName, String resourceId) { super(format("%s resource with id '%s' already exists.", resourceName, resourceId)); }
Source:
<code>private String setupMountPoint(String parent) { String mountPoint = null; <START> for (int i = 0; i < 10; i++) { String mntPt = parent + File.separator + String.valueOf(ManagementServerNode.getManagementServerId()) + "." + Integer.toHexString(rand.nextInt(Integer.MAX_VALUE)); File file = new File(mntPt); if (!file.exists()) { if (storage.mkdir(mntPt)) { mountPoint = mntPt; break; } } s_logger.error("Unable to create mount: " + mntPt); } return mountPoint; <END> }</code><technical_language>ten time logging error for time. done return null if failed! I improve this</technical_language>

Target:
private String setupMountPoint(String parent) { String mountPoint = null; String mntPt = parent + File.separator + String.valueOf(ManagementServerNode.getManagementServerId()) + "." + Integer.toHexString(rand.nextInt(Integer.MAX_VALUE)); for (int i = 0; i < 10; i++) { File file = new File(mntPt); if (!file.exists()) { if (storage.mkdir(mntPt)) { mountPoint = mntPt; break; } } } if (mountPoint == null){ s_logger.error("Unable to create mount: " + mntPt); } return mountPoint; }
Source:
<code>public static LocalDate deserializeLocalDate(String dateTimeString) throws IOException { return deserializeLocalDateTime(dateTimeString).toLocalDate(); <START> } <END></code><technical_language>public static LocalDate deserializeLocalDate(String dateTimeString) throws IOException { return DATE_FORMATTER.parse(dateTimeString, LocalDate::from); }</technical_language>

Target:
public static LocalDate deserializeLocalDate(String dateTimeString) throws IOException { return DATE_FORMATTER.parse(dateTimeString, LocalDate::from); }
Source:
<code>public String getLongAccessLabel() { String label = ""; if(isSiteOnly()) { checkParent(); if(this.parent == null) { label = trb.getString("access.site.noparent"); logger.warn("ListItem.getLongAccessLabel(): Unable to display label because isSiteOnly == true and parent == null and constructor == " + this.constructor); } else { label = trb.getFormattedMessage("access.site.nochoice", new String[]{parent.getName()}); } } else if(isGroupInherited()) { label = getMultiGroupLabel(); } else if(inheritsRoles()) { checkParent(); if(parent == null) { Iterator<String> roleIterator = this.inheritedRoleIds.iterator(); <START> label = trb.getString(String.format(String.format("access.role%s.noparent", roleIterator.next()))); <END> while(roleIterator.hasNext()) { label += "<br/>" + trb.getString(String.format(String.format("access.role%s.noparent", roleIterator.next()))); } logger.warn("ListItem.getLongAccessLabel(): Unable to display label because isPubviewInherited == true and parent == null and constructor == " + this.constructor); } else { Iterator<String> roleIterator = this.inheritedRoleIds.iterator(); label = trb.getFormattedMessage(String.format("access.role%s.nochoice", roleIterator.next()), new String[]{parent.getName()}); while(roleIterator.hasNext()) { label += "<br/>" + trb.getFormattedMessage(String.format("access.role%s.nochoice", roleIterator.next()), new String[]{parent.getName()}); } } } else if(isCollection()) { label = trb.getString("edit.who.fldr"); } else { label = trb.getString("edit.who"); } return label; }</code><technical_language>Redundant String.format()</technical_language>

Target:
public String getLongAccessLabel() { String label = ""; if(isSiteOnly()) { checkParent(); if(this.parent == null) { label = trb.getString("access.site.noparent"); logger.warn("ListItem.getLongAccessLabel(): Unable to display label because isSiteOnly == true and parent == null and constructor == " + this.constructor); } else { label = trb.getFormattedMessage("access.site.nochoice", new String[]{parent.getName()}); } } else if(isGroupInherited()) { label = getMultiGroupLabel(); } else if(inheritsRoles()) { checkParent(); if(parent == null) { Iterator<String> roleIterator = this.inheritedRoleIds.iterator(); label = trb.getString(String.format("access.role%s.noparent", roleIterator.next())); while(roleIterator.hasNext()) { label += "<br/>" + trb.getString(String.format("access.role%s.noparent", roleIterator.next())); } logger.warn("ListItem.getLongAccessLabel(): Unable to display label because isPubviewInherited == true and parent == null and constructor == " + this.constructor); } else { Iterator<String> roleIterator = this.inheritedRoleIds.iterator(); label = trb.getFormattedMessage(String.format("access.role%s.nochoice", roleIterator.next()), new String[]{parent.getName()}); while(roleIterator.hasNext()) { label += "<br/>" + trb.getFormattedMessage(String.format("access.role%s.nochoice", roleIterator.next()), new String[]{parent.getName()}); } } } else if(isCollection()) { label = trb.getString("edit.who.fldr"); } else { label = trb.getString("edit.who"); } return label; }
Source:
<code>public void conditionalReplaceAll(String originator, TaskId taskid, String channel, String predicate, String thenRemappingFunction, String elseRemappingFunction) throws InvalidChannelException, CompilationException, IOException { String currentKey = null; try { Channel chosenChannel = getChannel(channel); for (Map.Entry<String, Serializable> entry : chosenChannel.entrySet()) { currentKey = entry.getKey(); Serializable value = chosenChannel.get(currentKey); if (evaluateClosure(predicate, BiPredicate.class).test(currentKey, value)) { Serializable answer = chosenChannel.compute(currentKey, (BiFunction<? super String, ? super Serializable, ? extends Serializable>) evaluateClosure(thenRemappingFunction, <START> BiFunction.class)); <END> logWithContext(taskid, channel, "Run conditionalReplaceAll(Then)" + ON_KEY + QUOTE + currentKey + QUOTE + RESULT_IS + answer, Level.DEBUG); } else { Serializable answer = chosenChannel.compute(currentKey, (BiFunction<? super String, ? super Serializable, ? extends Serializable>) evaluateClosure(elseRemappingFunction, BiFunction.class)); logWithContext(taskid, channel, "Run conditionalReplaceAll(Else)" + ON_KEY + QUOTE + currentKey + QUOTE + RESULT_IS + answer, Level.DEBUG); } } commitIfNeeded(channel); } catch (InvalidChannelException | CompilationException | IOException e) { throw e; } catch (Exception e) { throw new ClosureEvaluationException(EXCEPTION_WHEN_EVALUATING_CLOSURE + StackTraceUtil.getStackTrace(e)); } }</code><technical_language>mentioned before, in general a handler function takes action perform logs end, instead of call time logWithContext</technical_language>

Target:
public void conditionalReplaceAll(String originator, TaskId taskid, String channel, String predicate, String thenRemappingFunction, String elseRemappingFunction) throws InvalidChannelException, CompilationException, IOException { String currentKey; try { Channel chosenChannel = getChannel(channel); for (Map.Entry<String, Serializable> entry : chosenChannel.entrySet()) { currentKey = entry.getKey(); if (evaluateClosure(predicate, BiPredicate.class).test(currentKey, entry.getValue())) { chosenChannel.compute(currentKey, (BiFunction<? super String, ? super Serializable, ? extends Serializable>) evaluateClosure(thenRemappingFunction, BiFunction.class)); } else { chosenChannel.compute(currentKey, (BiFunction<? super String, ? super Serializable, ? extends Serializable>) evaluateClosure(elseRemappingFunction, BiFunction.class)); } } logWithContextAndPersist(taskid, channel, "Run conditionalReplaceAll, new content is: " + chosenChannel, Level.DEBUG); } catch (InvalidChannelException | CompilationException | IOException e) { throw e; } catch (Exception e) { throw new ClosureEvaluationException(EXCEPTION_WHEN_EVALUATING_CLOSURE + StackTraceUtil.getStackTrace(e)); } }
Source:
<code>public void setup() throws Exception { DynamicSequentialTask<Object> t = new DynamicSequentialTask<Object>(); <START> DynamicTasks.setTaskQueueingContext(t); <END> app = ApplicationBuilder.newManagedApp(TestApplication.class); mgmt = app.getManagementContext(); LocalhostMachineProvisioningLocation localhost = mgmt.getLocationManager().createLocation( LocationSpec.create(LocalhostMachineProvisioningLocation.class)); host = localhost.obtain(); app.start(Arrays.asList(host)); }</code><technical_language>a good idea -- this sets a thread local interfere other tests. I suspect DynamicTasks.queue(anotherTask) run anotherTask TaskQueueingContext t is submitted executor. (Another reason getMachineDetails fail gracefully if outwith a TQC executionContext.)</technical_language>

Target:
public void setup() throws Exception { app = ApplicationBuilder.newManagedApp(TestApplication.class); mgmt = app.getManagementContext(); LocalhostMachineProvisioningLocation localhost = mgmt.getLocationManager().createLocation( LocationSpec.create(LocalhostMachineProvisioningLocation.class)); host = localhost.obtain(); app.start(Arrays.asList(host)); }
Source:
<code>public MetacardApplication( CatalogFramework catalogFramework, FilterBuilder filterBuilder, EndpointUtil endpointUtil, Validator validator, WorkspaceTransformer transformer, ExperimentalEnumerationExtractor enumExtractor, SubscriptionsPersistentStore subscriptions, List<MetacardType> types, Associated associated, QueryResponseTransformer csvQueryResponseTransformer, AttributeRegistry attributeRegistry, ConfigurationApplication configuration, NoteUtil noteUtil, SubjectIdentity subjectIdentity, AccessControlSecurityConfiguration accessControlSecurityConfiguration) { this.catalogFramework = catalogFramework; this.filterBuilder = filterBuilder; this.util = endpointUtil; this.validator = validator; this.transformer = transformer; this.enumExtractor = enumExtractor; this.subscriptions = subscriptions; this.types = types; this.associated = associated; this.csvQueryResponseTransformer = csvQueryResponseTransformer; this.attributeRegistry = attributeRegistry; this.configuration = configuration; this.noteUtil = noteUtil; this.subjectIdentity = subjectIdentity; <START> this.systemUserList.addAll( <END> Arrays.asList(accessControlSecurityConfiguration.getSystemUserAttributeValue().split(","))); }</code><technical_language>this.systemUserList = Arrays.asList(accessControlSecurityConfiguration.getSystemUserAttributeValue().split(",")); initializing top instead of creating a temporary list add another</technical_language>

Target:
public MetacardApplication( CatalogFramework catalogFramework, FilterBuilder filterBuilder, EndpointUtil endpointUtil, Validator validator, WorkspaceTransformer transformer, ExperimentalEnumerationExtractor enumExtractor, SubscriptionsPersistentStore subscriptions, List<MetacardType> types, Associated associated, QueryResponseTransformer csvQueryResponseTransformer, AttributeRegistry attributeRegistry, ConfigurationApplication configuration, NoteUtil noteUtil, SubjectIdentity subjectIdentity, AccessControlSecurityConfiguration accessControlSecurityConfiguration) { this.catalogFramework = catalogFramework; this.filterBuilder = filterBuilder; this.util = endpointUtil; this.validator = validator; this.transformer = transformer; this.enumExtractor = enumExtractor; this.subscriptions = subscriptions; this.types = types; this.associated = associated; this.csvQueryResponseTransformer = csvQueryResponseTransformer; this.attributeRegistry = attributeRegistry; this.configuration = configuration; this.noteUtil = noteUtil; this.subjectIdentity = subjectIdentity; this.accessControlSecurityConfiguration = accessControlSecurityConfiguration; }
Source:
<code>private int firstIndexOf(int fromIndex, int toIndex, byte value) { fromIndex = Math.max(fromIndex, 0); if (fromIndex >= toIndex || capacity() == 0) { return -1; } <START> for (int i = fromIndex; i < toIndex; i ++) { <END> if (_getByte(i) == value) { return i; } } return -1; }</code><technical_language>uneeded I remember issue counted loop causing long time safe point pauses: nice check if range is big a long based loop in case</technical_language>

Target:
private int firstIndexOf(int fromIndex, int toIndex, byte value) { fromIndex = Math.max(fromIndex, 0); if (fromIndex >= toIndex || capacity() == 0) { return -1; } checkIndex(fromIndex, toIndex - fromIndex); for (int i = fromIndex; i < toIndex; i ++) { if (_getByte(i) == value) { return i; } } return -1; }
Source:
<code>public void close() { <START> fBitBuffer = BitBuffer.EMPTY_BITBUFFER; <END> }</code><technical_language>convinced this is needed free file descriptors... close ByteBuffers, in memory. Anyway, safe, is. However, more simple/representative fBitBuffer null here</technical_language>

Target:
public void close() { fBitBuffer = null; }
Source:
<code>public boolean shouldRun() { final boolean shouldRun = <START> pendingPartitions.size() <END> > 0; return shouldRun; }</code><technical_language>synchronized</technical_language>

Target:
public boolean shouldRun() { synchronized (pendingPartitions) { final boolean shouldRun = pendingPartitions.size() > 0; return shouldRun; } }
Source:
<code>public void initiate() { for (int i = 0; i < currentEnsemble.size(); i++) { <START> lh.bk.getBookieClient().readLac(currentEnsemble.get(i), <END> lh.ledgerId, this, i); } }</code><technical_language>This is perfect</technical_language>

Target:
public void initiate() { for (int i = 0; i < currentEnsemble.size(); i++) { bookieClient.readLac(currentEnsemble.get(i), lh.ledgerId, this, i); } }
Source:
<code>public CreateWsResponse create(CreateRequest request) { return call( new PostRequest(path("create")) .setParam("email", request.getEmail()) .setParam("local", request.getLocal()) .setParam("login", request.getLogin()) .setParam("name", request.getName()) .setParam("password", request.getPassword()) <START> .setParam("scmAccount", request.getScmAccount() == null ? null : request.getScmAccount()) <END> .setParam("scmAccounts", request.getScmAccounts() == null ? null : request.getScmAccounts().stream().collect(Collectors.joining(","))), CreateWsResponse.parser()); }</code><technical_language>point of this change</technical_language>

Target:
public CreateWsResponse create(CreateRequest request) { return call( new PostRequest(path("create")) .setParam("email", request.getEmail()) .setParam("local", request.getLocal()) .setParam("login", request.getLogin()) .setParam("name", request.getName()) .setParam("password", request.getPassword()) .setParam("scmAccount", request.getScmAccount()) .setParam("scmAccounts", request.getScmAccounts() == null ? null : request.getScmAccounts().stream().collect(Collectors.joining(","))), CreateWsResponse.parser()); }
Source:
<code>public void testVersion0_98IsValid() throws Exception{ rootDir = Paths.get(getClass().getClassLoader().getResource("bags/v0_98/bag").toURI()); if (System.getProperty("os.name").contains("Windows")){ <START> Path bagitDir = rootDir.resolve(".bagit"); <END> Files.setAttribute(bagitDir, "dos:hidden", Boolean.TRUE); } Bag bag = reader.read(rootDir); sut.isValid(bag, true); }</code><technical_language>bagit folder hidden. .bagit is incubating next version of bagit spec; solves a lot of problems originial spec</technical_language>

Target:
public void testVersion0_98IsValid() throws Exception{ rootDir = Paths.get(getClass().getClassLoader().getResource("bags/v0_98/bag").toURI()); Bag bag = reader.read(rootDir); sut.isValid(bag, true); }
Source:
<code>protected void checkFile(@NotNull final GoFile file, @NotNull ProblemsHolder problemsHolder) { if (!GoTestFinder.isTestFile(file)) return; GoImportSpec testingImportSpec = file.getImportedPackagesMap().get(GoConstants.TESTING_PATH); String testingAlias = getTestingAlias(testingImportSpec); for (GoFunctionDeclaration function : file.getFunctions()) { GoTestFunctionType type = GoTestFunctionType.fromName(function.getName()); if (type == null) continue; GoSignature signature = function.getSignature(); if (signature == null) continue; List<GoParameterDeclaration> params = signature.getParameters().getParameterDeclarationList(); if (type == GoTestFunctionType.EXAMPLE) { <START> if (params.size() != 0) { <END> problemsHolder.registerProblem(function.getIdentifier(), "Wrong example signature", new GoTestSignaturesQuickFix(type)); } } else { GoParameterDeclaration param = ContainerUtil.getFirstItem(params); if (params.size() != 1 || param == null || testingImportSpec == null || !param.getType().textMatches(getProperParamType(testingAlias, type))) { problemsHolder.registerProblem(function.getIdentifier(), "Wrong test signature", new GoTestSignaturesQuickFix(type)); } } } }</code><technical_language>!isEmpty</technical_language>

Target:
protected void checkFile(@NotNull final GoFile file, @NotNull ProblemsHolder problemsHolder) { if (!GoTestFinder.isTestFile(file)) return; GoImportSpec testingImportSpec = file.getImportedPackagesMap().get(GoConstants.TESTING_PATH); String testingAlias = getTestingAlias(testingImportSpec); for (GoFunctionDeclaration function : file.getFunctions()) { GoTestFunctionType type = GoTestFunctionType.fromName(function.getName()); if (type == null) continue; GoSignature signature = function.getSignature(); if (signature == null) continue; List<GoParameterDeclaration> params = signature.getParameters().getParameterDeclarationList(); if (type == GoTestFunctionType.EXAMPLE) { if (!params.isEmpty()) { problemsHolder.registerProblem(function.getIdentifier(), "Wrong example signature", new GoTestSignaturesQuickFix(type)); } } else { GoParameterDeclaration param = ContainerUtil.getFirstItem(params); if (params.size() != 1 || param == null || testingImportSpec == null || !param.getType().textMatches(getProperParamType(testingAlias, type))) { problemsHolder.registerProblem(function.getIdentifier(), "Wrong test signature", new GoTestSignaturesQuickFix(type)); } } } }
Source:
<code>public void run() { long threadId = Thread.currentThread().getId(); if (webDriver != null) { log.info("Close webdriver: -> {}", threadId, webDriver); if (selenideProxyServer != null) { log.info("Close proxy server: -> {}", threadId, selenideProxyServer); } long start = System.currentTimeMillis(); Thread t = new Thread(new CloseBrowser(webDriver, selenideProxyServer)); t.setDaemon(true); t.start(); try { t.join(); } catch (InterruptedException e) { long duration = System.currentTimeMillis() - start; <START> log.debug("Failed to close webdriver " + threadId + " in " + duration + " ms", e); <END> Thread.currentThread().interrupt(); } long duration = System.currentTimeMillis() - start; log.info("Closed webdriver in ms", threadId, duration); } else if (selenideProxyServer != null) { log.info("Close proxy server: -> {}", threadId, selenideProxyServer); selenideProxyServer.shutdown(); } }</code><technical_language>If message pattern placeholder parameters comma, for logging</technical_language>

Target:
public void run() { long threadId = Thread.currentThread().getId(); if (webDriver != null) { log.info("Close webdriver: -> {}", threadId, webDriver); if (selenideProxyServer != null) { log.info("Close proxy server: -> {}", threadId, selenideProxyServer); } long start = System.currentTimeMillis(); Thread t = new Thread(new CloseBrowser(webDriver, selenideProxyServer)); t.setDaemon(true); t.start(); try { t.join(); } catch (InterruptedException e) { long duration = System.currentTimeMillis() - start; log.debug("Failed to close webdriver in ms", threadId, duration, e); Thread.currentThread().interrupt(); } long duration = System.currentTimeMillis() - start; log.info("Closed webdriver in ms", threadId, duration); } else if (selenideProxyServer != null) { log.info("Close proxy server: -> {}", threadId, selenideProxyServer); selenideProxyServer.shutdown(); } }
Source:
<code>public static Collection<DiskInterface> getDiskHotpluggableInterfaces(Integer osId, Version version) { Pair<Integer, Version> pair = new Pair<Integer, Version>(osId, version); if (getDiskHotpluggableInterfacesMap().containsKey(pair)) { <START> <END> List<String> diskHotpluggableInterfaces = getDiskHotpluggableInterfacesMap().get(pair); Collection<DiskInterface> diskInterfaces = new HashSet<DiskInterface>(); for (String diskHotpluggableInterface : diskHotpluggableInterfaces) { diskInterfaces.add(DiskInterface.valueOf(diskHotpluggableInterface)); } return diskInterfaces; } return Collections.emptyList(); }</code><technical_language>I "get" checking "containsKey", is reason generate hashCode search in map. check "if null" return empty list ...... this is matter of style</technical_language>

Target:
public static Collection<DiskInterface> getDiskHotpluggableInterfaces(Integer osId, Version version) { List<String> diskHotpluggableInterfaces = getDiskHotpluggableInterfacesMap() .get(new Pair<Integer, Version>(osId, version)); if (diskHotpluggableInterfaces == null) { return Collections.emptyList(); } Collection<DiskInterface> diskInterfaces = new HashSet<DiskInterface>(); for (String diskHotpluggableInterface : diskHotpluggableInterfaces) { diskInterfaces.add(DiskInterface.valueOf(diskHotpluggableInterface)); } return diskInterfaces; }
Source:
<code>private void sendDeleteEvent (final Contentlet contentlet) throws DotHibernateException { HibernateUtil.addAsyncCommitListener( () -> { <START> this.isInodeIndexed(contentlet.getInode()); <END> this.contentletSystemEventUtil.pushDeleteEvent(contentlet); }, 1000); }</code><technical_language>If this event is fired a delete operation is **isInodeIndexed** method validating</technical_language>

Target:
private void sendDeleteEvent (final Contentlet contentlet) throws DotHibernateException { HibernateUtil.addAsyncCommitListener( () -> { this.contentletSystemEventUtil.pushDeleteEvent(contentlet); }, 1000); }
Source:
<code>public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); <START> MenuItem item = menu.add(Menu.NONE, MENU_SORT_ID, Menu.FIRST, "Clear completed"); <END> item.setIcon(android.R.drawable.ic_input_delete); return true; }</code><technical_language>localize please :)</technical_language>

Target:
public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem item = menu.add(Menu.NONE, MENU_CLEAR_COMPLETED_ID, Menu.FIRST, this.getString(R.string.gtasks_GTA_clear_completed)); item.setIcon(android.R.drawable.ic_input_delete); return true; }
Source:
<code>public void testProject() { TableScanNode tableScan = tableScan("ts", "orderkey"); PlanNode project = project("project", tableScan, "string", new Cast(new SymbolReference("orderkey"), "STRING")); Map<String, PlanNodeCostEstimate> costs = ImmutableMap.of("ts", cpuCost(1000)); Map<String, PlanNodeStatsEstimate> stats = ImmutableMap.of( "project", statsEstimate(project, 4000), "ts", statsEstimate(tableScan, 1000)); Map<String, Type> types = ImmutableMap.of( "orderkey", BIGINT, "string", VARCHAR); assertCost(project, costs, stats, types) .cpu(1000 + 4000 * OFFSET_AND_IS_NULL_OVERHEAD) .memory(0) .network(0); assertCostEstimatedExchanges(project, costs, stats, types) .cpu(1000 + 4000 * OFFSET_AND_IS_NULL_OVERHEAD) .memory(0) .network(0); assertCostFragmentedPlan(project, costs, stats, types) <START> .cpu(1000 * IS_NULL_OVERHEAD + 4000 * OFFSET_AND_IS_NULL_OVERHEAD) <END> .memory(0) .network(0); assertCostHasUnknownComponentsForUnknownStats(project, types); }</code><technical_language>IS_NULL_OVERHEAD multiplications deserve a separate commit</technical_language>

Target:
public void testProject() { TableScanNode tableScan = tableScan("ts", "orderkey"); PlanNode project = project("project", tableScan, "string", new Cast(new SymbolReference("orderkey"), "STRING")); Map<String, PlanNodeCostEstimate> costs = ImmutableMap.of("ts", cpuCost(1000)); Map<String, PlanNodeStatsEstimate> stats = ImmutableMap.of( "project", statsEstimate(project, 4000), "ts", statsEstimate(tableScan, 1000)); Map<String, Type> types = ImmutableMap.of( "orderkey", BIGINT, "string", VARCHAR); assertCost(project, costs, stats, types) .cpu(1000 + 4000 * OFFSET_AND_IS_NULL_OVERHEAD) .memory(0) .network(0); assertCostEstimatedExchanges(project, costs, stats, types) .cpu(1000 + 4000 * OFFSET_AND_IS_NULL_OVERHEAD) .memory(0) .network(0); assertCostFragmentedPlan(project, costs, stats, types) .cpu(1000 + 4000 * OFFSET_AND_IS_NULL_OVERHEAD) .memory(0) .network(0); assertCostHasUnknownComponentsForUnknownStats(project, types); }
Source:
<code>public AllocateTableWriteIdsResponse allocate_table_write_ids( AllocateTableWriteIdsRequest rqst) throws TException { AllocateTableWriteIdsResponse response = getTxnHandler().allocateTableWriteIds(rqst); if (listeners != null && !listeners.isEmpty()) { MetaStoreListenerNotifier.notifyTxnEvent(listeners, EventType.ALLOC_WRITE_ID, <START> new AllocWriteIdEvent(rqst.getTxnIds(), rqst.getTableName(), this), null, null); <END> } return response; }</code><technical_language>AllocateWriteIdEvent writeIds ensure idempotent behaviour in target apply. pass TxnToWriteId list. Also, regular allocate writeid flow in target. For repl flow, need check if latest allocated writeid > requested writeid, noop. If allocated writeid < requested writeid, throw exception is invalid usage skipped some events</technical_language>

Target:
public AllocateTableWriteIdsResponse allocate_table_write_ids( AllocateTableWriteIdsRequest rqst) throws TException { AllocateTableWriteIdsResponse response = getTxnHandler().allocateTableWriteIds(rqst); if (listeners != null && !listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.ALLOC_WRITE_ID, new AllocWriteIdEvent(response.getTxnToWriteIds(), rqst.getDbName(), rqst.getTableName(), this)); } return response; }
Source:
<code>private List<Event> getDownloadedEvents() { List<Event> downloadedEvents = new ArrayList<>(); List<Event> downloadedEventsWithoutValues = eventStore.querySingleEvents(); TrackedEntityDataValueStore trackedEntityDataValueStore = TrackedEntityDataValueStoreImpl.create(databaseAdapter()); <START> for (Long i = 0L; i < downloadedEventsWithoutValues.size(); ++i) { <END> Event event = downloadedEventsWithoutValues.get(i.intValue()); List<TrackedEntityDataValue> trackedEntityDataValues = trackedEntityDataValueStore.queryTrackedEntityDataValuesByEventUid(event.uid()); List<TrackedEntityDataValue> trackedEntityDataValuesWithNullIdsAndEvents = new ArrayList<>(); for (TrackedEntityDataValue trackedEntityDataValue : trackedEntityDataValues) { trackedEntityDataValuesWithNullIdsAndEvents.add( trackedEntityDataValue.toBuilder().id(null).event(null).build()); } downloadedEvents.add(event.toBuilder() .id(null) .deleted(false) .trackedEntityDataValues(trackedEntityDataValuesWithNullIdsAndEvents).build()); } return downloadedEvents; }</code><technical_language>int i = 0</technical_language>

Target:
private List<Event> getDownloadedEvents() { List<Event> downloadedEvents = new ArrayList<>(); List<Event> downloadedEventsWithoutValues = eventStore.querySingleEvents(); TrackedEntityDataValueStore trackedEntityDataValueStore = TrackedEntityDataValueStoreImpl.create(databaseAdapter()); for (int i = 0; i < downloadedEventsWithoutValues.size(); ++i) { Event event = downloadedEventsWithoutValues.get(i); List<TrackedEntityDataValue> trackedEntityDataValues = trackedEntityDataValueStore.queryTrackedEntityDataValuesByEventUid(event.uid()); List<TrackedEntityDataValue> trackedEntityDataValuesWithNullIdsAndEvents = new ArrayList<>(); for (TrackedEntityDataValue trackedEntityDataValue : trackedEntityDataValues) { trackedEntityDataValuesWithNullIdsAndEvents.add( trackedEntityDataValue.toBuilder().id(null).event(null).build()); } downloadedEvents.add(event.toBuilder() .id(null) .deleted(false) .trackedEntityDataValues(trackedEntityDataValuesWithNullIdsAndEvents).build()); } return downloadedEvents; }
Source:
<code>public Map<String, SystemAdmin> getSystemAdmins(String adminLabel) { return getSystemFactories().entrySet() .stream() .collect(Collectors.toMap(Entry::getKey, systemNameToFactoryEntry -> systemNameToFactoryEntry.getValue() <START> .getAdmin(systemNameToFactoryEntry.getKey(), this, adminLabel))); <END> }</code><technical_language>change other getSystemAdmins() this new label = ""</technical_language>

Target:
public Map<String, SystemAdmin> getSystemAdmins(String adminLabel) { if (systemAdminMap.isEmpty()) { systemAdminMap = getSystemFactories().entrySet() .stream() .collect(Collectors.toMap(Entry::getKey, systemNameToFactoryEntry -> systemNameToFactoryEntry.getValue() .getAdmin(systemNameToFactoryEntry.getKey(), this, adminLabel))); } return systemAdminMap; }
Source:
<code>public static boolean vmDeviceChanged(Guid vmId, VmDeviceGeneralType deviceType, boolean deviceEnabled) { List<VmDevice> vmDevices = dao.getVmDeviceByVmIdAndType(vmId, deviceType); return deviceEnabled == vmDevices.isEmpty(); <START> } <END></code><technical_language>combine methods (pass null device method change db query this field)</technical_language>

Target:
public static boolean vmDeviceChanged(Guid vmId, VmDeviceGeneralType deviceType, boolean deviceEnabled) { return vmDeviceChanged(vmId, null, deviceEnabled); }
Source:
<code>private SpanContext startSpanOptions(SpanContext parentContext, String name, Timestamp timestamp, SpanKind spanKind, Boolean enableTrace, Boolean enableStackTrace) { if (timestamp == null) { timestamp = timestampFactory.now(); } if (spanKind == null) { spanKind = SpanKind.UNSPECIFIED; } if (enableTrace != null || enableStackTrace != null) { TraceOptions options = parentContext.getTraceOptions(); if (enableTrace) { options = options.overrideTraceEnabled(enableTrace); } <START> if (enableStackTrace) { <END> options = options.overrideStackTraceEnabled(enableStackTrace); } parentContext = parentContext.overrideOptions(options); } SpanContext context = spanContextFactory.childContext(parentContext); for (TraceSink sink : sinks) { sink.startSpan(context, parentContext, spanKind, name, timestamp); } return context; }</code><technical_language>allow overriding false? Making this: java if (enableStackTrace != null) applies enableTrace, straightforward. sense enableTrace=true a parent span enableTrace=false a child span</technical_language>

Target:
private SpanContext startSpanOptions(SpanContext parentContext, String name, Timestamp timestamp, SpanKind spanKind, Boolean enableTrace, Boolean enableStackTrace) { if (timestamp == null) { timestamp = timestampFactory.now(); } if (spanKind == null) { spanKind = SpanKind.UNSPECIFIED; } if (enableTrace != null || enableStackTrace != null) { TraceOptions options = parentContext.getTraceOptions(); if (enableTrace != null) { options = options.overrideTraceEnabled(enableTrace); } if (enableStackTrace != null) { options = options.overrideStackTraceEnabled(enableStackTrace); } parentContext = parentContext.overrideOptions(options); } SpanContext context = spanContextFactory.childContext(parentContext); for (TraceSink sink : sinks) { sink.startSpan(context, parentContext, spanKind, name, timestamp); } return context; }
Source:
<code>private void initZoomToolBar() { ZoomToolbar toolbar = new ZoomToolbar(MAXZOOM); wrapper.setRight(toolbar.getToolBar()); toolbar.getZoomlevel().addListener((observeVal, oldVal, newVal) -> { int diffLevel = oldVal.intValue() - newVal.intValue(); zoomLevel = Math.abs(newVal.intValue()); if (diffLevel < 0) { <START> zoom(Math.pow(ZOOMOUTFACTOR, diffLevel * -1)); <END> } else if (diffLevel > 0) { zoom(Math.pow(ZOOMINFACTOR, diffLevel)); } }); }</code><technical_language>duplicate code, a method</technical_language>

Target:
private void initZoomToolBar() { Zoombar toolbar = new Zoombar(MAXZOOM); wrapper.setRight(toolbar.getToolBar()); toolbar.getZoomlevel().addListener((observeVal, oldVal, newVal) -> { int diffLevel = oldVal.intValue() - newVal.intValue(); zoomLevel = Math.abs(newVal.intValue()); if (diffLevel < 0) { zoomGraph(Math.pow(ZOOM_OUT_FACTOR, diffLevel * -1)); } else if (diffLevel > 0) { zoomGraph(Math.pow(ZOOM_IN_FACTOR, diffLevel)); } }); }
Source:
<code>public void listPagedIterableCollectionQueuesFail() throws Exception { MockWebServer server = mockOpenStackServer(); server.enqueue(new MockResponse().setBody(accessRackspace)); server.enqueue(new MockResponse().setResponseCode(404).setBody("")); try { MarconiApi api = api(server.getUrl("/").toString(), "openstack-marconi"); QueueApi queueApi = api.getQueueApiForZoneAndClient("DFW", CLIENT_ID); Queues queues = queueApi.list(ListQueuesOptions.NONE); <START> assertEquals(queues.size(), 0); <END> } finally { server.shutdown(); } }</code><technical_language>assertTrue(queues.isEmpty(), "Expecting empty queues %s", queues)</technical_language>

Target:
public void listPagedIterableCollectionQueuesFail() throws Exception { MockWebServer server = mockOpenStackServer(); server.enqueue(new MockResponse().setBody(accessRackspace)); server.enqueue(new MockResponse().setResponseCode(404)); try { MarconiApi api = api(server.getUrl("/").toString(), "openstack-marconi"); QueueApi queueApi = api.getQueueApiForZoneAndClient("DFW", CLIENT_ID); Queues queues = queueApi.list(ListQueuesOptions.NONE); assertTrue(queues.isEmpty(), "Expecting empty queues but was " + queues.toString()); } finally { server.shutdown(); } }
Source:
<code>public void should_remove_invalid_contact_point() { InetSocketAddress wrongContactPoint = unusedAddress(); <START> <END> Iterator<InetSocketAddress> contactPoints = simulacron.getContactPoints().iterator(); InetSocketAddress address1 = contactPoints.next(); InetSocketAddress address2 = contactPoints.next(); NodeStateListener localNodeStateListener = Mockito.mock(NodeStateListener.class); try (Cluster localCluster = Cluster.builder() .addContactPoint(address1) .addContactPoint(wrongContactPoint) .addNodeStateListeners(localNodeStateListener) .withConfigLoader( new TestConfigLoader( "connection.reconnection-policy.base-delay = 1 hour", "connection.reconnection-policy.max-delay = 1 hour")) .build()) { Map<InetSocketAddress, Node> nodes = localCluster.getMetadata().getNodes(); assertThat(nodes).doesNotContainKey(wrongContactPoint); Node localMetadataNode1 = nodes.get(address1); Node localMetadataNode2 = nodes.get(address2); Mockito.verify(localNodeStateListener, timeout(100)) .onRemove(new DefaultNode(wrongContactPoint)); Mockito.verify(localNodeStateListener, timeout(100)).onUp(localMetadataNode1); Mockito.verify(localNodeStateListener, timeout(100)).onAdd(localMetadataNode2); } }</code><technical_language>a great validate onRemove event (tricky do otherwise)</technical_language>

Target:
public void should_remove_invalid_contact_point() { InetSocketAddress wrongContactPoint = unusedAddress(); Iterator<InetSocketAddress> contactPoints = simulacron.getContactPoints().iterator(); InetSocketAddress address1 = contactPoints.next(); InetSocketAddress address2 = contactPoints.next(); NodeStateListener localNodeStateListener = Mockito.mock(NodeStateListener.class); try (Cluster<CqlSession> localCluster = Cluster.builder() .addContactPoint(address1) .addContactPoint(wrongContactPoint) .addNodeStateListeners(localNodeStateListener) .withConfigLoader( new TestConfigLoader( "connection.reconnection-policy.base-delay = 1 hour", "connection.reconnection-policy.max-delay = 1 hour")) .build()) { Map<InetSocketAddress, Node> nodes = localCluster.getMetadata().getNodes(); assertThat(nodes).doesNotContainKey(wrongContactPoint); Node localMetadataNode1 = nodes.get(address1); Node localMetadataNode2 = nodes.get(address2); Mockito.verify(localNodeStateListener, timeout(100)) .onRemove(new DefaultNode(wrongContactPoint)); Mockito.verify(localNodeStateListener, timeout(100)).onUp(localMetadataNode1); Mockito.verify(localNodeStateListener, timeout(100)).onAdd(localMetadataNode2); } }
Source:
<code>protected void onDestroy() { super.onDestroy(); <START> } <END></code><technical_language>remove useless code</technical_language>

Target:
protected void onDestroy() { EMMessage message = EMChatManager.getInstance().getMessage(msgId); if(message != null){ removeMessage(); } super.onDestroy(); }