auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void executeVdsBrokerCommand() { String volumeName = getParameters().getVolumeName(); VDS vds = vdsDao.get(getParameters().getVdsId()); List<GlusterGlobalVolumeOptionEntity> globalVolumeOptionsList = glusterOptionDao.getGlobalVolumeOptions(vds.getClusterId()); <START> if (!globalVolumeOptionsList.isEmpty()) { <END> for (GlusterGlobalVolumeOptionEntity option : globalVolumeOptionsList) { if (option.getKey().equalsIgnoreCase(getParameters().getVolumeOption().getKey())) { volumeName = "all"; glusterOptionDao.updateGlobalVolumeOption(vds.getClusterId(), getParameters().getVolumeOption().getKey(), getParameters().getVolumeOption().getValue()); break; } } } else { GlusterVolumeGlobalOptionsInfoReturn entity = getBroker().glusterVolumeGlobalOptionsGet(); List<GlusterGlobalVolumeOptionEntity> globalVolumeOptionsListFromVds = entity.globalOptionList(); if (!globalVolumeOptionsListFromVds.isEmpty()) { for (GlusterGlobalVolumeOptionEntity option : globalVolumeOptionsListFromVds) { option.setClusterId(vds.getClusterId()); option.setId(Guid.newGuid()); glusterOptionDao.saveGlobalVolumeOption(option); if (option.getKey().equalsIgnoreCase(getParameters().getVolumeOption().getKey())) { volumeName = "all"; } } } } status = getBroker().glusterVolumeSet(volumeName, getParameters().getVolumeOption().getKey(), getParameters().getVolumeOption().getValue()); proceedProxyReturnValue(); }</code><technical_language>DB updated if setting of option succeeds</technical_language>

Target:
protected void executeVdsBrokerCommand() { String volumeName = getParameters().getVolumeName(); VDS vds = vdsDao.get(getParameters().getVdsId()); List<GlusterGlobalVolumeOptionEntity> globalVolumeOptionsList = glusterOptionDao.getGlobalVolumeOptions(vds.getClusterId()); if (!globalVolumeOptionsList.isEmpty()) { for (GlusterGlobalVolumeOptionEntity option : globalVolumeOptionsList) { if (option.getKey().equalsIgnoreCase(getParameters().getVolumeOption().getKey())) { volumeName = "all"; break; } } } else { GlusterVolumeGlobalOptionsInfoReturn entity = getBroker().glusterVolumeGlobalOptionsGet(); List<GlusterGlobalVolumeOptionEntity> globalVolumeOptionsListFromVds = entity.globalOptionList(); if (!globalVolumeOptionsListFromVds.isEmpty()) { for (GlusterGlobalVolumeOptionEntity option : globalVolumeOptionsListFromVds) { option.setClusterId(vds.getClusterId()); option.setId(Guid.newGuid()); glusterOptionDao.saveGlobalVolumeOption(option); if (option.getKey().equalsIgnoreCase(getParameters().getVolumeOption().getKey())) { volumeName = "all"; } } } } status = getBroker().glusterVolumeSet(volumeName, getParameters().getVolumeOption().getKey(), getParameters().getVolumeOption().getValue()); proceedProxyReturnValue(); }
Source:
<code>public static String getErrorMessage(@NonNull Throwable ex, @NonNull Context context) { String errorMessage = null; if (ex instanceof RetroHttpException) { RetrofitError cause = ((RetroHttpException) ex).getCause(); switch (cause.getKind()) { case NETWORK: { if (NetworkUtil.isConnected(context)) { errorMessage = context.getString(R.string.network_connected_error); } else { errorMessage = context.getString(R.string.reset_no_network_message); } break; } case HTTP: { if (cause.getResponse() != null) { final int status = cause.getResponse().getStatus(); <START> switch (status) { <END> case HttpURLConnection.HTTP_UNAVAILABLE: errorMessage = context.getString(R.string.network_service_unavailable); break; case HttpURLConnection.HTTP_NOT_FOUND: case HttpURLConnection.HTTP_INTERNAL_ERROR: errorMessage = context.getString(R.string.action_not_completed); break; } } } case CONVERSION: case UNEXPECTED: { break; } } } if (null == errorMessage) { logger.error(ex, true ); errorMessage = context.getString(R.string.error_unknown); } return errorMessage; }</code><technical_language>remove variable, replace switch subject method call for conciseness, i.e. switch (cause.getResponse().getStatus())</technical_language>

Target:
public static String getErrorMessage(@NonNull Throwable ex, @NonNull Context context) { String errorMessage = null; if (ex instanceof HttpConnectivityException) { if (NetworkUtil.isConnected(context)) { errorMessage = context.getString(R.string.network_connected_error); } else { errorMessage = context.getString(R.string.reset_no_network_message); } } else if (ex instanceof HttpResponseStatusException) { final int status = ((HttpResponseStatusException) ex).getStatusCode(); switch (status) { case HttpURLConnection.HTTP_UNAVAILABLE: errorMessage = context.getString(R.string.network_service_unavailable); break; case HttpURLConnection.HTTP_NOT_FOUND: case HttpURLConnection.HTTP_INTERNAL_ERROR: errorMessage = context.getString(R.string.action_not_completed); break; } } if (null == errorMessage) { logger.error(ex, true ); errorMessage = context.getString(R.string.error_unknown); } return errorMessage; }
Source:
<code><START> public void Case() { <END> NumberExpression<Float> numExpression = employee.salary.floatValue().divide(employee2.salary.floatValue()).multiply(100); NumberExpression<Float> numExpression2 = employee.id.when(0).then(0.0F).otherwise(numExpression); query().from(employee, employee2).list(numExpression2); }</code><technical_language>This test passes if I revert fix</technical_language>

