auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void addNewPartition() throws JSONException { TestUtils.TestHardwareLayout testHardwareLayout = new TestUtils.TestHardwareLayout("Alpha"); PartitionLayout partitionLayout = new PartitionLayout(testHardwareLayout.getHardwareLayout()); ClusterMapManager clusterMapManager = new ClusterMapManager(partitionLayout); <START> List<? extends PartitionId> partitionIds = clusterMapManager.getWritablePartitionIds(); <END> assertEquals(partitionIds.size(), 0); clusterMapManager.addNewPartition(testHardwareLayout.getIndependentDisks(6), 100 * 1024 * 1024 * 1024L); partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), 1); PartitionId partitionId = partitionIds.get(0); assertEquals(partitionId.getReplicaIds().size(), 6); }</code><technical_language>List<PartitionId></technical_language>

Target:
public void addNewPartition() throws JSONException { TestUtils.TestHardwareLayout testHardwareLayout = new TestUtils.TestHardwareLayout("Alpha"); PartitionLayout partitionLayout = new PartitionLayout(testHardwareLayout.getHardwareLayout()); ClusterMapManager clusterMapManager = new ClusterMapManager(partitionLayout); List<PartitionId> partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), 0); clusterMapManager.addNewPartition(testHardwareLayout.getIndependentDisks(6), 100 * 1024 * 1024 * 1024L); partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), 1); PartitionId partitionId = partitionIds.get(0); assertEquals(partitionId.getReplicaIds().size(), 6); }
Source:
<code><START> default void check() { <END> checkArgument(SERVICE_NAME_REGEX.matcher(serviceName()).matches(), "Illegal service name format: %s", serviceName()); if (instanceId().isPresent()) { checkArgument(INSTANCE_ID_REGEX.matcher(instanceId().get()).matches(), "Illegal instance id format: %s", instanceId().get()); } checkArgument(VERSION_REGEX.matcher(version()).matches(), "Illegal version format: %s", version()); }</code><technical_language>error messages regexes</technical_language>

Target:
default void check() { checkArgument(SERVICE_NAME_REGEX.matcher(serviceName()).matches(), "Illegal service name format: %s", serviceName()); if (instanceId().isPresent()) { checkArgument(INSTANCE_ID_REGEX.matcher(instanceId().get()).matches(), "Illegal instance id format: %s", instanceId().get()); } checkArgument(isOrderableVersion(version()), "Illegal version format: %s", version()); }
Source:
<code>public Collection<Statement> fetchRdfForEntity(String entityId) throws RetryableException { long start = System.currentTimeMillis(); StatementCollector collector = new StatementCollector(); collectStatementsFromUrl(uris.rdf(entityId), collector); if (collectConstraints) { <START> try (Timer.Context timerContext = rdfFetchTimer.time()) { <END> collectStatementsFromUrl(uris.constraints(entityId), collector); } catch (ContainedException ex) { log.info("Failed to load constraints: {}", ex.getMessage()); } } log.debug("Done in ms", System.currentTimeMillis() - start); return collector.getStatements(); }</code><technical_language>This measure constraints fetching regular fetching. I want measure - i.e. time spent fetching regular data time spent fetching constraints, spent fetchRdfForEntity (yes, I indecisive...). ok of (i.e. granular, method) timing constraints sense me..</technical_language>

Target:
public Collection<Statement> fetchRdfForEntity(String entityId) throws RetryableException { Timer.Context timerContext = rdfFetchTimer.time(); StatementCollector collector = new StatementCollector(); collectStatementsFromUrl(uris.rdf(entityId), collector, rdfFetchTimer); if (collectConstraints) { try { collectStatementsFromUrl(uris.constraints(entityId), collector, entityFetchTimer); } catch (ContainedException ex) { log.info("Failed to load constraints: {}", ex.getMessage()); } } log.debug("Done in ms", timerContext.stop() / 1000); return collector.getStatements(); }
Source:
<code>public ReadAlarmRegisterResponse getReadAlarmRegisterResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final ReadAlarmRegisterAsyncRequest request) throws OsgpException { LOGGER.info("Incoming RetrieveReadAlarmRegisterRequest for meter: {}", request.getDeviceIdentification()); final ReadAlarmRegisterResponse response = new ReadAlarmRegisterResponse(); try { final MeterResponseData meterResponseData = this.meterResponseDataService.dequeue( <START> request.getCorrelationUid(), AlarmRegister.class); <END> if (meterResponseData != null) { response.setAlarmRegister(this.monitoringMapper.map(meterResponseData.getMessageData(), com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AlarmRegister.class)); } } catch (final FunctionalException e) { throw e; } catch (final Exception e) { LOGGER.error( "Exception: while sending RetrieveReadAlarmRegisterRequest of device: for organisation {}.", new Object[] { e.getMessage(), request.getDeviceIdentification(), organisationIdentification }); this.handleException(e); } return response; }</code><technical_language>In other endpoints I response data retrieved a call related service (here monitoringService). Calling meterResponseDataService obtain response data inconsistent sight. If is reason for this difference, I cleaner if obtaining actual response is treated alike in endpoints</technical_language>

