auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected ResourceManager registerInRM(final Credentials credentials, final String rmURL, final String nodeName, final List<Node> nodes) { RMAuthentication auth = joinResourceManager(rmURL); final ResourceManager rm = loginToResourceManager(credentials, auth); if(!disabledMonitoring) { SigarExposer sigarExposer = new SigarExposer(nodeName); final RMAuthentication rmAuth = auth; sigarExposer.boot(auth, false, new PermissionChecker() { @Override public boolean checkPermission(Credentials cred) { ResourceManager rm = null; try { rm = rmAuth.login(cred); if (NB_OF_ADD_NODE_ATTEMPTS == 0) return true; boolean isAdmin = rm.isNodeAdmin(nodes.get(0).getNodeInformation().getURL()) .getBooleanValue(); if (!isAdmin) { throw new SecurityException("Permission denied"); } return true; } catch (LoginException e) { throw new SecurityException(e); } finally { if (rm != null) { rm.disconnect(); } } } }); for (final Node node : nodes) { try { node.setProperty(JMX_URL + JMXTransportProtocol.RMI, sigarExposer.getAddress( JMXTransportProtocol.RMI).toString()); node.setProperty(JMX_URL + JMXTransportProtocol.RO, sigarExposer.getAddress( JMXTransportProtocol.RO).toString()); } catch (Exception e) { logger.error("", e); } } }else { <START> logger.info("The monitoring is disabled!"); <END> } for (final Node node : nodes) { addNodeToResourceManager(rmURL, node, rm); } return rm; }</code><technical_language>"JMX monitoring is disabled."</technical_language>

Target:
protected ResourceManager registerInRM(final Credentials credentials, final String rmURL, final String nodeName, final List<Node> nodes) { RMAuthentication auth = joinResourceManager(rmURL); final ResourceManager rm = loginToResourceManager(credentials, auth); if(!disabledMonitoring) { SigarExposer sigarExposer = new SigarExposer(nodeName); final RMAuthentication rmAuth = auth; sigarExposer.boot(auth, false, new PermissionChecker() { @Override public boolean checkPermission(Credentials cred) { ResourceManager rm = null; try { rm = rmAuth.login(cred); if (NB_OF_ADD_NODE_ATTEMPTS == 0) return true; boolean isAdmin = rm.isNodeAdmin(nodes.get(0).getNodeInformation().getURL()) .getBooleanValue(); if (!isAdmin) { throw new SecurityException("Permission denied"); } return true; } catch (LoginException e) { throw new SecurityException(e); } finally { if (rm != null) { rm.disconnect(); } } } }); for (final Node node : nodes) { try { node.setProperty(JMX_URL + JMXTransportProtocol.RMI, sigarExposer.getAddress( JMXTransportProtocol.RMI).toString()); node.setProperty(JMX_URL + JMXTransportProtocol.RO, sigarExposer.getAddress( JMXTransportProtocol.RO).toString()); } catch (Exception e) { logger.error("", e); } } }else { logger.info("JMX monitoring is disabled."); } for (final Node node : nodes) { addNodeToResourceManager(rmURL, node, rm); } return rm; }
Source:
<code>private void deleteFiles(long endSegment) { int numFiles = 0; long freedBytes = 0; File dir = logDir.toFile(); File[] files = dir.listFiles(file -> { try { String segmentNum = file.getName().split("\\.")[0]; return Long.parseLong(segmentNum) < endSegment; } catch (Exception e) { log.warn("trimPrefix: ignoring file {}", file.getName()); return false; } }); if (files == null) { return; } <START> for (File file : files) { <END> long delta = file.length(); if (!file.delete()) { log.error("deleteFiles: Couldn't delete file {}", file.getName()); } else { freedBytes += delta; numFiles++; } } log.info("deleteFiles: completed, deleted files, freed bytes", numFiles, freedBytes); }</code><technical_language>return type is void</technical_language>

Target:
private void deleteFiles(long endSegment) { int numFiles = 0; long freedBytes = 0; File dir = logDir.toFile(); File[] files = dir.listFiles(file -> { try { String segmentNum = file.getName().split("\\.")[0]; return Long.parseLong(segmentNum) <= endSegment; } catch (Exception e) { log.warn("trimPrefix: ignoring file {}", file.getName()); return false; } }); if (files == null) { return; } for (File file : files) { long delta = file.length(); if (!file.delete()) { log.error("deleteFiles: Couldn't delete file {}", file.getName()); } else { freedBytes += delta; numFiles++; } } log.info("deleteFiles: completed, deleted files, freed bytes", numFiles, freedBytes); }
Source:
<code>protected Object handleRequestMessage(Message<?> message) { Object value = message; if (this.extractPayload) { value = message.getPayload(); } value = SerializerUtil.serialize(value, this.serializerExplicitlySet, this.serializer); <START> String queueName = this.queueNameExpression.getValue(this.evaluationContext, message, String.class); <END> if (this.expectReply) { long uuid = generateRandomUUID(); this.template.boundListOps(queueName).leftPush(SerializerUtil.serialize(uuid+"", this.serializerExplicitlySet, this.serializer)); this.template.boundListOps(uuid + "").leftPush(value); this.boundListOperations = template.boundListOps(uuid + MESSAGESUFFIX); byte[] reply = (byte[]) this.boundListOperations.rightPop(this.timeout, TimeUnit.MILLISECONDS); Object replyMessage = this.serializer.deserialize(reply); if (replyMessage == null) { return null; } return this.getMessageBuilderFactory().withPayload(replyMessage).build(); } else { this.template.boundListOps(queueName).leftPush(value); return null; } }</code><technical_language>No, expression. is a control-queue. fixed configurable property. for name of property different. control-queue, control-list, queue-names-list... @garyrussell</technical_language>