Target:
public void Case() { NumberExpression<Float> numExpression = employee.salary.floatValue().divide(employee2.salary.floatValue()).multiply(100.1); NumberExpression<Float> numExpression2 = employee.id.when(0).then(0.0F).otherwise(numExpression); assertEquals(ImmutableList.of(87, 90, 88, 87, 83, 80, 75), query().from(employee, employee2) .where(employee.id.eq(employee2.id.add(1))) .orderBy(employee.id.asc(), employee2.id.asc()) .list(numExpression2.floor().intValue())); }
Source:
<code>public Response checkItemAvailability(@PathParam("id") String id) throws IOException { Response response; try (ItemManager itemManager = new ItemManager(); DownloadManager downloadManager = new DownloadManager()) { Item item = itemManager.load(id); if (item == null) { response = Response.status(NOT_FOUND).build(); } else { Download download = downloadManager.load(id); if (download != null) { String persistenceURI = download.getPersistanceURI(); if (download.isProblem()) { <START> response = Response.status(NOT_IMPLEMENTED).build(); <END> } else if (StringUtils.isBlank(persistenceURI)) { response = Response.status(ACCEPTED).build(); } else { if (!downloadManager.downloadFileExistsOnFilesystem(download)) { new DownloadService().delete(id); DownloadUtility.stageAsyncItemDownload(id); response = Response.status(ACCEPTED).build(); } else { response = Response.status(OK).build(); } } } else { DownloadUtility.stageAsyncItemDownload(id); response = Response.status(ACCEPTED).build(); } } } return response; }</code><technical_language>if isProblem necessarily NOT_IMPLEMENTED. I cases is a problem in building download of implemented</technical_language>

Target:
public Response checkItemAvailability(@PathParam("id") String id) throws IOException { Response response; try (ItemManager itemManager = new ItemManager(); DownloadManager downloadManager = new DownloadManager()) { Item item = itemManager.load(id); if (item == null) { response = Response.status(NOT_FOUND).build(); } else { Download download = downloadManager.load(id); if (download != null) { String persistenceURI = download.getPersistanceURI(); if (download.isProblem()) { response = Response.status(INTERNAL_SERVER_ERROR).build(); } else if (StringUtils.isBlank(persistenceURI)) { response = Response.status(ACCEPTED).build(); } else { if (!downloadManager.downloadFileExistsOnFilesystem(download)) { new DownloadService().delete(id); DownloadUtility.stageAsyncItemDownload(id); response = Response.status(ACCEPTED).build(); } else { response = Response.status(OK).build(); } } } else { DownloadUtility.stageAsyncItemDownload(id); response = Response.status(ACCEPTED).build(); } } } return response; }
Source:
<code>public void init(StreamGraph graph, Config config) { MessageStream<String> pageViews = graph.<String, String, String>getInputStream(INPUT_TOPIC, (k, v) -> v); <START> OutputStream<String, String, WindowPane<String, Collection<String>>> outputStream = graph <END> .getOutputStream(OUTPUT_TOPIC, m -> m.getKey().getKey(), m -> new Integer(m.getMessage().size()).toString()); Function<String, String> keyFn = pageView -> new PageView(pageView).getCountry(); pageViews .partitionBy(keyFn) .window(Windows.keyedTumblingWindow(keyFn, Duration.ofSeconds(3))) .sendTo(outputStream); }</code><technical_language>Minor: IMHO a cleaner add a .map window do counting send value. aggregator here? aside, a confusing WindowPane getKey getMessage. rename getWindowKey getWindowContents (or s/Window/Pane)</technical_language>

Target:
public void init(StreamGraph graph, Config config) { MessageStream<String> pageViews = graph.<String, String, String>getInputStream(INPUT_TOPIC, (k, v) -> v); OutputStream<String, String, WindowPane<String, Integer>> outputStream = graph .getOutputStream(OUTPUT_TOPIC, m -> m.getKey().getKey(), m -> m.getMessage().toString()); Function<String, String> keyFn = pageView -> new PageView(pageView).getCountry(); pageViews .partitionBy(keyFn) .window(Windows.keyedTumblingWindow(keyFn, Duration.ofSeconds(3), () -> 0, (m, prevCount) -> prevCount + 1)) .sendTo(outputStream); }
Source:
<code>public ThriftMessageParser(SecorConfig config) throws InstantiationException, IllegalAccessException, ClassNotFoundException { super(config); String factoryClassName = mConfig.getThriftProtocolClass().concat("$Factory"); TProtocolFactory protocolFactory = ((Class<? extends TProtocolFactory>) Class.forName(factoryClassName)).newInstance(); <START> mDeserializer = new TDeserializer(protocolFactory); <END> mThriftPath = new ThriftPath(mConfig.getMessageTimestampName(), (short) mConfig.getMessageTimestampId()); mTimestampType = mConfig.getMessageTimestampType(); }</code><technical_language>This is a new API procotolFactory, is this compatible previous code</technical_language>

Target:
public ThriftMessageParser(SecorConfig config) throws InstantiationException, IllegalAccessException, ClassNotFoundException { super(config); TProtocolFactory protocolFactory = null; String protocolName = mConfig.getThriftProtocolClass(); if (StringUtils.isNotEmpty(protocolName)) { String factoryClassName = protocolName.concat("$Factory"); protocolFactory = ((Class<? extends TProtocolFactory>) Class.forName(factoryClassName)).newInstance(); } else protocolFactory = new TBinaryProtocol.Factory(); mDeserializer = new TDeserializer(protocolFactory); mThriftPath = new ThriftPath(mConfig.getMessageTimestampName(),(short) mConfig.getMessageTimestampId()); mTimestampType = mConfig.getMessageTimestampType(); }
Source:
<code>private void cancel(int id, String paragraphId) { if (livyVersion.isCancelSupported()) { try { LOGGER.info("Cancelling statement " + id); cancelStatement(id); <START> paragraphsToCancel.remove(paragraphId); <END> } catch (LivyException e) { LOGGER.error("Fail to cancel statement " + id + " for paragraph " + paragraphId, e); } } else { LOGGER.warn("cancel is not supported for this version of livy: " + livyVersion); } }</code><technical_language>put in finally block ensure is removed</technical_language>