Target:
public ReadAlarmRegisterResponse getReadAlarmRegisterResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final ReadAlarmRegisterAsyncRequest request) throws OsgpException { LOGGER.info("Incoming RetrieveReadAlarmRegisterRequest for meter: {}", request.getDeviceIdentification()); final ReadAlarmRegisterResponse response = new ReadAlarmRegisterResponse(); try { final MeterResponseData meterResponseData = this.monitoringService.dequeueReadAlarmRegisterResponse(request .getCorrelationUid()); response.setAlarmRegister(this.monitoringMapper.map(meterResponseData.getMessageData(), com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AlarmRegister.class)); } catch (final FunctionalException e) { throw e; } catch (final Exception e) { LOGGER.error( "Exception: while sending RetrieveReadAlarmRegisterRequest of device: for organisation {}.", new Object[] { e.getMessage(), request.getDeviceIdentification(), organisationIdentification }); this.handleException(e); } return response; }
Source:
<code>public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getDeadLetterEntityPath(logger, entityType, queueName, topicName, subscriptionName); <START> if (prefetchCount < 1) { <END> throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "prefetchCount (%s) cannot be less than 1.", prefetchCount))); } else if (maxAutoLockRenewalDuration != null && maxAutoLockRenewalDuration.isNegative()) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "maxAutoLockRenewalDuration (%s) cannot be negative.", maxAutoLockRenewalDuration))); } final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, maxAutoLockRenewalDuration); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); }</code><technical_language>amount of duplicated logic amassing is concerning. This is painful a maintenance standpoint</technical_language>

Target:
public ServiceBusReceiverAsyncClient buildAsyncClient() { final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName, queueName); final String entityPath = getDeadLetterEntityPath(logger, entityType, queueName, topicName, subscriptionName); validateAndThrow(prefetchCount, maxAutoLockRenewalDuration); final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer); final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount, maxAutoLockRenewalDuration); return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath, entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose); }
Source:
<code>public ExecutionResult prepareNetworkElementCommand(final IpAssocCommand cmd) { final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); Connect conn; try { conn = getLibvirtUtilitiesHelper().getConnectionByVmName(routerName); Integer devNum = 0; final List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName); final Map<String, Integer> macAddressToNicNum = new HashMap<>(pluggedNics.size()); for (final InterfaceDef pluggedNic : pluggedNics) { final String pluggedVlan = pluggedNic.getBrName(); macAddressToNicNum.put(pluggedNic.getMacAddress(), devNum); <START> devNum++; <END> } final IpAddressTO[] ips = cmd.getIpAddresses(); int nicNum = 0; for (final IpAddressTO ip : ips) { boolean newNic = false; if (!macAddressToNicNum.containsKey(ip.getVifMacAddress())) { VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress()); macAddressToNicNum.put(ip.getVifMacAddress(), devNum++); newNic = true; } nicNum = macAddressToNicNum.get(ip.getVifMacAddress()); networkUsage(routerIp, "addVif", "eth" + nicNum); ip.setNicDevId(nicNum); ip.setNewNic(newNic); } return new ExecutionResult(true, null); } catch (final LibvirtException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } catch (final InternalErrorException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } }</code><technical_language>Duplicated lines (_1797 - 1805_ **=** _1838 - 1847_). please extract a method</technical_language>