Target:
protected Object handleRequestMessage(Message<?> message) { Object value = message; if (this.extractPayload) { value = message.getPayload(); } if (!(value instanceof byte[])) { if (value instanceof String && !serializerExplicitlySet) { value = stringSerializer.serialize((String) value); } else { value = ((RedisSerializer<Object>) serializer).serialize(value); } } String uuid = defaultIdGenerator.generateId().toString(); byte[] uuidByte; if (!serializerExplicitlySet) { uuidByte = stringSerializer.serialize(uuid); } else { uuidByte = ((RedisSerializer<Object>) serializer).serialize(uuid); } this.template.boundListOps(this.queueName).leftPush(uuidByte); this.template.boundListOps(uuid).leftPush(value); this.boundListOperations = template.boundListOps(uuid + MESSAGESUFFIX); byte[] reply = (byte[]) this.boundListOperations.rightPop(this.timeout, TimeUnit.MILLISECONDS); if(reply != null && reply.length > 0) { Object replyMessage = this.serializer.deserialize(reply); if (replyMessage == null) { return null; } return this.getMessageBuilderFactory().withPayload(replyMessage).build(); } return null; }
Source:
<code>public Password(String password) { <START> super(); <END> this.password = password; }</code><technical_language>remove</technical_language>

Target:
public Password(String password) { this.password = password; }
Source:
<code><START> public abstract FileSegment<T> createFileSegment(Path p) throws IOException; <END> @Override public final Iterator<FileSegment<T>> iterator(){ List<Path> paths = discover(this.path); Iterator<Path> pathsIterator = paths.iterator(); return new Iterator<FileSegment<T>>(){ Path segmentPath; FileSegment<T> segment; @Override public boolean hasNext(){ if (segment != null){ return true; } if (!pathsIterator.hasNext()){ return false; } else { try { Path segmentPath = pathsIterator.next(); segment = createFileSegment(segmentPath); } catch (IOException e){ return false; } } return true; } @Override public FileSegment<T> next() throws NoSuchElementException { if (!hasNext()){ throw new NoSuchElementException("No more file segments to read."); } else { FileSegment<T> seg = segment; segment = null; return seg; } } @Override public void remove(){ throw new UnsupportedOperationException(); } }; }</code><technical_language>Do need this? iterator figure out this itself</technical_language>

Target:
public abstract FileSegment<T> createFileSegment(Path p) throws IOException; @Override public final Iterator<FileSegment<T>> iterator(){ List<Path> paths = discover(this.path); Iterator<Path> pathsIterator = paths.iterator(); return new Iterator<FileSegment<T>>(){ Path segmentPath; FileSegment<T> segment; @Override public boolean hasNext(){ if (segment != null){ return true; } if (!pathsIterator.hasNext()){ return false; } else { try { segmentPath = pathsIterator.next(); segment = createFileSegment(segmentPath); } catch (IOException e){ return false; } } return true; } @Override public FileSegment<T> next() throws NoSuchElementException { if (!hasNext()){ throw new NoSuchElementException("No more file segments to read."); } else { FileSegment<T> seg = segment; segment = null; return seg; } } @Override public void remove(){ throw new UnsupportedOperationException(); } }; }
Source:
<code>public void onDeleted(MatrixConfiguration item) throws IOException { if(activeConfigurations.contains(item)){ <START> LOGGER.warning("Tring of delete active configuration " + item.getDisplayName() + " of job " + getDisplayName() + ". Active configurations should not be deleted."); <END> } else{ configurations.remove(item.getCombination()); } }</code><technical_language>typo</technical_language>

Target:
public void onDeleted(MatrixConfiguration item) throws IOException { if(activeConfigurations.contains(item)){ LOGGER.warning("Trying to delete active configuration " + item.getDisplayName() + " of job " + getDisplayName() + ". Active configurations should not be deleted."); } else{ configurations.remove(item.getCombination()); } }
Source:
<code>private void testClientContext() throws Exception { CountDownLatch serverLatch = new CountDownLatch(1); server.requestHandler(req -> { req.response().end(); } ).listen(ar -> { assertTrue(ar.succeeded()); serverLatch.countDown();; }); awaitLatch(serverLatch); CountDownLatch req1Latch = new CountDownLatch(1); AtomicReference<Context> c = new AtomicReference<>(); HttpClientRequest req1 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/1"); req1.handler(res -> { c.set(Vertx.currentContext()); res.endHandler(v -> req1Latch.countDown()); }); req1.end(); Consumer<HttpClientRequest> checker = req -> { <START> if (req1.connection() == req.connection()) { <END> assertSame(Vertx.currentContext(), c.get()); } else { } }; awaitLatch(req1Latch); CountDownLatch req2Latch = new CountDownLatch(2); HttpClientRequest req2 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/2"); req2.handler(res -> { checker.accept(req2); req2Latch.countDown(); }).exceptionHandler(err -> { fail(err); }).sendHead(); HttpClientRequest req3 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/3"); req3.handler(res -> { checker.accept(req3); req2Latch.countDown(); }).exceptionHandler(err -> { fail(err); }); req3.end(); req2.end(); awaitLatch(req2Latch); vertx.getOrCreateContext().runOnContext(v -> { HttpClientRequest req4 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/4"); req4.handler(res -> { checker.accept(req4); testComplete(); }); req4.exceptionHandler(err -> { fail(err); }); req4.end(); }); await(); }</code><technical_language>OK, this is check context is of connection</technical_language>