Target:
private void cancel(int id, String paragraphId) { if (livyVersion.isCancelSupported()) { try { LOGGER.info("Cancelling statement " + id); cancelStatement(id); } catch (LivyException e) { LOGGER.error("Fail to cancel statement " + id + " for paragraph " + paragraphId, e); } finally { paragraphsToCancel.remove(paragraphId); } } else { LOGGER.warn("cancel is not supported for this version of livy: " + livyVersion); paragraphsToCancel.clear(); } }
Source:
<code>private String formatHeadRef(Ref ref) { final String name = ref.getName(); <START> if (name.startsWith(Constants.R_HEADS)) { <END> return name.substring(Constants.R_HEADS.length()); } else if (name.startsWith(Constants.R_REMOTES)) { return name.substring(Constants.R_REMOTES.length()); } return name; }</code><technical_language>please remove brackets</technical_language>

Target:
private String formatHeadRef(Ref ref) { final String name = ref.getName(); if (name.startsWith(Constants.R_HEADS)) return name.substring(Constants.R_HEADS.length()); else if (name.startsWith(Constants.R_REMOTES)) return name.substring(Constants.R_REMOTES.length()); return name; }
Source:
<code>public void canSubscribeIfInvited() throws Exception { <START> System.out.println("\n\n\n***** this test"); <END> Map<String, String> configuration = new HashMap<String, String>(); configuration.put(Conf.ACCESS_MODEL, AccessModel.local.toString()); configuration.put(Conf.DEFAULT_AFFILIATION, Affiliations.member.toString()); Mockito.when(channelManager.getNodeConf(Mockito.anyString())) .thenReturn(configuration); membership = new NodeMembershipImpl(node, jid, Subscriptions.invited, Affiliations.none, null); Mockito.when( channelManager.getNodeMembership(Mockito.anyString(), Mockito.any(JID.class))).thenReturn(membership); subscribe.process(element, new JID("francisco@denmark.lit"), request, null); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.result, response.getType()); Assert.assertEquals(Subscriptions.subscribed, Subscriptions .valueOf(response.getChildElement().element("subscription") .attributeValue("subscription"))); }</code><technical_language>Remove this</technical_language>