Target:
public ExecutionResult prepareNetworkElementCommand(final IpAssocCommand cmd) { final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); Connect conn; try { conn = getLibvirtUtilitiesHelper().getConnectionByVmName(routerName); Pair<Map<String, Integer>, Integer> macAddressToNicNumPair = getMacAddressToNicNumPair(conn, routerName); final Map<String, Integer> macAddressToNicNum = macAddressToNicNumPair.first(); Integer devNum = macAddressToNicNumPair.second(); final IpAddressTO[] ips = cmd.getIpAddresses(); int nicNum = 0; for (final IpAddressTO ip : ips) { boolean newNic = false; if (!macAddressToNicNum.containsKey(ip.getVifMacAddress())) { VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress()); macAddressToNicNum.put(ip.getVifMacAddress(), devNum++); newNic = true; } nicNum = macAddressToNicNum.get(ip.getVifMacAddress()); networkUsage(routerIp, "addVif", "eth" + nicNum); ip.setNicDevId(nicNum); ip.setNewNic(newNic); } return new ExecutionResult(true, null); } catch (final LibvirtException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } catch (final InternalErrorException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } }
Source:
<code><START> public <T extends Component> T createComponent (Class<T> componentType) { <END> try { return componentType.newInstance(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } return null; }</code><technical_language>This is regular Java reflection API, need [Libgdx reflection API](<LINK_1>, break GWT backend. I [this](<LINK_0> in serialization branch, copy it</technical_language>

Target:
public <T extends Component> T createComponent (Class<T> componentType) { try { return ClassReflection.newInstance(componentType); } catch (ReflectionException e) { e.printStackTrace(); } return null; }
Source:
<code>protected int getLatestPacketFailRate() { int failure = 0; int sent = 0; int received = 0; int size = mTcpStats.size(); for (int i = 0; i < size; i++) { <START> long key <END> = mTcpStats.keyAt(i); failure += (mTcpStats.get(key).nLost + mTcpStats.get(key).nRetransmit); sent += mTcpStats.get(key).nSent; received += mTcpStats.get(key).nReceived; } updateSentSinceLastRecv(sent, received); if (getSentSinceLastRecv() < getMinPacketsThreshold()) return 0; int rate = ((sent != 0) ? (failure * 100 / sent) : 0); log("getLatestPacketFailRate:" + rate); return rate; }</code><technical_language>final</technical_language>

Target:
public int getLatestPacketFailRate() { int failure = 0; int sent = 0; int received = 0; int size = mTcpStats.size(); for (int i = 0; i < size; i++) { final long key = mTcpStats.keyAt(i); failure += (mTcpStats.get(key).lostCount + mTcpStats.get(key).retransmitCount); sent += mTcpStats.get(key).sentCount; received += mTcpStats.get(key).receivedCount; } updateSentSinceLastRecv(sent, received); if (getSentSinceLastRecv() < getMinPacketsThreshold()) return 0; int rate = ((sent != 0) ? (failure * 100 / sent) : 0); log("getLatestPacketFailRate:" + rate); return rate; }
Source:
<code>private ApplicationAwareQueryAllocationManager( @Parameter(OverloadedTaskThreshold.class) final double overloadedTaskThreshold <START> ) { <END> this.appTaskListMap = new ConcurrentHashMap<>(); this.modifyTaskListLockMap = new ConcurrentHashMap<>(); this.taskInfoMap = new ConcurrentHashMap<>(); this.overloadedTaskThreshold = overloadedTaskThreshold; }</code><technical_language>please remove new line</technical_language>

Target:
private ApplicationAwareQueryAllocationManager( @Parameter(OverloadedTaskThreshold.class) final double overloadedTaskThreshold) { this.appTaskListMap = new ConcurrentHashMap<>(); this.taskInfoMap = new ConcurrentHashMap<>(); this.overloadedTaskThreshold = overloadedTaskThreshold; }
Source:
<code>public void testPrepareStub() { String[] args = {"--preparestub", getTargetPath("arith_funcs")}; final TaskExecutor executor = Mockito.mock(TaskExecutor.class); final Path stubPath = new File(getTargetPath("arith_funcs")).toPath(); Main mainClass = new Main(executor); exit.expectSystemExitWithStatus(0); exit.checkAssertionAfterwards(new Assertion() { @Override public void checkAssertion() throws Exception { Mockito.verify(executor).prepareStub(stubPath); } }); mainClass.main(args); <START> } <END></code><technical_language>Remove empty line</technical_language>

Target:
public void testPrepareStub() { String[] args = {"prepare-stub", getTargetPath("arith_funcs")}; final Path stubPath = new File(getTargetPath("arith_funcs")).toPath(); exit.expectSystemExitWithStatus(0); exit.checkAssertionAfterwards(new Assertion() { @Override public void checkAssertion() throws Exception { Mockito.verify(executor).prepareStub(stubPath); } }); mainClass.main(args); }
Source:
<code>protected IgniteEx grid(String name) { if (!isRemoteJvm(name)) <START> return (IgniteEx)IgnitionEx.grid(name); <END> else { if (isRemoteJvm()) return IgniteNodeRunner.startedInstance(); else return IgniteProcessProxy.ignite(name); } }</code><technical_language>do need it? I fail if cast IgniteEx test affect sandbox tests, other tests work well. If cast IgniteEx sandbox test rewrite this logic</technical_language>

Target:
protected IgniteEx grid(String name) { if (!isRemoteJvm(name)) return (IgniteEx)G.ignite(name); else { if (isRemoteJvm()) return IgniteNodeRunner.startedInstance(); else return IgniteProcessProxy.ignite(name); } }
Source:
<code>public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); String name = servletConfig.getServletName(); if (httpRegistry == null) { httpRegistry = DefaultHttpRegistry.getHttpRegistry(name); ResteasyCamelServlet existing = httpRegistry.getCamelServlet(name); if (existing != null) { String msg = "Duplicate ServletName detected: " + name + ". Existing: " + existing + " This: " + this.toString() + ". Its advised to use unique ServletName per Camel application."; LOG.info(msg); } httpRegistry.register(this); } for (Map.Entry<String, HttpConsumer> entry : consumers.entrySet()) { String proxyClasses = ((ResteasyComponent)getServletEndpoint(entry.getValue()).getComponent()).getProxyConsumersClasses(); if (proxyClasses != null) { String[] classes = proxyClasses.split(","); LOG.debug("Proxy classes defined in the component {}", Arrays.asList(classes)); for (String clazz : classes) { try { Class realClazz = Class.forName(clazz); InvocationHandler handler = new ResteasyInvocationHandler(); Object proxy = Proxy.newProxyInstance(realClazz.getClassLoader(), new Class[]{realClazz}, handler); getDispatcher().getRegistry().addSingletonResource(proxy); } catch (ClassNotFoundException e) { <START> e.printStackTrace(); <END> } } return; } } }</code><technical_language>Dont ignore exception, log logger fail fast</technical_language>

Target:
public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); String name = servletConfig.getServletName(); if (httpRegistry == null) { httpRegistry = DefaultHttpRegistry.getHttpRegistry(name); HttpRegistryProvider existing = httpRegistry.getCamelServlet(name); if (existing != null) { LOG.info("Duplicate ServletName detected: {}. Existing: This: {}. " + "Its advised to use unique ServletName per Camel application.", name, existing, this.toString()); } httpRegistry.register(this); } for (Map.Entry<String, HttpConsumer> entry : consumers.entrySet()) { String proxyClasses = ((ResteasyComponent)getServletEndpoint(entry.getValue()).getComponent()).getProxyConsumersClasses(); if (proxyClasses != null) { String[] classes = proxyClasses.split(","); LOG.debug("Proxy classes defined in the component {}", Arrays.asList(classes)); for (String clazz : classes) { try { Class realClazz = Class.forName(clazz); InvocationHandler handler = new ResteasyInvocationHandler(); Object proxy = Proxy.newProxyInstance(realClazz.getClassLoader(), new Class[]{realClazz}, handler); getDispatcher().getRegistry().addSingletonResource(proxy); } catch (ClassNotFoundException e) { LOG.error("Error initializing servlet: {}", e); throw new ServletException(e); } } return; } } }
Source:
<code>boolean wouldPushProject(Project.NameKey project) { if (projectMatch != null) { if (projectMatch.endsWith("/*")) { return project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1)); <START> } else { <END> String projectPattern; if (isRE(projectMatch)) { projectPattern = projectMatch.substring(1); } else { projectPattern = projectMatch; } return (new RegExp(projectPattern)).toAutomaton().run(project.get()); } } return true; }</code><technical_language>[optional] remove else save level of indention</technical_language>