Target:
private void testClientContext() throws Exception { CountDownLatch serverLatch = new CountDownLatch(1); server.requestHandler(req -> { req.response().end(); } ).listen(ar -> { assertTrue(ar.succeeded()); serverLatch.countDown();; }); awaitLatch(serverLatch); CountDownLatch req1Latch = new CountDownLatch(1); AtomicReference<Context> c = new AtomicReference<>(); HttpClientRequest req1 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/1"); req1.handler(res -> { c.set(Vertx.currentContext()); res.endHandler(v -> req1Latch.countDown()); }); req1.end(); Consumer<HttpClientRequest> checker = req -> { assertSame(Vertx.currentContext(), c.get()); assertSame(req1.connection(), req.connection()); }; awaitLatch(req1Latch); CountDownLatch req2Latch = new CountDownLatch(2); HttpClientRequest req2 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/2"); req2.handler(res -> { checker.accept(req2); req2Latch.countDown(); }).exceptionHandler(err -> { fail(err); }).sendHead(); HttpClientRequest req3 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/3"); req3.handler(res -> { checker.accept(req3); req2Latch.countDown(); }).exceptionHandler(err -> { fail(err); }); req3.end(); req2.end(); awaitLatch(req2Latch); vertx.getOrCreateContext().runOnContext(v -> { HttpClientRequest req4 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/4"); req4.handler(res -> { checker.accept(req4); testComplete(); }); req4.exceptionHandler(err -> { fail(err); }); req4.end(); }); await(); }
Source:
<code>static CompletableFuture<byte[]> sendrecv( InetSocketAddress local, InetSocketAddress remote, Message query, byte[] data, Duration timeout) { CompletableFuture<byte[]> f = new CompletableFuture<>(); try { startTcp(); long endTime = System.nanoTime() + timeout.toNanos(); ChannelState channel = channelMap.computeIfAbsent( new ChannelKey(local, remote), key -> { try { log.trace("Opening async channel for l={}/r={}", local, remote); SocketChannel c = SocketChannel.open(); c.configureBlocking(false); if (local != null) { c.bind(local); } final ChannelState channelState = new ChannelState(c); <START> c.register(selector, SelectionKey.OP_CONNECT, channelState); <END> c.connect(remote); return channelState; } catch (IOException e) { f.completeExceptionally(e); return null; } }); if (channel != null) { log.trace( "Creating transaction for {}/{}", query.getQuestion().getName(), Type.string(query.getQuestion().getType())); Transaction t = new Transaction(query, data, endTime, channel.channel, f); channel.pendingTransactions.add(t); final SelectionKey selectionKey = channel.channel.keyFor(selector); selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_WRITE); selector.wakeup(); } } catch (IOException e) { f.completeExceptionally(e); } return f; }</code><technical_language>AFAIR this work in a multithreaded scenario. A registration selector selector thread deadlocks</technical_language>

Target:
static CompletableFuture<byte[]> sendrecv( InetSocketAddress local, InetSocketAddress remote, Message query, byte[] data, Duration timeout) { CompletableFuture<byte[]> f = new CompletableFuture<>(); try { startTcp(); long endTime = System.nanoTime() + timeout.toNanos(); ChannelState channel = channelMap.computeIfAbsent( new ChannelKey(local, remote), key -> { try { log.trace("Opening async channel for l={}/r={}", local, remote); SocketChannel c = SocketChannel.open(); c.configureBlocking(false); if (local != null) { c.bind(local); } c.connect(remote); return new ChannelState(c); } catch (IOException e) { f.completeExceptionally(e); return null; } }); if (channel != null) { log.trace( "Creating transaction for {}/{}", query.getQuestion().getName(), Type.string(query.getQuestion().getType())); Transaction t = new Transaction(query, data, endTime, channel.channel, f); channel.pendingTransactions.add(t); registrationQueue.add(channel); selector.wakeup(); } } catch (IOException e) { f.completeExceptionally(e); } return f; }
Source:
<code>public Future<AppSearchBatchResult<String, AppSearchDocument>> getDocuments( @NonNull List<String> uris) { Callable<AppSearchBatchResult<String, AppSearchDocument>> callableTask = () -> { AppSearchBatchResult.Builder<String, AppSearchDocument> resultBuilder = new AppSearchBatchResult.Builder<>(); for (int i = 0; i < uris.size(); i++) { String uri = uris.get(i); try { DocumentProto documentProto = mAppSearchImpl.getDocument(uri); if (documentProto == null) { resultBuilder.setFailure( uri, AppSearchResult.RESULT_NOT_FOUND, null); } else { AppSearchDocument <START> document; <END> try { document = new AppSearchDocument(documentProto); resultBuilder.setSuccess(uri, document); } catch (Throwable t) { resultBuilder.setFailure( uri, AppSearchResult.RESULT_INTERNAL_ERROR, t.getMessage()); } } } catch (Throwable t) { resultBuilder.setResult(uri, throwableToFailedResult(t)); } } return resultBuilder.build(); }; return mExecutor.submit(callableTask); }</code><technical_language>Put definition try</technical_language>

Target:
public Future<AppSearchBatchResult<String, AppSearchDocument>> getDocuments( @NonNull List<String> uris) { Callable<AppSearchBatchResult<String, AppSearchDocument>> callableTask = () -> { AppSearchBatchResult.Builder<String, AppSearchDocument> resultBuilder = new AppSearchBatchResult.Builder<>(); for (int i = 0; i < uris.size(); i++) { String uri = uris.get(i); try { DocumentProto documentProto = mAppSearchImpl.getDocument(uri); if (documentProto == null) { resultBuilder.setFailure( uri, AppSearchResult.RESULT_NOT_FOUND, null); } else { try { AppSearchDocument document = new AppSearchDocument(documentProto); resultBuilder.setSuccess(uri, document); } catch (Throwable t) { resultBuilder.setFailure( uri, AppSearchResult.RESULT_INTERNAL_ERROR, t.getMessage()); } } } catch (Throwable t) { throw throwableToAppSearchException(t); } } return resultBuilder.build(); }; return mExecutor.submit(callableTask); }
Source:
<code>protected String createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); temp.setReadable(true, true); <START> temp.setWritable(true, true); <END> BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.close(); return filePath; }</code><technical_language>insist, is setExecutable method, setReadable setWritable work want. add permissions, remove them. alternative Java 7 is chmod, some native code</technical_language>