Target:
public void canSubscribeIfInvited() throws Exception { Map<String, String> configuration = new HashMap<String, String>(); configuration.put(Conf.ACCESS_MODEL, AccessModel.local.toString()); configuration.put(Conf.DEFAULT_AFFILIATION, Affiliations.member.toString()); Mockito.when(channelManager.getNodeConf(Mockito.anyString())) .thenReturn(configuration); membership = new NodeMembershipImpl(node, jid, Subscriptions.invited, Affiliations.none, null); Mockito.when( channelManager.getNodeMembership(Mockito.anyString(), Mockito.any(JID.class))).thenReturn(membership); subscribe.process(element, new JID("francisco@denmark.lit"), request, null); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.result, response.getType()); Assert.assertEquals(Subscriptions.subscribed, Subscriptions .valueOf(response.getChildElement().element("subscription") .attributeValue("subscription"))); }
Source:
<code>public void testUndo() { <START> if (!hasExecuted) <END> { aDeleteNodeCommand.execute(); } int numOfNodes = aRootNodes.size(); aDeleteNodeCommand.undo(); assertEquals(numOfNodes+1, aRootNodes.size()); try { assertTrue((boolean)aNeedsLayout.get(aGraph)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }</code><technical_language>Tests independent. part of test needs setup a command execute it, undo, test happened</technical_language>

Target:
public void testUndo() { aDeleteNodeCommand.execute(); assertEquals(0, aGraph.getRootNodes().size()); aDeleteNodeCommand.undo(); assertEquals(1, aGraph.getRootNodes().size()); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { List<RepositoryTreeNode> nodes = getSelectedNodes(); try { RevCommit a = getCommit(nodes.get(0)); RevCommit b = getCommit(nodes.get(1)); if (a != null && b != null) { Repository repo = <START> (nodes.get(0).getRepository()); <END> IWorkbenchPage workbenchPage = HandlerUtil .getActiveWorkbenchWindowChecked(event).getActivePage(); if (a.getCommitTime() <= b.getCommitTime()) { compare(workbenchPage, repo, b.getName(), a.getName()); } else { compare(workbenchPage, repo, a.getName(), b.getName()); } } } catch (IOException e) { throw new ExecutionException(e.getLocalizedMessage(), e); } return null; }</code><technical_language>Superfluous parentheses</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { List<RepositoryTreeNode> nodes = getSelectedNodes(); Ref ref1 = getRef(nodes.get(0)); Ref ref2 = getRef(nodes.get(1)); if (ref1 != null && ref2 != null) { Repository repo = (nodes.get(0).getRepository()); IWorkbenchPage workbenchPage = HandlerUtil .getActiveWorkbenchWindowChecked(event).getActivePage(); try { RevCommit a = repo.parseCommit(ref1.getObjectId()); RevCommit b = repo.parseCommit(ref2.getObjectId()); if (a.getCommitTime() <= b.getCommitTime()) { compare(workbenchPage, repo, b.getName(), a.getName()); } else { compare(workbenchPage, repo, a.getName(), b.getName()); } } catch (IOException e) { throw new ExecutionException(e.getLocalizedMessage(), e); } } return null; }
Source:
<code>public AmazonS3 provideAmazonS3Client(AWSCredentials awsCredentials) { if (awsCredentials == null) { <START> InstanceProfileCredentialsProvider iamCredentials = new InstanceProfileCredentialsProvider(true); <END> return new AmazonS3Client(iamCredentials); } return new AmazonS3Client(awsCredentials); }</code><technical_language>experience, new InstanceProfileCredentialsProvider(true) launch a non-daemon background thread refresh credential. caused java process quits cleanly. heads up, if test it, process exit cleanly, ahead. Otherwise, default constructor is good</technical_language>

Target:
public AmazonS3 provideAmazonS3Client(AWSCredentials awsCredentials) { if (awsCredentials == null) { InstanceProfileCredentialsProvider iamCredentials = new InstanceProfileCredentialsProvider(); return new AmazonS3Client(iamCredentials); } return new AmazonS3Client(awsCredentials); }
Source:
<code>public static Optional<Long> getCorporateCardSurchargeFor(AuthCardDetails authCardDetails, ChargeEntity chargeEntity) { if (authCardDetails.isCorporateCard()) { if (isCreditSurcharge(authCardDetails, chargeEntity)) { <START> return Optional.of(chargeEntity.getGatewayAccount().getCorporateCreditCardSurchargeAmount()); <END> } if (isDebitSurcharge(authCardDetails, chargeEntity)) { return Optional.of(chargeEntity.getGatewayAccount().getCorporateDebitCardSurchargeAmount()); } if (isPrepaidCreditSurcharge(authCardDetails, chargeEntity)) { return Optional.of(chargeEntity.getGatewayAccount().getCorporatePrepaidCreditCardSurchargeAmount()); } if (isPrepaidDebitSurcharge(authCardDetails, chargeEntity)) { return Optional.of(chargeEntity.getGatewayAccount().getCorporatePrepaidDebitCardSurchargeAmount()); } } return Optional.empty(); }</code><technical_language>I want rename getCorporateCreditCardSurchargeAmount() getCorporateNonPrepaidCreditCardSurchargeAmount() (and rename getCorporateDebitCardSurchargeAmount() getCorporateNonPrepaidDebitCardSurchargeAmount()) exclusiveness obvious</technical_language>

Target:
public static Optional<Long> getCorporateCardSurchargeFor(AuthCardDetails authCardDetails, ChargeEntity chargeEntity) { long surcharge = FixedCorporateCardSurchargeCalculator.calculate(authCardDetails, chargeEntity); return surcharge > 0 ? Optional.of(surcharge) : Optional.empty(); }
Source:
<code>public Builder withCreatedAt(Date createdAt) { <START> Date dateToAdd = (createdAt == null) <END> ? Const.TIME_REPRESENTS_DEFAULT_TIMESTAMP : createdAt; studentAttributes.setCreatedAt(dateToAdd); return this; }</code><technical_language>I brackets necessary</technical_language>

Target:
public Builder withCreatedAt(Date createdAt) { Date dateToAdd = createdAt == null ? Const.TIME_REPRESENTS_DEFAULT_TIMESTAMP : createdAt; studentAttributes.setCreatedAt(dateToAdd); return this; }
Source:
<code>protected void buildScript(int age, WikiSite wiki) { boolean restBaseEnabled = <START> RbSwitch.INSTANCE.isRestBaseEnabled(WikiSite.forLanguageCode(wiki.languageCode())); <END> if (age == 0) { addPendingClient(new SearchClient()); if (restBaseEnabled) { addPendingClient(new AnnouncementClient()); } } if (restBaseEnabled) { addPendingClient(new AggregatedFeedContentClient()); } addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } }</code><technical_language>Is needed create a new instance of WikiSite passed this method</technical_language>

Target:
protected void buildScript(int age, WikiSite wiki) { boolean restBaseEnabled = RbSwitch.INSTANCE.isRestBaseEnabled(wiki); if (age == 0) { addPendingClient(new SearchClient()); if (restBaseEnabled) { addPendingClient(new AnnouncementClient()); } } if (restBaseEnabled) { addPendingClient(new AggregatedFeedContentClient()); } addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } }
Source:
<code>public void testCompatibility() throws Exception { DocumentModel root = session.getDocument(new PathRef("/")); JsonAssert json = jsonAssert(root, CtxBuilder.enrichDoc("acls").get()); json = json.has("contextParameters").isObject(); json.properties(1); json = json.has("acls").length(1).has(0); json.has("name").isEquals("local"); json.has("aces").isArray(); json.hasNot("ace"); try { <START> harness.deployContrib("org.nuxeo.ecm.permissions", "test-acl-enricher-compat-config.xml"); <END> json = jsonAssert(root, CtxBuilder.enrichDoc("acls").get()); json = json.has("contextParameters").isObject(); json.properties(1); json = json.has("acls").length(1).has(0); json.has("name").isEquals("local"); json.has("aces").isArray(); JsonAssert aces = json.has("ace").get(0); aces.has("username").isText(); aces.has("creator").isNull(); json.has("ace").isArray(); JsonAssert ace = json.has("ace").get(0); ace.has("username").isText(); ace.has("creator").isNull(); } finally { harness.undeployContrib("org.nuxeo.ecm.permissions", "test-acl-enricher-compat-config.xml"); } }</code><technical_language>split test in @LocalDeploy instead of explicit deploy for this part</technical_language>

Target:
public void testCompatibility() throws Exception { DocumentModel root = session.getDocument(new PathRef("/")); JsonAssert json = jsonAssert(root, CtxBuilder.enrichDoc("acls").get()); json = json.has("contextParameters").isObject(); json.properties(1); json = json.has("acls").length(1).has(0); json.has("name").isEquals("local"); json.has("aces").isArray(); JsonAssert aces = json.has("ace").get(0); aces.has("username").isText(); aces.has("creator").isNull(); json.has("ace").isArray(); JsonAssert ace = json.has("ace").get(0); ace.has("username").isText(); ace.has("creator").isNull(); }
Source:
<code>public Collection<Object> getAttributeValues(IAtsObject atsObject, IAttributeType attributeType) throws OseeCoreException { try { Artifact artifact = WorkItemUtil.get(atsObject); Conditions.checkNotNull(artifact, "workItem", "Can't Find Artifact matching " + atsObject.toStringWithId()); <START> return artifact.getAttributeValues(attributeType); <END> } catch (ArtifactDoesNotExist ex) { return Collections.emptyList(); } }</code><technical_language>call throw ArtifactDoesNotExist? WorkItemUtil catch exception call a method throw exceptions artifact DNE</technical_language>

Target:
public Collection<Object> getAttributeValues(IAtsObject atsObject, IAttributeType attributeType) throws OseeCoreException { Artifact artifact = null; try { artifact = WorkItemUtil.get(atsObject); } catch (ArtifactDoesNotExist ex) { return Collections.emptyList(); } Conditions.checkNotNull(artifact, "workItem", "Can't Find Artifact matching " + atsObject.toStringWithId()); return artifact.getAttributeValues(attributeType); }
Source:
<code>public int getLineOfText(final String text) { <START> return TextEditorHandler.getInstance().getLineOfText((ITextEditor)getEditorPart(), text); <END> }</code><technical_language>call getLineOfText(text,0) instead of TextEditorHandler..</technical_language>

Target:
public int getLineOfText(final String text) { return getLineOfText(text, 0); }
Source:
<code>private void createSwitchBody(IDecisionNode switchNode, IConnectorNode mergeNode, IASTStatement body) { if (!(body instanceof IASTCompoundStatement)) return; IASTCompoundStatement comp = (IASTCompoundStatement) body; IBasicBlock prev = switchNode; IConnectorNode savedBreak = outerBreak; outerBreak = mergeNode; for (IASTStatement statement : comp.getStatements()) { if (statement instanceof IASTCaseStatement || statement instanceof IASTDefaultStatement) { IBranchNode lbl = null; if (statement instanceof IASTCaseStatement) { lbl = factory.createBranchNode(statement); } else if (statement instanceof IASTDefaultStatement) { lbl = factory.createBranchNode(IBranchNode.DEFAULT); } if (!(prev instanceof IExitNode) && prev != switchNode) { IConnectorNode here = factory.createConnectorNode(); addJump(prev, here); addOutgoing(lbl, here); prev = here; } else { prev = lbl; } addOutgoing(switchNode, lbl); continue; } IBasicBlock last = createSubGraph(prev, statement); prev = last; } <START> outerBreak = savedBreak; <END> addJump(prev, mergeNode); }</code><technical_language>I put in finally block, in case messed in middle, want leave global state clean</technical_language>

Target:
private void createSwitchBody(IDecisionNode switchNode, IConnectorNode mergeNode, IASTStatement body) { if (!(body instanceof IASTCompoundStatement)) return; IASTCompoundStatement comp = (IASTCompoundStatement) body; IBasicBlock prev = switchNode; IConnectorNode savedBreak = outerBreak; outerBreak = mergeNode; try { for (IASTStatement statement : comp.getStatements()) { if (statement instanceof IASTCaseStatement || statement instanceof IASTDefaultStatement) { IBranchNode lbl = null; if (statement instanceof IASTCaseStatement) { lbl = factory.createBranchNode(statement); } else if (statement instanceof IASTDefaultStatement) { lbl = factory.createBranchNode(IBranchNode.DEFAULT); } if (!(prev instanceof IExitNode) && prev != switchNode) { IConnectorNode here = factory.createConnectorNode(); addJump(prev, here); addOutgoing(lbl, here); prev = here; } else { prev = lbl; } addOutgoing(switchNode, lbl); continue; } prev = createSubGraph(prev, statement); } } finally { outerBreak = savedBreak; } addJump(prev, mergeNode); }
Source:
<code>public synchronized void requestStop() { LOGGER.info(description + " requestStop() called (in state: " + state + ")"); <START> if (state == RunState.RUNNING) { <END> this.state = RunState.REQUEST_STOP; } }</code><technical_language>if (keepGoing())</technical_language>

Target:
public synchronized void requestStop() { LOGGER.info(description + " requestStop() called (in state: " + state + ")"); if (isRunning()) { this.state = RunState.REQUEST_STOP; } }
Source:
<code>public void prepareInternalPool() { try { this.internalPool.preparePool(); } catch (Exception e) { <START> logger.warn("failed to initialize minIdle connections in the internal jedis connection pool", e); <END> } }</code><technical_language>Please change: - Capitalize beginning of sentence. - Remove jedis. This is a generic class (Pool<T>) T Jedis. suggestion logger.warn("Could initialize minimum number of idle resources", e);</technical_language>

Target:
public void prepareInternalPool() { try { this.internalPool.preparePool(); } catch (Exception e) { logger.warn("Could not initialize minimum number of idle resources", e); } }
Source:
<code>public static Long getOldestTimestamp(String zookeepers, String zkPath) { Long oldestTs = Long.MAX_VALUE; boolean nodeFound = false; ZooKeeper zk; try { <START> zk = new ZooKeeper(zookeepers, 30000, null); <END> } catch (IOException e) { throw new IllegalStateException(e); } String tsRootPath = ZookeeperConstants.transactorTsRoot(zkPath); try { if (zk.exists(tsRootPath, false) != null) { for (String child : zk.getChildren(tsRootPath, false)) { Long ts = LongUtil.fromByteArray(zk.getData(tsRootPath+"/"+child, false, null)); nodeFound = true; if (ts < oldestTs) { oldestTs = ts; } } } } catch (Exception e) { log.error("Failed to get oldest timestamp of transactors from Zookeeper"); e.printStackTrace(); return OLDEST_POSSIBLE; } if (nodeFound == false) { try { byte[] d = zk.getData(ZookeeperConstants.oracleCurrentTimestampPath(zkPath), false, null); oldestTs = LongUtil.fromByteArray(d); nodeFound = true; } catch (KeeperException | InterruptedException e) { log.error("Failed to get oldest timestamp of Oracle from Zookeeper"); e.printStackTrace(); return OLDEST_POSSIBLE; } } if (!nodeFound) { return OLDEST_POSSIBLE; } return oldestTs; }</code><technical_language>need close this zookeeper</technical_language>

Target:
public static long getOldestTimestamp(String zookeepers, String zkPath) { long oldestTs = Long.MAX_VALUE; boolean nodeFound = false; ZooKeeper zk = null; try { zk = new ZooKeeper(zookeepers, 30000, null); String tsRootPath = ZookeeperConstants.transactorTsRoot(zkPath); try { if (zk.exists(tsRootPath, false) != null) { for (String child : zk.getChildren(tsRootPath, false)) { Long ts = LongUtil.fromByteArray(zk.getData(tsRootPath+"/"+child, false, null)); nodeFound = true; if (ts < oldestTs) { oldestTs = ts; } } } } catch (Exception e) { log.error("Failed to get oldest timestamp of transactors from Zookeeper", e); return OLDEST_POSSIBLE; } if (nodeFound == false) { try { byte[] d = zk.getData(ZookeeperConstants.oracleCurrentTimestampPath(zkPath), false, null); oldestTs = LongUtil.fromByteArray(d); nodeFound = true; } catch (KeeperException | InterruptedException e) { log.error("Failed to get oldest timestamp of Oracle from Zookeeper", e); return OLDEST_POSSIBLE; } } if (!nodeFound) { return OLDEST_POSSIBLE; } return oldestTs; } catch (IOException e) { throw new IllegalStateException(e); } finally { if (zk != null) { try { zk.close(); } catch (InterruptedException e) { log.error("Failed to close zookeeper client", e); } } } }
Source:
<code>public void testValidateSetAnswer_sameValues_shouldReturnTrue() { String testValue = "Hello World"; String emptyString = ""; FeedbackTextResponseDetails feedbackTextResponseDetails = new FeedbackTextResponseDetails(); <START> assertEquals(feedbackTextResponseDetails.getAnswerString(), <END> SanitizationHelper.sanitizeForRichText(emptyString)); feedbackTextResponseDetails.setAnswer(testValue); assertEquals(feedbackTextResponseDetails.getAnswerString(), SanitizationHelper.sanitizeForRichText(testValue)); }</code><technical_language>clearer for testing (the function setAnswer), test initial testValue i.e. suggestion assertNotEquals(feedbackTextResponseDetails.getAnswerString(), SanitizationHelper.sanitizeForRichText(testValue));</technical_language>

Target:
public void testValidateSetAnswer_sameValues_shouldReturnTrue() { String testValue = "Hello World"; FeedbackTextResponseDetails feedbackTextResponseDetails = new FeedbackTextResponseDetails(); assertNotEquals(feedbackTextResponseDetails.getAnswerString(), SanitizationHelper.sanitizeForRichText(testValue)); feedbackTextResponseDetails.setAnswer(testValue); assertEquals(feedbackTextResponseDetails.getAnswerString(), SanitizationHelper.sanitizeForRichText(testValue)); }
Source:
<code>protected void applyMutation(Mutation uncastMutation) { AssociatedMutation mutation = (AssociatedMutation) uncastMutation; MutatableCode mutatableCode = mutation.mutatableCode; generateCachedNewInstanceInsns(mutatableCode); MInsn newInstanceInsnInCache = newInstanceCachedInsns.get(mutation.newInstanceToChangeIdx); long typeIdx = newInstanceInsnInCache.insn.vregB; <START> newInstanceInsnInCache.insn.vregB = mutation.newInstanceTypeIdx; <END> Log.info("Changed " + typeIdx + " to " + mutation.newInstanceTypeIdx); stats.incrementStat("Changed new instance."); newInstanceCachedInsns = null; }</code><technical_language>note now, changing non-registers in a bit sloppy way. This setPoolIndex() casting format ContainsPoolIndex. For constants changed, this setConst() casting format ContainsConst. is wrong, style of original code</technical_language>

Target:
protected void applyMutation(Mutation uncastMutation) { AssociatedMutation mutation = (AssociatedMutation) uncastMutation; MutatableCode mutatableCode = mutation.mutatableCode; generateCachedNewInstanceInsns(mutatableCode); MInsn newInstanceInsn = newInstanceCachedInsns.get(mutation.newInstanceToChangeIdx); long oldTypeIdx = ((ContainsPoolIndex)newInstanceInsn.insn.info.format).getPoolIndex(newInstanceInsn.insn); ((ContainsPoolIndex)newInstanceInsn.insn.info.format). setPoolIndex(newInstanceInsn.insn, mutation.newInstanceTypeIdx); Log.info("Changed " + oldTypeIdx + " to " + mutation.newInstanceTypeIdx); stats.incrementStat("Changed new instance."); newInstanceCachedInsns = null; }
Source:
<code>public Optional<SymbolicValue> getValueForOwnProperty(String name) { <START> Constraint constraint = type.builtInProperties().getOwnPropertiesConstraints().get(name); <END> if (constraint != null) { return Optional.of(new SymbolicValueWithConstraint(constraint)); } SymbolicValue value = type.builtInProperties().getOwnMethods().get(name); if (value != null) { return Optional.of(value); } return Optional.empty(); }</code><technical_language>@vilchik-elena This duplication BuiltInProperties shows is wrong</technical_language>

Target:
public Optional<SymbolicValue> getValueForOwnProperty(String name) { return type.getValueForOwnProperty(name); }
Source:
<code>public static String getValue(Object obj, String field, final String defaultValue) { BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext(); String valueToReturn = defaultValue; if (TranslationConsiderationContext.hasTranslation() && <START> !requestContext.getLocale().getDefaultFlag()) { <END> TranslationService translationService = TranslationConsiderationContext.getTranslationService(); Locale locale = requestContext.getJavaLocale(); String translatedValue = translationService.getTranslatedValue(obj, field, locale); if (StringUtils.isNotBlank(translatedValue)) { valueToReturn = translatedValue; } else { valueToReturn = translationService.getDefaultTranslationValue(obj, field, locale, defaultValue); } } return valueToReturn; }</code><technical_language>@Vitalij-Voronkoff thought, I refactor this && localeShouldBeTranslated(requestContext.getLocale()) method, simply return !locale.getDefaultFlag(), give users ability declare en_us & en_gb translated if en_us is default</technical_language>

Target:
public static String getValue(Object obj, String field, final String defaultValue) { BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext(); String valueToReturn = defaultValue; if (TranslationConsiderationContext.hasTranslation()) { TranslationService translationService = TranslationConsiderationContext.getTranslationService(); Locale locale = requestContext.getJavaLocale(); String translatedValue = translationService.getTranslatedValue(obj, field, locale); if (StringUtils.isNotBlank(translatedValue)) { valueToReturn = translatedValue; } else { valueToReturn = translationService.getDefaultTranslationValue(obj, field, locale, defaultValue); } } return valueToReturn; }
Source:
<code>public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); <START> String login = userSession.getLogin(); <END> HomepageTypes type = valueOf(request.mandatoryParam(PARAM_TYPE)); String componentParameter = request.param(PARAM_COMPONENT); String organizationParameter = request.param(PARAM_ORGANIZATION); try (DbSession dbSession = dbClient.openSession(false)) { String parameter = getHomepageParameter(dbSession, type, componentParameter, organizationParameter); UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, login); checkState(user != null, "User login '%s' cannot be found", login); user.setHomepageType(type.name()); user.setHomepageParameter(parameter); dbClient.userDao().update(dbSession, user); dbSession.commit(); } response.noContent(); }</code><technical_language>suggestion: inline</technical_language>