Target:
boolean wouldPushProject(Project.NameKey project) { if (projectMatch != null) { if (projectMatch.endsWith("/*")) { return project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1)); } String projectPattern; if (isRE(projectMatch)) { projectPattern = projectMatch.substring(1); } else { projectPattern = projectMatch; } return (new RegExp(projectPattern, RegExp.NONE)). toAutomaton().run(project.get()); } return true; }
Source:
<code>private Account authenticateInternal(HibernateAccount hibernateAccount, PasswordAlgorithm algorithm, String hash, String credentialValue, String credentialName) { verifyCredential(hibernateAccount.getId(), credentialName, algorithm, hash, credentialValue); Account account = unmarshallAccount(hibernateAccount); validateHealthCode(new StudyIdentifierImpl(hibernateAccount.getStudyId()), hibernateAccount, account, false); <START> updateReauthToken(hibernateAccount, account); <END> return account; }</code><technical_language>This updates reauth token password logins. Is this want</technical_language>

Target:
private Account authenticateInternal(HibernateAccount hibernateAccount, PasswordAlgorithm algorithm, String hash, String credentialValue, String credentialName) { verifyCredential(hibernateAccount.getId(), credentialName, algorithm, hash, credentialValue); validateHealthCode(new StudyIdentifierImpl(hibernateAccount.getStudyId()), hibernateAccount, false); Account account = unmarshallAccount(hibernateAccount); updateReauthToken(hibernateAccount, account); return account; }
Source:
<code>public B2Api api(String uri, String provider, Properties overrides) { return ContextBuilder.newBuilder(provider) .credentials("ACCOUNT_ID", "APPLICATION_KEY") .endpoint(uri) .overrides(overrides) .modules(modules) <START> .buildApi(new TypeToken<B2Api>(getClass()) {}); <END> }</code><technical_language>buildApi(B2Api.class);</technical_language>

Target:
public B2Api api(String uri, String provider, Properties overrides) { return ContextBuilder.newBuilder(provider) .credentials("ACCOUNT_ID", "APPLICATION_KEY") .endpoint(uri) .overrides(overrides) .modules(modules) .buildApi(B2Api.class); }
Source:
<code>protected void doStart() throws Exception { client = getConfiguration().getAmazonSQSClient() != null ? getConfiguration().getAmazonSQSClient() : getClient(); if (headerFilterStrategy == null) { headerFilterStrategy = new SqsHeaderFilterStrategy(); } if (configuration.getQueueUrl() != null) { queueUrl = configuration.getQueueUrl(); } else { if (configuration.getRegion() != null && configuration.getQueueOwnerAWSAccountId() != null) { <START> queueUrl = "https://sqs." + configuration.getRegion() + ".amazonaws.com/" <END> + configuration.getQueueOwnerAWSAccountId() + "/" + configuration.getQueueName(); } else if (configuration.getQueueOwnerAWSAccountId() != null) { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(); getQueueUrlRequest.setQueueName(configuration.getQueueName()); getQueueUrlRequest.setQueueOwnerAWSAccountId(configuration.getQueueOwnerAWSAccountId()); GetQueueUrlResult getQueueUrlResult = client.getQueueUrl(getQueueUrlRequest); queueUrl = getQueueUrlResult.getQueueUrl(); } else { ListQueuesResult listQueuesResult = client.listQueues(); for (String url : listQueuesResult.getQueueUrls()) { if (url.endsWith("/" + configuration.getQueueName())) { queueUrl = url; LOG.trace("Queue available at '{}'.", queueUrl); break; } } } } if (queueUrl == null) { createQueue(client); } else { LOG.debug("Using Amazon SQS queue url: {}", queueUrl); updateQueueAttributes(client); } }</code><technical_language>remove host specification? add again</technical_language>

Target:
protected void doStart() throws Exception { client = getConfiguration().getAmazonSQSClient() != null ? getConfiguration().getAmazonSQSClient() : getClient(); if (headerFilterStrategy == null) { headerFilterStrategy = new SqsHeaderFilterStrategy(); } if (configuration.getQueueUrl() != null) { queueUrl = configuration.getQueueUrl(); } else { if (configuration.getRegion() != null && configuration.getQueueOwnerAWSAccountId() != null) { String host = configuration.getAmazonAWSHost(); host = FileUtil.stripTrailingSeparator(host); queueUrl = "https://sqs." + configuration.getRegion() + host + "/" + configuration.getQueueOwnerAWSAccountId() + "/" + configuration.getQueueName(); } else if (configuration.getQueueOwnerAWSAccountId() != null) { GetQueueUrlRequest getQueueUrlRequest = new GetQueueUrlRequest(); getQueueUrlRequest.setQueueName(configuration.getQueueName()); getQueueUrlRequest.setQueueOwnerAWSAccountId(configuration.getQueueOwnerAWSAccountId()); GetQueueUrlResult getQueueUrlResult = client.getQueueUrl(getQueueUrlRequest); queueUrl = getQueueUrlResult.getQueueUrl(); } else { ListQueuesResult listQueuesResult = client.listQueues(); for (String url : listQueuesResult.getQueueUrls()) { if (url.endsWith("/" + configuration.getQueueName())) { queueUrl = url; LOG.trace("Queue available at '{}'.", queueUrl); break; } } } } if (queueUrl == null) { createQueue(client); } else { LOG.debug("Using Amazon SQS queue url: {}", queueUrl); updateQueueAttributes(client); } }
Source:
<code>public Message setToken(Token token) { this.token = token; bytes = null; <START> sent = false; <END> return this; }</code><technical_language>setting Token MID imply = false</technical_language>

Target:
public Message setToken(Token token) { this.token = token; if (bytes != null) { throw new IllegalStateException("already serialized!"); } return this; }
Source:
<code>public void after() { <START> cluster.destroy(); <END> }</code><technical_language>this is enough? Containers, started scheduler, part of cluster. stopped. If I recall correctly, scheduler killed destroy(), schedulers remain running - CLUSTER is annotated @ClassRule, stop() call MesosCluster.after()</technical_language>