Target:
protected String createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); File chmodFile = new File("/usr/bin/chmod"); if (!chmodFile.exists()) { throw new IOException("Can't find the chmod command in order to change the permissions of file \"" + filePath + "\"."); } Process chmodProcess = Runtime.getRuntime().exec(chmodFile.getAbsolutePath() + " 600 " + filePath); try { int chmodExitCode = chmodProcess.waitFor(); if (chmodExitCode != 0) { throw new IOException("Failed to change permissions for file \"" + filePath + "\", the chmod command returns exit code " + chmodExitCode + "\"."); } } catch (InterruptedException ie) { throw new IOException("Failed to change permissions for file \"" + filePath + "\"", ie); } BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.close(); return filePath; }
Source:
<code>private synchronized List<TileLayer> getTileLayers(boolean reload) throws GeoWebCacheException { List<TileLayer> layers = null; WebMapServer wms = null; try { wms = getWMS(); } catch (ServiceException | IOException e) { <START> throw new ConfigurationException("Unable to connect to " + this.url + " :"+e.getMessage(), e); <END> } String wmsUrl = getWMSUrl(wms); log.info("Using " + wmsUrl + " to generate URLs for WMS requests"); String urlVersion = parseVersion(url); layers = getLayers(wms, wmsUrl, urlVersion); if (layers == null || layers.size() < 1) { log.error("Unable to find any layers based on " + url); } else { log.info("Loaded " + layers.size() + " layers from " + url); } return layers; }</code><technical_language>change message ("Unable connect..."? confusing actual error is a parse error instead of a connection issue</technical_language>

Target:
private synchronized List<TileLayer> getTileLayers(boolean reload) throws GeoWebCacheException { List<TileLayer> layers = null; WebMapServer wms = null; try { wms = getWMS(); } catch (ServiceException | IOException e) { throw new ConfigurationException("Could not retrieve (or parse) GetCapaibilities " + this.url + " :"+e.getMessage(), e); } String wmsUrl = getWMSUrl(wms); log.info("Using GetCapabilities " + wmsUrl + " to generate URLs for WMS requests"); String urlVersion = parseVersion(url); layers = getLayers(wms, wmsUrl, urlVersion); if (layers == null || layers.size() < 1) { log.error("Unable to find any layers based on " + url); } else { log.info("Loaded " + layers.size() + " layers from " + url); } return layers; }
Source:
<code>protected void printUsageSummary(PrintStream stderr) { <START> stderr.println(Messages.DisablePluginCommand_PrintUsageSummary()); <END> }</code><technical_language>For printUsageSummary if follow format in LoginCommand LogoutCommand for consistency</technical_language>

Target:
protected void printUsageSummary(PrintStream stderr) { super.printUsageSummary(stderr); stderr.println(Messages.DisablePluginCommand_PrintUsageSummary()); }
Source:
<code>public void run(final int iteration) { <START> final int workload = memoryStore.getElasticStore().getNumUnits(SleepParameters.KEY); <END> final long sleepTime = (long)(workload * computationSpeed); try { Thread.sleep(sleepTime); } catch (final InterruptedException e) { throw new RuntimeException("InterruptedException during sleeping", e); } }</code><technical_language>add a log message iteration number, size of workload, computationSpeed iteration? This authors debug optimizers. (Since computationSpeed change, log once, initialization if preferred.) log this start exit</technical_language>

Target:
public void run(final int iteration) { final int workload = memoryStore.getElasticStore().getNumUnits(SleepParameters.KEY); final long sleepTime = workload * computationRate; LOG.log(Level.INFO, "iteration start: {0}, workload: {1}, computationRate: {2}, sleepTime: {3}", new Object[]{iteration, workload, computationRate, sleepTime}); try { Thread.sleep(sleepTime); } catch (final InterruptedException e) { throw new RuntimeException("InterruptedException during sleeping", e); } final int finWorkload = memoryStore.getElasticStore().getNumUnits(SleepParameters.KEY); LOG.log(Level.INFO, "iteration finish: {0}, finWorkload: {1}", new Object[]{iteration, finWorkload}); }
Source:
<code>void handleDelayedWriteBookieFailure() { <START> final Map<Integer, BookieSocketAddress> CopyDelayedWriteFailedBookies = <END> new HashMap<Integer, BookieSocketAddress>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); handleBookieFailure(CopyDelayedWriteFailedBookies); }</code><technical_language>nit: variable names start a case</technical_language>

Target:
void handleDelayedWriteBookieFailure() { final Map<Integer, BookieSocketAddress> copyDelayedWriteFailedBookies = new HashMap<Integer, BookieSocketAddress>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); handleBookieFailure(copyDelayedWriteFailedBookies); }
Source:
<code>public void testArrayRemoveFunctionDoubleWithInt() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); String tableName = initTables(conn); ResultSet rs; <START> rs = conn.createStatement().executeQuery("SELECT ARRAY_REMOVE(doubles,10) FROM " + tableName + " WHERE region_name = 'SF Bay Area'"); <END> assertTrue(rs.next()); Double[] doubles = new Double[]{23.45,46.345,23.234,45.6,5.78}; Array array = conn.createArrayOf("DOUBLE", doubles); assertEquals(array, rs.getArray(1)); assertFalse(rs.next()); }</code><technical_language>test 10.0 is in array removing a 10 int argument</technical_language>

Target:
public void testArrayRemoveFunctionDoubleWithInt() throws Exception { ResultSet rs = conn.createStatement().executeQuery( "SELECT ARRAY_REMOVE(doubles,10),doubles FROM " + tableName + " WHERE region_name = 'SF Bay Area'"); assertTrue(rs.next()); assertEquals(conn.createArrayOf("DOUBLE", new Double[] { 23.45, 46.345, 23.234, 45.6, 5.78 }), rs.getArray(1)); assertEquals(conn.createArrayOf("DOUBLE", new Double[] { 10.0, 23.45, 46.345, 23.234, 45.6, 5.78 }), rs.getArray(2)); assertFalse(rs.next()); }
Source:
<code>public void setConfigured(boolean configured) { this.configured = configured; <START> } <END></code><technical_language>need for setter</technical_language>