Target:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); HomepageTypes.Type type = request.mandatoryParamAsEnum(PARAM_TYPE, HomepageTypes.Type.class); String componentParameter = request.param(PARAM_COMPONENT); String organizationParameter = request.param(PARAM_ORGANIZATION); try (DbSession dbSession = dbClient.openSession(false)) { String parameter = getHomepageParameter(dbSession, type, componentParameter, request.param(PARAM_BRANCH), organizationParameter); UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, userSession.getLogin()); checkState(user != null, "User login '%s' cannot be found", userSession.getLogin()); user.setHomepageType(type.name()); user.setHomepageParameter(parameter); dbClient.userDao().update(dbSession, user); dbSession.commit(); } response.noContent(); }
Source:
<code><START> public Boolean usePillPairedTimeAsLastSeen(final Optional<PillHeartBeat> pillStatusOptional, final DateTime pairedDateTime, final DateTime now) { <END> final DateTime lastHeartBeatThreshold = now.minusMinutes(RECENTLY_PAIRED_PILL_UNSEEN_THRESHOLD); if (pillStatusOptional.isPresent()) { if (pillStatusOptional.get().createdAtUTC.isBefore(pairedDateTime)) { return pairedDateTime.isAfter(lastHeartBeatThreshold); } } else if (pairedDateTime.isAfter(lastHeartBeatThreshold)) { return true; } return false; }</code><technical_language>this static</technical_language>