Target:
public void after() { DockerContainersUtil util = new DockerContainersUtil(); util.getContainers(false).filterByName(HelloWorldContainer.CONTAINER_NAME_PATTERN).kill().remove(); }
Source:
<code>private void setter(String prop, String ...val) { <START> if (prop.matches("(rotate[XYZ]?|skew[XYZ])")) { <END> map.put(prop, unit(val[0], "deg")); } else if ("scale".equals(prop)) { String x = val.length < 1 ? "1" : val[0]; String y = val.length < 2 ? x : val[1]; map.put(prop, Arrays.asList(x, y)); } else if ("perspective".equals(prop)) { map.put(prop, unit(val[0], "px")); } else if ("x".equals(prop)) { setter("translate", val[0], null); } else if ("y".equals(prop)) { setter("translate", null, val[0]); } else if (prop.matches("(translate[XYZ])")) { map.put(prop, unit(val[0], "px")); } else if ("translate".equals(prop)) { if (map.get("translateX") == null) { map.put("translateX", unit("0", "px")); } if (val[0] != null) { map.put("translateX", unit(val[0], "px")); } if (map.get("translateY") == null) { map.put("translateY", unit("0", "px")); } if (val.length > 1 && val[1] != null) { map.put("translateY", unit(val[1], "px")); } if (map.get("translateZ") == null) { map.put("translateZ", unit("0", "px")); } if (val.length > 2 && val[2] != null) { map.put("translateZ", unit(val[0], "px")); } map.put("translate", Arrays.asList(map.get("translateX").get(0), map.get("translateY").get(0), map.get("translateY").get(0))); } else { map.put(prop, unit(val[0], "")); } }</code><technical_language>a regex defined constant</technical_language>

Target:
private void setter(String prop, String ...val) { if (anglePropRegex.test(prop)) { map.put(prop, unit(val[0], "deg")); } else if ("scale".equals(prop)) { String x = val.length < 1 ? "1" : val[0]; String y = val.length < 2 ? x : val[1]; map.put(prop, Arrays.asList(x, y)); } else if ("perspective".equals(prop)) { map.put(prop, unit(val[0], "px")); } else if (translatePropRegex.test(prop)) { map.put(prop, unit(val[0], "px")); } else if ("translate".equals(prop)) { if (val[0] != null) { map.put("translateX", unit(val[0], "px")); } if (val.length > 1 && val[1] != null) { map.put("translateY", unit(val[1], "px")); } if (has3d && val.length > 2 && val[2] != null) { map.put("translateZ", unit(val[2], "px")); } } else { map.put(prop, Arrays.asList(val)); } }
Source:
<code>public DruidQuery toDruidQuery(final boolean finalizeAggregations) { final DruidQuery subQuery = ((DruidRel) sourceRel).toDruidQuery(true); if (subQuery == null) { return null; } final RowSignature sourceRowSignature = subQuery.getOutputRowSignature(); final GroupByQuery groupByQuery = subQuery.toGroupByQuery(); <START> final DataSource dataSource = groupByQuery == null ? subQuery.getDataSource() : new QueryDataSource(groupByQuery); <END> return partialQuery.build( dataSource, sourceRowSignature, getPlannerContext(), getCluster().getRexBuilder(), finalizeAggregations ); }</code><technical_language>I this is correct. is ignoring subQuery underlying dataSource. means if underlying query is "interesting", a limit, expression, etc, ignored. suggest this instead, return a "nice" null instead of throwing NPE. get understood planner unplannable query. java if (groupByQuery == null) { return null; }</technical_language>

Target:
public DruidQuery toDruidQuery(final boolean finalizeAggregations) { final DruidQuery subQuery = ((DruidRel) sourceRel).toDruidQuery(true); if (subQuery == null) { return null; } final GroupByQuery groupByQuery = subQuery.toGroupByQuery(); if (groupByQuery == null) { throw new CannotBuildQueryException("Subquery could not be converted to GroupBy query"); } final RowSignature sourceRowSignature = subQuery.getOutputRowSignature(); return partialQuery.build( new QueryDataSource(groupByQuery), sourceRowSignature, getPlannerContext(), getCluster().getRexBuilder(), finalizeAggregations ); }
Source:
<code>public void testPolling() throws Exception { AbstractBuild<?, ?> b; PollingResult pr; FreeStyleProject p = createFreeStyleProject(); p.setScm(new MercurialSCM(hgInstallation, repo.getPath(), null, null, null, null, false)); p.setAssignedLabel(null); hg(repo, "init"); touchAndCommit(repo, "f1"); String cs1 = getLastChangesetId(repo); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.INCOMPARABLE, null, null, pr); b = p.scheduleBuild2(0).get(); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.NONE, null, null, pr); touchAndCommit(repo, "f2"); String cs2 = getLastChangesetId(repo); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.SIGNIFICANT, null, null, pr); b.getWorkspace().deleteRecursive(); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.INCOMPARABLE, null, null, pr); b = p.scheduleBuild2(0).get(); touchAndCommit(repo, "f3"); touchAndCommit(repo, "f4"); String cs4 = getLastChangesetId(repo); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.SIGNIFICANT, null, null, pr); touchAndCommit(repo, "f5"); String cs5 = getLastChangesetId(repo); pr = pollSCMChanges(p); <START> assertPollingResult(PollingResult.Change.SIGNIFICANT, null, null, pr); <END> }</code><technical_language>Is intentional this information is lost? (If so, expectedBaselineId expectedRemoteId parameters dropped assertPollingResult null.)</technical_language>