Target:
protected void setConfigured(boolean configured) { this.configured = configured; }
Source:
<code>private String[] updateInstancesAndGetInstanceNames(HelixAdmin dcAdmin, String partitionName, List<ReplicaId> replicaList, boolean sealed) { String[] instances = new String[replicaList.size()]; for (int i = 0; i < replicaList.size(); i++) { Replica replica = (Replica) replicaList.get(i); DataNodeId node = replica.getDataNodeId(); <START> String instanceName = node.getHostname() + "_" + node.getPort(); <END> instances[i] = instanceName; InstanceConfig instanceConfig = dcAdmin.getInstanceConfig(clusterName, instanceName); Map<String, String> diskInfo = instanceConfig.getRecord().getMapField(replica.getMountPath()); String replicasStr = diskInfo.get(REPLICAS_STR); replicasStr += replica.getPartition().getId() + REPLICAS_DELIM_STR; diskInfo.put(REPLICAS_STR, replicasStr); instanceConfig.getRecord().setMapField(replica.getMountPath(), diskInfo); if (sealed) { List<String> currentSealedPartitions = instanceConfig.getRecord().getListField(SEALED_STR); List<String> newSealedPartitionsList = new ArrayList<>(currentSealedPartitions); newSealedPartitionsList.add(partitionName); instanceConfig.getRecord().setListField(SEALED_STR, newSealedPartitionsList); } dcAdmin.setInstanceConfig(clusterName, instanceName, instanceConfig); } return instances; }</code><technical_language>create a private method get instance name based a DataNode</technical_language>

Target:
private String[] updateInstancesAndGetInstanceNames(HelixAdmin dcAdmin, String partitionName, List<ReplicaId> replicaList, boolean sealed) { String[] instances = new String[replicaList.size()]; for (int i = 0; i < replicaList.size(); i++) { Replica replica = (Replica) replicaList.get(i); DataNodeId node = replica.getDataNodeId(); String instanceName = getInstanceName(node); instances[i] = instanceName; InstanceConfig instanceConfig = dcAdmin.getInstanceConfig(clusterName, instanceName); Map<String, String> diskInfo = instanceConfig.getRecord().getMapField(replica.getMountPath()); String replicasStr = diskInfo.get(REPLICAS_STR); replicasStr += replica.getPartition().getId() + REPLICAS_DELIM_STR; diskInfo.put(REPLICAS_STR, replicasStr); instanceConfig.getRecord().setMapField(replica.getMountPath(), diskInfo); if (sealed) { List<String> currentSealedPartitions = instanceConfig.getRecord().getListField(SEALED_STR); List<String> newSealedPartitionsList = new ArrayList<>(currentSealedPartitions); newSealedPartitionsList.add(partitionName); instanceConfig.getRecord().setListField(SEALED_STR, newSealedPartitionsList); } } return instances; }
Source:
<code>public void disconnect() { if (fExplicitConnect) { <START> fHost.close(); <END> } }</code><technical_language>set variable false, close connection once</technical_language>

Target:
public void disconnect() { if (fExplicitConnect) { fHost.close(); fExplicitConnect = false; } }
Source:
<code>public int compareTo(Object obj) { if (this == obj) { return 0; } if (obj == null) { return 1; } if (getClass() != obj.getClass()) { return 1; } RepositoryVersion other = (RepositoryVersion) obj; if (this.major == null || other.major == null) { <START> return this.toString().compareTo(other.toString()); <END> } int erg = this.major - other.major; if (erg != 0) { return erg; } if (this.minor != null && other.minor == null) { return 1; } else if (this.minor == null && other.minor != null) { return -1; } else if (this.minor != null && other.minor != null) { erg = this.minor - other.minor; if (erg != 0) { return erg; } } if (this.micro != null && other.micro == null) { return 1; } else if (this.micro == null && other.micro != null) { return -1; } else if (this.micro != null && other.micro != null) { erg = this.micro - other.micro; if (erg != 0) { return erg; } } if (this.qualifier != null && other.qualifier == null) { if (this.qualifier.equals("+")) { return 1; } else { return -1; } } if (this.qualifier == null && other.qualifier != null) { if (other.qualifier.equals("+")) { return -1; } else { return 1; } } if (this.qualifier != null && other.qualifier != null) { erg = this.qualifier.compareTo(other.qualifier); if (this.qualifier.equals("+") || other.qualifier.equals("+")) { return erg * -1; } if (erg != 0) { return erg; } } return 0; }</code><technical_language>write this this.qualifier.compareTo(other.qualifier) for clarity</technical_language>