Target:
public static Boolean usePillPairedTimeAsLastSeen(final Optional<PillHeartBeat> pillStatusOptional, final DateTime pairedDateTime, final DateTime now) { final DateTime lastHeartBeatThreshold = now.minusMinutes(RECENTLY_PAIRED_PILL_UNSEEN_THRESHOLD); if (pillStatusOptional.isPresent()) { if (pillStatusOptional.get().createdAtUTC.isBefore(pairedDateTime)) { return pairedDateTime.isAfter(lastHeartBeatThreshold); } } else if (pairedDateTime.isAfter(lastHeartBeatThreshold)) { return true; } return false; }
Source:
<code><START> RemotePartitioningMasterStepBuilder beanFactory(BeanFactory beanFactory) { <END> this.beanFactory = beanFactory; return this; }</code><technical_language>Is a reason this is package private? a fluent builder this feels odd..</technical_language>

Target:
public RemotePartitioningMasterStepBuilder beanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; return this; }
Source:
<code>protected Date convertFromString(final String value) { if ("now()".equalsIgnoreCase(value)) { return new NowDate(); } if ("today()".equalsIgnoreCase(value)) { return new TodayDate(); } if ("yesterday()".equalsIgnoreCase(value)) { return new YesterdayDate(); } <START> if (value.matches("shifted_today(.+)")) { <END> return new ShiftedToday(value); } for (DateTimeFormatter formatter : _dateTimeFormatters) { try { return formatter.parseDateTime(value).toDate(); } catch (Exception e) { } } try { long longValue = Long.parseLong(value); return convertFromNumber(longValue, false); } catch (NumberFormatException e) { } final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S"); format.setTimeZone(TimeZone.getTimeZone(timeZone)); try { return format.parse(value); } catch (ParseException e) { } return null; }</code><technical_language>Consider a null check first, this introduces risk of a NullPointerException</technical_language>

Target:
protected Date convertFromString(final String value) { if (value == null) { return null; } if ("now()".equalsIgnoreCase(value)) { return new NowDate(); } if ("today()".equalsIgnoreCase(value)) { return new TodayDate(); } if ("yesterday()".equalsIgnoreCase(value)) { return new YesterdayDate(); } if (value.matches("shifted_today(.+)")) { return new ShiftedToday(value); } for (DateTimeFormatter formatter : _dateTimeFormatters) { try { return formatter.parseDateTime(value).toDate(); } catch (Exception e) { } } try { long longValue = Long.parseLong(value); return convertFromNumber(longValue, false); } catch (NumberFormatException e) { } final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S"); format.setTimeZone(TimeZone.getTimeZone(timeZone)); try { return format.parse(value); } catch (ParseException e) { } return null; }
Source:
<code><START> private static boolean isValidRange(byte[] startCol, byte[] endCol) { <END> return RangeRequests.isValidRange(false, startCol, endCol); }</code><technical_language>expose this a method, in RangeRequest? delete happily RangeRequests.isValidRange directly</technical_language>

Target:
public static boolean isValidRange(byte[] startCol, byte[] endCol) { return RangeRequests.isContiguousRange(false, startCol, endCol) && !RangeRequests.isExactlyEmptyRange(startCol, endCol); }
Source:
<code>public static Map<String, String> getCustomAttributes(XmlPullParser parser) { Map<String, String> customAttributes = new LinkedHashMap<>(); <START> List<String> standardAttributes = Arrays.asList(new String[] {"xml:lang", "id", "to", "from", "type"}); <END> for (int i = 0; i < parser.getAttributeCount(); i++) { String attributeName = parser.getAttributeName(i); boolean isLangAttribute = "lang".equals(attributeName) && "xml".equals(parser.getAttributePrefix(i)); if (!standardAttributes.contains(attributeName) && !isLangAttribute) { String attributeValue = parser.getAttributeValue(i); customAttributes.put(attributeName, attributeValue); } } return customAttributes; }</code><technical_language>construct this time method is called? is a List? This a static Set</technical_language>

Target:
public static Map<String, String> getCustomAttributes(XmlPullParser parser) { Map<String, String> customAttributes = new LinkedHashMap<>(); for (int i = 0; i < parser.getAttributeCount(); i++) { String attributeName = parser.getAttributeName(i); boolean isLangAttribute = "lang".equals(attributeName) && "xml".equals(parser.getAttributePrefix(i)); if (!Stanza.REGISTERED_ATTRIBUTES.contains(attributeName) && !isLangAttribute) { String attributeValue = parser.getAttributeValue(i); customAttributes.put(attributeName, attributeValue); } } return customAttributes; }
Source:
<code><START> public QueryMessage<Q, I> withMetaData(Map<String, ?> metaData) { <END> return new GenericSubscriptionQueryMessage<>(getDelegate().withMetaData(metaData), getQueryName(), getResponseType(), updateResponseType); }</code><technical_language>Please declare GenericSubscriptionQueryMessage<...> return type</technical_language>

Target:
public GenericSubscriptionQueryMessage<Q, I, U> withMetaData(Map<String, ?> metaData) { return new GenericSubscriptionQueryMessage<>(getDelegate().withMetaData(metaData), getQueryName(), getResponseType(), updateResponseType); }
Source:
<code>public QuerySystemTable(QueryManager queryManager, NodeInfo nodeInfo, TypeManager typeManager) { this.queryManager = queryManager; this.nodeId = nodeInfo.getNodeId(); this.sessionPropertiesType = (MapType) typeManager.getParameterizedType(StandardTypes.MAP, ImmutableList.<TypeSignatureParameter>builder() <START> .add(TypeSignatureParameter.of(createUnboundedVarcharType().getTypeSignature())) <END> .add(TypeSignatureParameter.of(createUnboundedVarcharType().getTypeSignature())) .build()); this.queryTable = tableMetadataBuilder(QUERY_TABLE_NAME) .column("node_id", createUnboundedVarcharType()) .column("query_id", createUnboundedVarcharType()) .column("state", createUnboundedVarcharType()) .column("user", createUnboundedVarcharType()) .column("source", createUnboundedVarcharType()) .column("query", createUnboundedVarcharType()) .column("resource_group_id", new ArrayType(createUnboundedVarcharType())) .column("session_properties", sessionPropertiesType) .column("queued_time_ms", BIGINT) .column("analysis_time_ms", BIGINT) .column("distributed_planning_time_ms", BIGINT) .column("created", TIMESTAMP) .column("started", TIMESTAMP) .column("last_heartbeat", TIMESTAMP) .column("end", TIMESTAMP) .build(); }</code><technical_language>This static</technical_language>

Target:
public QuerySystemTable(QueryManager queryManager, NodeInfo nodeInfo, TypeManager typeManager) { requireNonNull(typeManager, "typeManager is null"); requireNonNull(nodeInfo, "nodeInfo is null"); this.queryManager = requireNonNull(queryManager, "queryManager is null"); this.nodeId = nodeInfo.getNodeId(); this.sessionPropertiesType = (MapType) typeManager.getParameterizedType(StandardTypes.MAP, ImmutableList.<TypeSignatureParameter>builder() .add(TypeSignatureParameter.of(createUnboundedVarcharType().getTypeSignature())) .add(TypeSignatureParameter.of(createUnboundedVarcharType().getTypeSignature())) .build()); this.queryTableMetadata = tableMetadataBuilder(QUERY_TABLE_NAME) .column("node_id", createUnboundedVarcharType()) .column("query_id", createUnboundedVarcharType()) .column("state", createUnboundedVarcharType()) .column("user", createUnboundedVarcharType()) .column("source", createUnboundedVarcharType()) .column("query", createUnboundedVarcharType()) .column("resource_group_id", new ArrayType(createUnboundedVarcharType())) .column("session_properties", sessionPropertiesType) .column("queued_time_ms", BIGINT) .column("analysis_time_ms", BIGINT) .column("distributed_planning_time_ms", BIGINT) .column("created", TIMESTAMP) .column("started", TIMESTAMP) .column("last_heartbeat", TIMESTAMP) .column("end", TIMESTAMP) .build(); }
Source:
<code>private void placeFenceBlocks(Region3i region, boolean placeTorch) { int minX = region.minX(); int maxX = region.maxX(); int minZ = region.minZ(); int maxZ = region.maxZ(); int y = region.minY(); <START> Block block = blockManager.getBlock("Fences:fence.0"); <END> for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { blockEntityRegistry.setBlockForceUpdateEntity(new Vector3i(x, y + 1, z), block); } } if (placeTorch) { block = blockManager.getBlock("Core:Torch.TOP"); blockEntityRegistry.setBlockForceUpdateEntity(new Vector3i(minX, y + 2, minZ), block); blockEntityRegistry.setBlockForceUpdateEntity(new Vector3i(maxX, y + 2, maxZ), block); } }</code><technical_language>this a constant</technical_language>

Target:
private void placeFenceBlocks(Region3i region, boolean placeTorch) { int minX = region.minX(); int maxX = region.maxX(); int minZ = region.minZ(); int maxZ = region.maxZ(); int y = region.minY(); Block block = blockManager.getBlock(Constants.FENCE_BLOCK_URI); for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { blockEntityRegistry.setBlockForceUpdateEntity(new Vector3i(x, y + 1, z), block); } } if (placeTorch) { block = blockManager.getBlock(Constants.TORCH_BLOCK_URI); blockEntityRegistry.setBlockForceUpdateEntity(new Vector3i(minX, y + 2, minZ), block); blockEntityRegistry.setBlockForceUpdateEntity(new Vector3i(maxX, y + 2, maxZ), block); } }