Target:
public void testPolling() throws Exception { AbstractBuild<?, ?> b; PollingResult pr; FreeStyleProject p = createFreeStyleProject(); p.setScm(new MercurialSCM(hgInstallation, repo.getPath(), null, null, null, false, new DefaultBuildChooser(), new SingleBranch(""))); p.setAssignedLabel(null); hg(repo, "init"); touchAndCommit(repo, "f1"); String cs1 = getLastChangesetId(repo); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.INCOMPARABLE, pr); b = p.scheduleBuild2(0).get(); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.NONE, pr); touchAndCommit(repo, "f2"); String cs2 = getLastChangesetId(repo); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.SIGNIFICANT, pr); b.getWorkspace().deleteRecursive(); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.INCOMPARABLE, pr); b = p.scheduleBuild2(0).get(); touchAndCommit(repo, "f3"); touchAndCommit(repo, "f4"); String cs4 = getLastChangesetId(repo); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.SIGNIFICANT, pr); touchAndCommit(repo, "f5"); String cs5 = getLastChangesetId(repo); pr = pollSCMChanges(p); assertPollingResult(PollingResult.Change.SIGNIFICANT, pr); }
Source:
<code>void export(MBeanExporter exporter) { for (Map.Entry<Class<?>, RuleStats> entry : stats.entrySet()) { verify(!entry.getKey().getSimpleName().isEmpty()); String name = ObjectNames.builder(IterativeOptimizer.class) .withProperty("rule", entry.getKey().getSimpleName()) .build(); try { exporter.export(name, entry.getValue()); } <START> catch (Exception e) { <END> throw new RuntimeException(format("Failed to export MBean with name '%s'", name), e); } } }</code><technical_language>undo RuntimeException</technical_language>

Target:
void export(MBeanExporter exporter) { for (Map.Entry<Class<?>, RuleStats> entry : stats.entrySet()) { verify(!entry.getKey().getSimpleName().isEmpty()); String name = ObjectNames.builder(IterativeOptimizer.class) .withProperty("rule", entry.getKey().getSimpleName()) .build(); try { exporter.export(name, entry.getValue()); } catch (RuntimeException e) { throw new RuntimeException(format("Failed to export MBean with name '%s'", name), e); } } }
Source:
<code>private void verifyAccountsAreSame(AccountAttributes student, ShowPageResult result) { PageData data = result.data; student.studentProfile.modifiedDate = data.account.studentProfile.modifiedDate; student.createdAt = data.account.createdAt; <START> student.studentProfile.gender = data.account.studentProfile.gender; <END> assertEquals(student.toString(), data.account.toString()); }</code><technical_language>is this necessary</technical_language>

Target:
private void verifyAccountsAreSame(AccountAttributes student, ShowPageResult result) { PageData data = result.data; student.studentProfile.modifiedDate = data.account.studentProfile.modifiedDate; student.createdAt = data.account.createdAt; assertEquals(student.toString(), data.account.toString()); }
Source:
<code>public void testCompositeViewAction() { <START> CompositeViewAction viewAction = new CompositeViewAction(1, TriggerType.CLICK); <END> assertNotNull(viewAction); viewAction = new CompositeViewAction(1, TriggerType.CLICK_LIST_ITEM); assertNotNull(viewAction); viewAction = new CompositeViewAction(1, TriggerType.LONG_CLICK); assertNotNull(viewAction); viewAction = new CompositeViewAction(1, TriggerType.LONG_CLICK_LIST_ITEM); assertNotNull(viewAction); viewAction = new CompositeViewAction(1, TriggerType.TOUCH); assertNotNull(viewAction); viewAction = new CompositeViewAction(1, TriggerType.TOUCH_DOWN); assertNotNull(viewAction); viewAction = new CompositeViewAction(1, TriggerType.TOUCH_UP); assertNotNull(viewAction); }</code><technical_language>assertNotNull is a basic test, want check values for view_id Trigger Type. need done for Trigger type is happening if want do for TriggerTypes do in a mentioning manually</technical_language>

Target:
public void testCompositeViewAction() { CompositeViewAction viewAction = new CompositeViewAction(1, TriggerType.CLICK); assertNotNull(viewAction); assertEquals(TriggerType.CLICK, viewAction.getTriggerType()); assertEquals(1, viewAction.getViewId()); }
Source:
<code>public boolean hasAllDataAccess(final AuthorizationService.Operation operation) { <START> final List<Permission> permissions = authorizationDbRepository.listAllDataAccess(); <END> final Resource resource = new AllDataAccessResource(ALL_DATA_ACCESS_RESOURCE, ResourceAuthorization.fromPermissionsList(permissions)); return authorizationService.isAuthorized(operation, resource); }</code><technical_language>I remember: planned simple guava cache in this implementation not? I checked - currently reading events endpoint (both hila lola) is called ~25 times/sec</technical_language>

Target:
public boolean hasAllDataAccess(final AuthorizationService.Operation operation) { try { final List<Permission> permissions = resourceCache.get(ALL_DATA_ACCESS_RESOURCE, () -> authorizationDbRepository.listAllDataAccess()); final Resource resource = new AllDataAccessResource(ALL_DATA_ACCESS_RESOURCE, ResourceAuthorization.fromPermissionsList(permissions)); return authorizationService.isAuthorized(operation, resource); } catch (ExecutionException e) { LOG.error("Could not determine whether this application has all data access", e); return false; } }
Source:
<code>public void setCustomEmulatedMachine(String customEmulatedMachine) { <START> this.customEmulatedMachine = ((customEmulatedMachine == null || customEmulatedMachine.length() == 0) ? null : customEmulatedMachine); <END> }</code><technical_language>please trim().isEmpty() instead of length check</technical_language>