Target:
public int compareTo(Object obj) { if (this == obj) { return 0; } if (obj == null) { return 1; } if (getClass() != obj.getClass()) { return 1; } RepositoryVersion other = (RepositoryVersion) obj; if (this.major == null || other.major == null) { return this.orgVersion.compareTo(other.orgVersion); } int erg = this.major - other.major; if (erg != 0) { return erg; } if (this.minor != null && other.minor == null) { return 1; } else if (this.minor == null && other.minor != null) { return -1; } else if (this.minor != null && other.minor != null) { erg = this.minor - other.minor; if (erg != 0) { return erg; } } if (this.micro != null && other.micro == null) { return 1; } else if (this.micro == null && other.micro != null) { return -1; } else if (this.micro != null && other.micro != null) { erg = this.micro - other.micro; if (erg != 0) { return erg; } } if (this.qualifier != null && other.qualifier == null) { return -1; } else if (this.qualifier == null && other.qualifier != null) { return 1; } else if (this.qualifier != null && other.qualifier != null) { return this.qualifier.compareTo(other.qualifier); } return 0; }
Source:
<code>public void run() { try { TERMINATE_MESSAGE_PROCESSING: while (true) { if (Thread.currentThread().isInterrupted()) { Thread.currentThread().interrupt(); break TERMINATE_MESSAGE_PROCESSING; } ControlMessage cm = null; try { while ((cm = controlMessageQueue.take()) != null) { switch (cm.getType()) { case SHUTDOWN: if (LOGGER.isInfoEnabled()) { LOGGER.info("shutdown requested"); } toShutdown = true; abruptShutdown = false; break; case ADD_WORKER: int workerId = cm.getWorkerId(); if (LOGGER.isInfoEnabled()) { LOGGER.info("received ADD_WORKER " + workerId); } connectionPool.putRemote( workerId, SocketInfo.fromProtobuf(cm.getRemoteAddress())); sendMessageToMaster(IPCUtils.addWorkerAckTM(workerId)); break; case SYSTEM_GC: if (LOGGER.isInfoEnabled()) { <START> LOGGER.info("Trigger System GC"); <END> } System.gc(); break; default: if (LOGGER.isErrorEnabled()) { LOGGER.error("Unexpected control message received at worker: " + cm.getType()); } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } catch (Throwable ee) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Unknown exception caught at control message processing.", ee); } } }</code><technical_language>computing here, conditional is necessary..</technical_language>

Target:
public void run() { try { TERMINATE_MESSAGE_PROCESSING: while (true) { if (Thread.currentThread().isInterrupted()) { Thread.currentThread().interrupt(); break TERMINATE_MESSAGE_PROCESSING; } ControlMessage cm = null; try { while ((cm = controlMessageQueue.take()) != null) { switch (cm.getType()) { case SHUTDOWN: if (LOGGER.isInfoEnabled()) { LOGGER.info("shutdown requested"); } toShutdown = true; abruptShutdown = false; break; case ADD_WORKER: int workerId = cm.getWorkerId(); if (LOGGER.isInfoEnabled()) { LOGGER.info("received ADD_WORKER " + workerId); } connectionPool.putRemote( workerId, SocketInfo.fromProtobuf(cm.getRemoteAddress())); sendMessageToMaster(IPCUtils.addWorkerAckTM(workerId)); break; case SYSTEM_GC: if (LOGGER.isDebugEnabled()) { LOGGER.debug("Trigger System GC"); } System.gc(); break; default: if (LOGGER.isErrorEnabled()) { LOGGER.error("Unexpected control message received at worker: " + cm.getType()); } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } catch (Throwable ee) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Unknown exception caught at control message processing.", ee); } } }
Source:
<code><START> public boolean equals(Object obj) { <END> if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } MultiCurrencyValuesArray other = (MultiCurrencyValuesArray) obj; if (values.size() != other.values.size()) { return false; } for (Currency currency : values.keySet()) { double[] currencyValues = values.get(currency); double[] otherCurrencyValues = other.values.get(currency); if (otherCurrencyValues == null) { return false; } if (!Arrays.equals(currencyValues, otherCurrencyValues)) { return false; } } return true; }</code><technical_language>Manual equals/hashCode avoided DoubleArray</technical_language>

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { MultiCurrencyValuesArray other = (MultiCurrencyValuesArray) obj; return JodaBeanUtils.equal(values, other.values) && (size == other.size); } return false; }
Source:
<code><START> public void addStore(PartitionId partitionId, ReplicationTest.StoreEventListener listener) { <END> storesByPartition.computeIfAbsent(partitionId, partitionId1 -> new InMemoryStore(partitionId, infosByPartition.computeIfAbsent(partitionId1, (Function<PartitionId, List<MessageInfo>>) partitionId2 -> new ArrayList<>()), buffersByPartition.computeIfAbsent(partitionId1, (Function<PartitionId, List<ByteBuffer>>) partitionId22 -> new ArrayList<>()), listener)); }</code><technical_language>minor: package private</technical_language>

Target:
void addStore(PartitionId partitionId, ReplicationTest.StoreEventListener listener) { storesByPartition.computeIfAbsent(partitionId, partitionId1 -> new InMemoryStore(partitionId, infosByPartition.computeIfAbsent(partitionId1, (Function<PartitionId, List<MessageInfo>>) partitionId2 -> new ArrayList<>()), buffersByPartition.computeIfAbsent(partitionId1, (Function<PartitionId, List<ByteBuffer>>) partitionId22 -> new ArrayList<>()), listener)); }
Source:
<code>public void onProgress(long transferred, long total) { if (!notificationTitleChanged) { curNotification.setContentTitle(notificationProgressTitle); notificationTitleChanged = true; contribution.setState(Contribution.STATE_IN_PROGRESS); } if (transferred == total) { curNotification.setContentTitle(notificationFinishingTitle) .setTicker(notificationFinishingTitle) .setProgress(0, 100, true); } else { curNotification.setProgress(100, (int) (((double) transferred / (double) total) * 100), false); } notificationManager.notify(notificationTag, NOTIFICATION_UPLOAD_IN_PROGRESS, curNotification.build()); contribution.setTransferred(transferred); <START> ExecutorUtils.get().submit(() -> appDatabase.getContributionDao().save(contribution)); <END> }</code><technical_language>Singles here</technical_language>

Target:
public void onProgress(long transferred, long total) { if (!notificationTitleChanged) { curNotification.setContentTitle(notificationProgressTitle); notificationTitleChanged = true; contribution.setState(Contribution.STATE_IN_PROGRESS); } if (transferred == total) { curNotification.setContentTitle(notificationFinishingTitle) .setTicker(notificationFinishingTitle) .setProgress(0, 100, true); } else { curNotification.setProgress(100, (int) (((double) transferred / (double) total) * 100), false); } notificationManager.notify(notificationTag, NOTIFICATION_UPLOAD_IN_PROGRESS, curNotification.build()); contribution.setTransferred(transferred); compositeDisposable.add(contributionDao. save(contribution).subscribeOn(ioThreadScheduler) .observeOn(mainThreadScheduler) .subscribe()); }
Source:
<code>@Override public void run() { try { while (!isInterrupted()) { ResetReason reason = sceneProvider.awaitSceneStateChange(); synchronized (bufferedScene) { sceneProvider.withSceneProtected(scene -> { if (reason.overwriteState()) { bufferedScene.copyState(scene); } <START> if(reason.reloadMaterials()) { <END> scene.importMaterials(); } bufferedScene.copyTransients(scene); finalizeAllFrames = scene.shouldFinalizeBuffer(); updateRenderState(scene); if (reason == ResetReason.SCENE_LOADED) { bufferedScene.swapBuffers(); sendSceneStatus(bufferedScene.sceneStatus()); } }); } initializeJobQueue(); if (mode == RenderMode.PREVIEW) { previewLoop(); } else { int spp, targetSpp; synchronized (bufferedScene) { spp = bufferedScene.spp; targetSpp = bufferedScene.getTargetSpp(); if (spp < targetSpp) { updateRenderProgress(); } } if (spp < targetSpp) { pathTraceLoop(); } else { sceneProvider.withEditSceneProtected(scene -> { scene.pauseRender(); updateRenderState(scene); }); } } if (headless) { break; } } } catch (InterruptedException e) { } catch (Throwable e) { Log.error("Unchecked exception in render manager", e); } stopWorkers(); }</code><technical_language>Change this if(reason == ResetReason.MATERIALS_CHANGED || reason == ResetReason.SCENE_LOADED). event emitter decide needs reloaded</technical_language>

Target:
@Override public void run() { try { while (!isInterrupted()) { ResetReason reason = sceneProvider.awaitSceneStateChange(); synchronized (bufferedScene) { sceneProvider.withSceneProtected(scene -> { if (reason.overwriteState()) { bufferedScene.copyState(scene); } if(reason == ResetReason.MATERIALS_CHANGED || reason == ResetReason.SCENE_LOADED) { scene.importMaterials(); } bufferedScene.copyTransients(scene); finalizeAllFrames = scene.shouldFinalizeBuffer(); updateRenderState(scene); if (reason == ResetReason.SCENE_LOADED) { bufferedScene.swapBuffers(); sendSceneStatus(bufferedScene.sceneStatus()); } }); } initializeJobQueue(); if (mode == RenderMode.PREVIEW) { previewLoop(); } else { int spp, targetSpp; synchronized (bufferedScene) { spp = bufferedScene.spp; targetSpp = bufferedScene.getTargetSpp(); if (spp < targetSpp) { updateRenderProgress(); } } if (spp < targetSpp) { pathTraceLoop(); } else { sceneProvider.withEditSceneProtected(scene -> { scene.pauseRender(); updateRenderState(scene); }); } } if (headless) { break; } } } catch (InterruptedException e) { } catch (Throwable e) { Log.error("Unchecked exception in render manager", e); } stopWorkers(); }
Source:
<code>public void createFeedback(@RequestBody TrainingFeedbackDTO feedbackDTO) { TrainingFeedback feedback = new TrainingFeedback(feedbackDTO); trainingFeedbackService.addTrainingFeedback(feedback); feedbackDTO.setId(feedback.getId()); trainingFeedbackEventService.addEvent(new TrainingFeedbackEvent(feedbackDTO)); List<EventDTO> list = new ArrayList<>(); List<Event> events = new ArrayList<>(); events.addAll(trainingEventService.getUnwatchedEvents()); events.addAll(trainingFeedbackEventService.getUnwatchedEvents()); events.addAll(userFeedbackEventService.getUnwatchedEvents()); for (Event event: events){ list.add(event.toEventDTO()); } for (Map.Entry<DeferredResult<List<EventDTO>>, Integer> entry : EventController.eventRequests.entrySet()) { entry.getKey().setResult(list); <START> } <END> }</code><technical_language>move this code method</technical_language>

Target:
public void createFeedback(@RequestBody TrainingFeedbackDTO feedbackDTO) { TrainingFeedback feedback = new TrainingFeedback(feedbackDTO); trainingFeedbackService.addTrainingFeedback(feedback); feedbackDTO.setId(feedback.getId()); trainingFeedbackEventService.addEvent(new TrainingFeedbackEvent(feedbackDTO)); for (Map.Entry<DeferredResult<List<EventDTO>>, Integer> entry : EventController.eventRequests.entrySet()) { entry.getKey().setResult(getEvents()); } }
Source:
<code>public List<ScoredCandidates<T>> generate(T content, ResultDescription desc) { desc.startStage("Generating equivalences"); Builder<ScoredCandidates<T>> generatedScores = ImmutableList.builder(); ImmutableList<Long> excludedIds = excludedUris.stream() .filter(id -> !id.contains("http")) <START> .map(id -> codec.decode(id).longValue()) <END> .collect(MoreCollectors.toImmutableList()); if (excludedUris.contains(content.getCanonicalUri()) || excludedIds.contains(content.getId())) { desc.appendText("Content %s is in equivalence blacklist and will not be equivalated", content.getCanonicalUri()); return generatedScores.build(); } if (!content.isActivelyPublished()) { return generatedScores.build(); } for (EquivalenceGenerator<T> generator : generators) { try { desc.startStage(generator.toString()); generatedScores.add(generator.generate(content, desc)); desc.finishStage(); } catch (Exception e) { throw new RuntimeException(String.format("Exception running %s for %s", generator, content), e); } } desc.finishStage(); return generatedScores.build(); }</code><technical_language>need do a bit of parsing get id uri</technical_language>

Target:
public List<ScoredCandidates<T>> generate(T content, ResultDescription desc) { desc.startStage("Generating equivalences"); Builder<ScoredCandidates<T>> generatedScores = ImmutableList.builder(); ImmutableList<Long> excludedDecodedIds = excludedIds.stream() .map(id -> codec.decode(id).longValue()) .collect(MoreCollectors.toImmutableList()); if (excludedUris.contains(content.getCanonicalUri()) || excludedDecodedIds.contains(content.getId())) { desc.appendText("Content %s is in equivalence blacklist and will not be equivalated", content.getCanonicalUri()); return generatedScores.build(); } if (!content.isActivelyPublished()) { return generatedScores.build(); } for (EquivalenceGenerator<T> generator : generators) { try { desc.startStage(generator.toString()); generatedScores.add(generator.generate(content, desc)); desc.finishStage(); } catch (Exception e) { throw new RuntimeException(String.format("Exception running %s for %s", generator, content), e); } } desc.finishStage(); return generatedScores.build(); }
Source:
<code>private static void runStatementWithRetry(ShouldRetry retryAnnotation, Statement base, Description description) { Preconditions.checkArgument(retryAnnotation.numAttempts() > 0, "Number of attempts should be positive, but found %s", retryAnnotation.numAttempts()); for (int attempt = 1; attempt <= retryAnnotation.numAttempts(); attempt++) { try { base.evaluate(); return; <START> } catch (Throwable t) { <END> log.info("Test {}.{} failed on attempt of {}.", description.getClassName(), description.getMethodName(), attempt, retryAnnotation.numAttempts()); if (attempt == retryAnnotation.numAttempts()) { throw Throwables.propagate(t); } } } }</code><technical_language>if retry Exceptions? Errors OOMs similarly fatal problems succeed retry want if application is hitting, occasionally</technical_language>

Target:
private static void runStatementWithRetry(ShouldRetry retryAnnotation, Statement base, Description description) { Preconditions.checkArgument(retryAnnotation.numAttempts() > 0, "Number of attempts should be positive, but found %s", retryAnnotation.numAttempts()); for (int attempt = 1; attempt <= retryAnnotation.numAttempts(); attempt++) { try { base.evaluate(); log.info("Test {}.{} succeeded on attempt of {}.", description.getClassName(), description.getMethodName(), attempt, retryAnnotation.numAttempts()); return; } catch (Exception | AssertionError e) { logFailureAndThrowIfNeeded(retryAnnotation, description, attempt, e); } catch (Throwable t) { throw Throwables.propagate(t); } } }
Source:
<code>private Result increment(final HRegion region, final OperationQuota quota, final MutationProto mutation, final CellScanner cells, long nonceGroup, ActivePolicyEnforcement spaceQuota) throws IOException { long before = EnvironmentEdgeManager.currentTime(); Increment increment = ProtobufUtil.toIncrement(mutation, cells); checkCellSizeLimit(region, increment); spaceQuota.getPolicyEnforcement(region).check(increment); quota.addMutation(increment); Result r = null; <START> boolean canProceed = startNonceOperation(mutation, nonceGroup); <END> boolean success = false; try { long nonce = mutation.hasNonce() ? mutation.getNonce() : HConstants.NO_NONCE; if (canProceed) { r = region.increment(increment, nonceGroup, nonce); } else { if (region.getCoprocessorHost() != null) { r = region.getCoprocessorHost().preIncrement(increment); } if (r == null) { List<Cell> results = region.get(toGet(increment), false, nonceGroup, nonce); r = Result.create(results); } if (region.getCoprocessorHost() != null) { r = region.getCoprocessorHost().postIncrement(increment, r); } } success = true; } finally { if (canProceed) { endNonceOperation(mutation, nonceGroup, success); } } final MetricsRegionServer metricsRegionServer = regionServer.getMetrics(); if (metricsRegionServer != null) { metricsRegionServer.updateIncrement(region.getTableDescriptor().getTableName(), EnvironmentEdgeManager.currentTime() - before); } return r == null ? Result.EMPTY_RESULT : r; }</code><technical_language>changed semantics here. Before, call preIncrement create a new nonce'd operation. Now, a new nonce operation, if CP is "skip this increment" Is intentional</technical_language>

Target:
private Result increment(final HRegion region, final OperationQuota quota, final MutationProto mutation, final CellScanner cells, long nonceGroup, ActivePolicyEnforcement spaceQuota) throws IOException { long before = EnvironmentEdgeManager.currentTime(); Increment increment = ProtobufUtil.toIncrement(mutation, cells); checkCellSizeLimit(region, increment); spaceQuota.getPolicyEnforcement(region).check(increment); quota.addMutation(increment); long nonce = mutation.hasNonce() ? mutation.getNonce() : HConstants.NO_NONCE; Result r = region.increment(increment, nonceGroup, nonce); final MetricsRegionServer metricsRegionServer = regionServer.getMetrics(); if (metricsRegionServer != null) { metricsRegionServer.updateIncrement(region.getTableDescriptor().getTableName(), EnvironmentEdgeManager.currentTime() - before); } return r == null ? Result.EMPTY_RESULT : r; }
Source:
<code>private void InitVdsBroker() { log.infoFormat("vdsBroker({0},{1})", _vds.gethost_name(), _vds.getport()); String clusterVersion = _vds.getvds_group_compatibility_version().getValue(); <START> int clientTimeOut = Config.<Integer> GetValue(ConfigValues.vdsTimeout, clusterVersion) * 1000; <END> int connectionTimeOut = Config.<Integer>GetValue(ConfigValues.vdsConnectionTimeout, clusterVersion) * 1000; int clientRetries = Config.<Integer>GetValue(ConfigValues.vdsRetries, clusterVersion); Pair<VdsServerConnector, HttpClient> returnValue = XmlRpcUtils.getConnection(_vds.gethost_name(), _vds.getport(), clientTimeOut, connectionTimeOut, clientRetries, VdsServerConnector.class, Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)); _vdsProxy = new VdsServerWrapper(returnValue.getFirst(), returnValue.getSecond()); }</code><technical_language>i change in config.sql this per-version, ok call version if 'general' config</technical_language>

Target:
private void InitVdsBroker() { log.infoFormat("Initialize vdsBroker ({0},{1})", _vds.getHostName(), _vds.getPort()); int clientTimeOut = Config.<Integer> GetValue(ConfigValues.vdsTimeout) * 1000; int connectionTimeOut = Config.<Integer>GetValue(ConfigValues.vdsConnectionTimeout) * 1000; int clientRetries = Config.<Integer>GetValue(ConfigValues.vdsRetries); Pair<VdsServerConnector, HttpClient> returnValue = XmlRpcUtils.getConnection(_vds.getHostName(), _vds.getPort(), clientTimeOut, connectionTimeOut, clientRetries, VdsServerConnector.class, Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)); _vdsProxy = new VdsServerWrapper(returnValue.getFirst(), returnValue.getSecond()); }