Target:
public void setCustomEmulatedMachine(String customEmulatedMachine) { this.customEmulatedMachine = ((customEmulatedMachine == null || customEmulatedMachine.trim().isEmpty()) ? null : customEmulatedMachine); }
Source:
<code>public void updateAttribute(String name, String attributeName, Attribute attribute) throws EntityNotFoundException { Product product = null; try { <START> product = productManager.load(name); <END> } catch (EntityNotFoundException e) { log.warning("The product: " + name + " is not in the database"); throw new APIException(new EntityNotFoundException(Product.class,name, e)); } try { product.updateAttribute(attribute); try { productManager.update(product); } catch (Exception e) { log.warning("Exception but it works "+ e.getMessage()); } } catch (Exception e) { log.warning("Attribute not found : " + attributeName); throw new APIException(new EntityNotFoundException(Metadata.class, "Attribute not found : " + attributeName, attributeName)); } }</code><technical_language>doppel space equal sign</technical_language>

Target:
public void updateAttribute(String name, String attributeName, Attribute attribute) throws APIException { Product product = null; try { product = productManager.load(name); } catch (EntityNotFoundException e) { log.warning("The product: " + name + " is not in the database"); throw new APIException(new EntityNotFoundException(Product.class,name, e)); } try { product.updateAttribute(attribute); try { productManager.update(product); } catch (Exception e) { log.warning("Exception but it works " + e.getMessage()); } } catch (Exception e) { log.warning("Attribute not found : " + attributeName); throw new APIException(new EntityNotFoundException(Metadata.class, "Attribute not found : " + attributeName, attributeName)); } }
Source:
<code>void pushAttribute(long t, Object value, int attributeQuark) throws StateValueTypeException; <START> ITmfStateValue selectivePopAttribute(long <END> t, Object value, int attributeQuark) throws StateValueTypeException; ITmfStateValue popAttribute(long t, int attributeQuark) throws StateValueTypeException; default Object popAttributeObject(long t, int attributeQuark) throws StateValueTypeException { return popAttribute(t, attributeQuark).unboxValue(); }</code><technical_language>Object</technical_language>

Target:
void pushAttribute(long t, Object value, int attributeQuark) throws StateValueTypeException; ITmfStateValue popAttribute(long t, int attributeQuark) throws StateValueTypeException; default Object popAttributeObject(long t, int attributeQuark) throws StateValueTypeException { return popAttribute(t, attributeQuark).unboxValue(); }
Source:
<code>public UserRole[] getAllowedRoles() { <START> return new UserRole[] { UserRole.MANAGER, UserRole.ADMINISTRATOR }; <END> }</code><technical_language>smarter</technical_language>

Target:
public UserRole[] getAllowedRoles() { return new UserRole[] { UserRole.ADMINISTRATOR }; }
Source:
<code>public void rebindPartialActive(CompoundTransformer transformer, String ...objectsToRebindIds) { List<BrooklynObject> objectsToRebind = MutableList.of(); for (String objectId: objectsToRebindIds) { BrooklynObject obj = managementContext.lookup(objectId); <START> if (obj instanceof Entity) obj = Entities.deproxy((Entity)obj); <END> objectsToRebind.add(obj); } rebindPartialActive(transformer, objectsToRebind.iterator()); }</code><technical_language>Do deproxy'ed here? Callers of rebindPartialActive(CompoundTransformer, Iterator<BrooklynObject>) realise pass proxy objects. inclined deproxy'ing happen somehwere in other rebindPartialActive method</technical_language>

Target:
public void rebindPartialActive(CompoundTransformer transformer, String ...objectsToRebindIds) { List<BrooklynObject> objectsToRebind = MutableList.of(); for (String objectId: objectsToRebindIds) { BrooklynObject obj = managementContext.lookup(objectId); objectsToRebind.add(obj); } rebindPartialActive(transformer, objectsToRebind.iterator()); }
Source:
<code>public void execute(String[] args, Console console) { String msg = String.join(" ", args); BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); Collection<ServiceReference<HumanLanguageInterpreter>> refs = null; try { refs = context.getServiceReferences(HumanLanguageInterpreter.class, null); } catch (InvalidSyntaxException e) { } if (refs != null && refs.size() > 0) { try { <START> console.println(context.getService(refs.iterator().next()).interpret(Locale.ENGLISH, msg)); <END> } catch (InterpretationException ie) { console.println(ie.getMessage()); } } else { console.println("No human language interpreter available - tried to interpret: " + msg); } }</code><technical_language>I expect system locale here</technical_language>

Target:
public void execute(String[] args, Console console) { String msg = String.join(" ", args); BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); Collection<ServiceReference<HumanLanguageInterpreter>> refs = null; try { refs = context.getServiceReferences(HumanLanguageInterpreter.class, null); } catch (InvalidSyntaxException e) { } if (refs != null && refs.size() > 0) { try { HumanLanguageInterpreter interpreter = context.getService(refs.iterator().next()); Locale locale = pickLanguage(interpreter.getSupportedLocales()); console.println(interpreter.interpret(locale, msg)); } catch (InterpretationException ie) { console.println(ie.getMessage()); } } else { console.println("No human language interpreter available - tried to interpret: " + msg); } }
Source:
<code>public static String getLocalIpAddress() { InetAddress inetAddress; try { inetAddress = InetAddress.getLocalHost(); <START> if (inetAddress.getAddress()[0] == Byte.MAX_VALUE) { <END> throw new UnknownHostException(String.format("can't resolve non-loopback ip addr for %s, resolved to %s", inetAddress.getHostName(), inetAddress.getHostAddress())); } } catch (UnknownHostException e) { throw Throwables.propagate(e); } return inetAddress.getHostAddress(); }</code><technical_language>I this check is relevant</technical_language>

Target:
public static String getLocalIpAddress() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { LOGGER.error("Unable to determine local hostname, cause: {}", new Object[] {e}); throw Throwables.propagate(e); } }
Source:
<code>protected void deallocate() { for (HAProxyTLV tlv : tlvs) { tlv.release(); } <START> final ResourceLeakTracker<HAProxyMessage> leak = this.leak; <END> if (leak != null) { boolean closed = leak.close(this); assert closed; } }</code><technical_language>put of this in a finally block, in case</technical_language>

Target:
protected void deallocate() { try { for (HAProxyTLV tlv : tlvs) { tlv.release(); } } finally { final ResourceLeakTracker<HAProxyMessage> leak = this.leak; if (leak != null) { boolean closed = leak.close(this); assert closed; } } }
Source:
<code>private String getYouViewId(Channel channel) { for (String alias : channel.getAliasUrls()) { if (alias.contains("youview.com")) { return alias; } } <START> return ""; <END> }</code><technical_language>return emptystring here, is this error case</technical_language>

Target:
private String getYouViewId(Channel channel) { for (String alias : channel.getAliasUrls()) { if (alias.contains("youview.com")) { return alias; } } throw new RuntimeException("Channel " + channel.title() + " does not have a YouView alias (" + channel.toString() + ")"); }
Source:
<code>public void handleResponse(AbstractResponse response) { InitProducerIdResponse initProducerIdResponse = (InitProducerIdResponse) response; Errors error = initProducerIdResponse.error(); if (error == Errors.NONE) { ProducerIdAndEpoch producerIdAndEpoch = new ProducerIdAndEpoch(initProducerIdResponse.data.producerId(), initProducerIdResponse.data.producerEpoch()); setProducerIdAndEpoch(producerIdAndEpoch); if (!isTransactional()) { <START> topicPartitionBookkeeper.startAllSequencesFromBeginning(producerIdAndEpoch); <END> transitionTo(State.READY); } else if (this.isEpochBump) { resetSequenceNumbers(); completeTransaction(); } else { transitionTo(State.READY); lastError = null; } result.done(); } else if (error == Errors.NOT_COORDINATOR || error == Errors.COORDINATOR_NOT_AVAILABLE) { lookupCoordinator(FindCoordinatorRequest.CoordinatorType.TRANSACTION, transactionalId); reenqueue(); } else if (error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.CONCURRENT_TRANSACTIONS) { reenqueue(); } else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED || error == Errors.CLUSTER_AUTHORIZATION_FAILED) { fatalError(error.exception()); } else { fatalError(new KafkaException("Unexpected error in InitProducerIdResponse; " + error.message())); } }</code><technical_language>Ok, this answers of questions above. Do need rewrite inflight batches necessarily? able continue initial sequence numbers, is preferred if avoid introducing duplicates</technical_language>

Target:
public void handleResponse(AbstractResponse response) { InitProducerIdResponse initProducerIdResponse = (InitProducerIdResponse) response; Errors error = initProducerIdResponse.error(); if (error == Errors.NONE) { ProducerIdAndEpoch producerIdAndEpoch = new ProducerIdAndEpoch(initProducerIdResponse.data.producerId(), initProducerIdResponse.data.producerEpoch()); setProducerIdAndEpoch(producerIdAndEpoch); transitionTo(State.READY); lastError = null; if (this.isEpochBump) { resetSequenceNumbers(); } result.done(); } else if (error == Errors.NOT_COORDINATOR || error == Errors.COORDINATOR_NOT_AVAILABLE) { lookupCoordinator(FindCoordinatorRequest.CoordinatorType.TRANSACTION, transactionalId); reenqueue(); } else if (error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.CONCURRENT_TRANSACTIONS) { reenqueue(); } else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED || error == Errors.CLUSTER_AUTHORIZATION_FAILED) { fatalError(error.exception()); } else { fatalError(new KafkaException("Unexpected error in InitProducerIdResponse; " + error.message())); } }
Source:
<code>private void removeRollingOperation(final ZooKeeperClient client, final List<ZooKeeperOperation> operations, final String rollingOpId) { try { try { final RollingOperationStatus status = getRollingOperationStatus(client, rollingOpId); if (status.getState() == ROLLING_OUT) { throw new HeliosRuntimeException( "Please wait for rolling-operation " + rollingOpId + " to finish."); } } catch (RollingOperationDoesNotExistException e) { return; } client.ensurePath(Paths.configRollingOps()); <START> client.ensurePath(Paths.statusRollingOps()); <END> operations.add(delete(Paths.configRollingOp(rollingOpId))); operations.add(delete(Paths.statusRollingOp(rollingOpId))); } catch (final KeeperException e) { throw new HeliosRuntimeException("removing rolling-operation " + rollingOpId + " failed", e); } }</code><technical_language>remove Paths.statusRollingOpsTasks? [same code @gimaker here](<LINK_0> ensure consistency</technical_language>

Target:
private void removeRollingOperation(final ZooKeeperClient client, final List<ZooKeeperOperation> operations, final String rollingOpId) { try { try { final RollingOperationStatus status = getRollingOperationStatus(client, rollingOpId); if (status.getState() == ROLLING_OUT) { throw new HeliosRuntimeException( "Please wait for rolling-operation " + rollingOpId + " to finish."); } } catch (RollingOperationDoesNotExistException e) { return; } client.ensurePath(Paths.configRollingOps()); client.ensurePath(Paths.statusRollingOps()); if (client.exists(Paths.statusRollingOpsTasks(rollingOpId)) != null) { operations.add(delete(Paths.statusRollingOpsTasks(rollingOpId))); } else { operations.add(create(Paths.statusRollingOpsTasks(rollingOpId))); operations.add(delete(Paths.statusRollingOpsTasks(rollingOpId))); } operations.add(delete(Paths.configRollingOp(rollingOpId))); operations.add(delete(Paths.statusRollingOp(rollingOpId))); } catch (final KeeperException e) { throw new HeliosRuntimeException("removing rolling-operation " + rollingOpId + " failed", e); } }