auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean lock() { if (backoffParameters.hasAcquireQueueLimit() && lock.getQueueLength() >= backoffParameters.maximumQueued) { throw new LockAcquisitionFailedException("Failed to acquire lock for aggregate identifier " + identifier + ": too many queued threads."); } try { if (!lock.tryLock(0, TimeUnit.NANOSECONDS)) { <START> int attempts = backoffParameters.acquireAttempts - 1; <END> do { attempts--; checkForDeadlock(); if(backoffParameters.hasAcquireAttemptLimit() && attempts < 1) { throw new LockAcquisitionFailedException("Failed to acquire lock for aggregate identifier " + identifier); } } while (!lock.tryLock(backoffParameters.spinTime, TimeUnit.MILLISECONDS)); } } catch (InterruptedException e) { throw new LockAcquisitionFailedException("Thread was interrupted", e); } if (isClosed) { lock.unlock(); return false; } return true; }</code><technical_language>set acquireAttempt Integer.MAX_VALUE virtually identical unlimited. drop hasAcquireAttemptLimit() call, simplifying if-block in this do-while</technical_language>

Target:
public boolean lock() { if (backoffParameters.maximumQueuedThreadsReached(lock.getQueueLength())) { throw new LockAcquisitionFailedException("Failed to acquire lock for aggregate identifier " + identifier + ": too many queued threads."); } try { if (!lock.tryLock(0, TimeUnit.NANOSECONDS)) { int attempts = backoffParameters.acquireAttempts - 1; do { attempts--; checkForDeadlock(); if(backoffParameters.hasAcquireAttemptLimit() && attempts < 1) { throw new LockAcquisitionFailedException( "Failed to acquire lock for aggregate identifier(" + identifier + "), maximum attempts exceeded (" + backoffParameters.maximumQueued + ")" ); } } while (!lock.tryLock(backoffParameters.spinTime, TimeUnit.MILLISECONDS)); } } catch (InterruptedException e) { throw new LockAcquisitionFailedException("Thread was interrupted", e); } if (isClosed) { lock.unlock(); return false; } return true; }
Source:
<code>public void access_to_superclass_should_trigger_completion() { <START> JavaSymbol.TypeJavaSymbol typeSymbol = spy(new JavaSymbol.TypeJavaSymbol(42, "name", new JavaSymbol.PackageJavaSymbol(null, null))); <END> typeSymbol.getSuperclass(); verify(typeSymbol).complete(); }</code><technical_language>this package symbol factorized</technical_language>

Target:
public void access_to_superclass_should_trigger_completion() { JavaSymbol.TypeJavaSymbol typeSymbol = spy(new JavaSymbol.TypeJavaSymbol(42, "name", P_PACKAGE_JAVA_SYMBOL)); typeSymbol.getSuperclass(); verify(typeSymbol).complete(); }
Source:
<code>protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (GoTestFinder.getTestTargetPackage(file) != null) return; List<GoFunctionDeclaration> functions = file.getFunctions(); for (GoFunctionDeclaration function : functions) { for (GoImportSpec importSpec : file.getImports()) { <START> if (function.getIdentifier().textMatches(importSpec.getLocalPackageName())) { <END> problemsHolder.registerProblem(function.getIdentifier(), getMessage(importSpec.getLocalPackageName())); } } } }</code><technical_language>This breaks stubs, function.getName instead</technical_language>

Target:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (GoTestFinder.getTestTargetPackage(file) != null) return; List<GoFunctionDeclaration> functions = file.getFunctions(); String funcName; for (GoFunctionDeclaration function : functions) { funcName = function.getName(); if (funcName == null) continue; for (GoImportSpec importSpec : file.getImports()) { if (funcName.equals(importSpec.getLocalPackageName())) { problemsHolder.registerProblem(function.getIdentifier(), getMessage(importSpec.getLocalPackageName()), new GoRenameQuickFix(function)); } } } }
Source:
<code>private boolean needProjectionNode (AbstractPlanNode root) { <START> if ( false == root.planNodeClassNeedsProjectionNode()) { <END> return false; } if (m_parsedSelect.hasComplexGroupby() || m_parsedSelect.hasComplexAgg()) { return false; } if (root instanceof AbstractReceivePlanNode && m_parsedSelect.hasPartitionColumnInGroupby()) { return false; } return true; }</code><technical_language>false == is a peculiar express !. BTW, peculiar is a polite wrong</technical_language>

Target:
private boolean needProjectionNode (AbstractPlanNode root) { if (!root.planNodeClassNeedsProjectionNode()) { return false; } if (m_parsedSelect.hasComplexGroupby() || m_parsedSelect.hasComplexAgg()) { return false; } if (root instanceof AbstractReceivePlanNode && m_parsedSelect.hasPartitionColumnInGroupby()) { return false; } return true; }
Source:
<code>public synchronized void save() throws IOException { InitMilestone currentMilestone = initLevel; if (!configLoaded) { <START> LOGGER.log(Level.SEVERE, <END> "An attempt to save Jenkins'' global configuration before it has been loaded has been " + "made during milestone " + currentMilestone + ". This is indicative of a bug in the caller and may lead to full or partial loss of " + "configuration.", new IllegalStateException("call trace")); throw new IOException("An attempt to save the configuration was made before it was loaded"); } if(BulkChange.contains(this)) { return; } if (currentMilestone == InitMilestone.COMPLETED) { LOGGER.log(FINE, "setting version {0} to {1}", new Object[] {version, VERSION}); version = VERSION; } else { LOGGER.log(FINE, "refusing to set version {0} to {1} during {2}", new Object[] {version, VERSION, currentMilestone}); } getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); }</code><technical_language>unnecessary log a stack trace _and_ throw exception. understanding of this situation is expect data loss, is broken return save(). delete log call expand message in IOException. (Arguably throwing IllegalStateException: IOException is a save attempted failed due filesystem problems, is caught logged, expectation a subsequent save persist data anyway, worst losing a bit of robustness a JVM crash. This case is different.)</technical_language>

Target:
public synchronized void save() throws IOException { InitMilestone currentMilestone = initLevel; if (!configLoaded) { LOGGER.log(Level.SEVERE, "An attempt to save Jenkins'' global configuration before it has been loaded has been " + "made during milestone " + currentMilestone + ". This is indicative of a bug in the caller and may lead to full or partial loss of " + "configuration.", new IllegalStateException("call trace")); throw new IllegalStateException("An attempt to save the global configuration was made before it was loaded"); } if(BulkChange.contains(this)) { return; } if (currentMilestone == InitMilestone.COMPLETED) { LOGGER.log(FINE, "setting version {0} to {1}", new Object[] {version, VERSION}); version = VERSION; } else { LOGGER.log(FINE, "refusing to set version {0} to {1} during {2}", new Object[] {version, VERSION, currentMilestone}); } getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); }
Source:
<code>public static Object awaitLatch(Object payload, CountDownLatch latch) { try { latch.await(); } catch (InterruptedException e) { currentThread().interrupt(); <START> return payload; <END> } return payload; }</code><technical_language>remove "return payload" in catch</technical_language>

Target:
public static Object awaitLatch(Object payload, CountDownLatch latch) { try { latch.await(); } catch (InterruptedException e) { currentThread().interrupt(); } return payload; }
Source:
<code>public LockResponse lock(LockRequest request) { <START> long startTime = System.nanoTime(); <END> LeasableLockResponse leasableResponse = delegate.leasableLock(request); LockResponse lockResponse = leasableResponse.getLockResponse(); Optional<Duration> leasePeriod = leasableResponse.getLeasePeriod(); if (lockResponse.wasSuccessful()) { updateLockLeases(lockResponse.getToken(), startTime, leasePeriod); } return lockResponse; }</code><technical_language>here; NanoTimes, plz</technical_language>

Target:
public LockResponse lock(LockRequest request) { LeasableLockResponse leasableResponse = delegate.lockV2(request); LockResponse lockResponse = leasableResponse.getLockResponse(); Lease lease = leasableResponse.getLease(); if (lockResponse.wasSuccessful()) { LeasedLockToken leasedLockToken = LeasedLockToken.of(lockResponse.getToken(), lease); return ImmutableLockResponse.of(Optional.of(leasedLockToken)); } return LockResponse.timedOut(); }
Source:
<code>private void testWriteCredentialReferenceAttribute(String resource, String resourceName, String store, String alias, String secret, boolean assertFailed) { ModelNode operation = new ModelNode(); operation.get(ClientConstants.OP_ADDR).add("subsystem", "elytron").add(resource, resourceName); operation.get(ClientConstants.OP).set(ClientConstants.WRITE_ATTRIBUTE_OPERATION); operation.get(ClientConstants.NAME).set(CREDENTIAL_REFERENCE); ModelNode credentialReference = new ModelNode(); if (store != null) { credentialReference.get(STORE).set(store); } if (alias != null) { credentialReference.get(ALIAS).set(alias); } if (secret != null) { credentialReference.get(CLEAR_TEXT).set(secret); } operation.get(ClientConstants.VALUE).set(credentialReference); ModelNode response = services.executeOperation(operation); if (assertFailed) { assertEquals(FAILED, response.get(OUTCOME).asString()); assertTrue(response.get(FAILURE_DESCRIPTION).asString().contains(CREDENTIAL_REFERENCE)); } else { <START> assertSuccess(response).get(RESULT); <END> } }</code><technical_language>get(RESULT) part redundant anymore</technical_language>

Target:
private void testWriteCredentialReferenceAttribute(String resource, String resourceName, String store, String alias, String secret, boolean assertFailed) { ModelNode operation = new ModelNode(); operation.get(ClientConstants.OP_ADDR).add("subsystem", "elytron").add(resource, resourceName); operation.get(ClientConstants.OP).set(ClientConstants.WRITE_ATTRIBUTE_OPERATION); operation.get(ClientConstants.NAME).set(CREDENTIAL_REFERENCE); ModelNode credentialReference = new ModelNode(); if (store != null) { credentialReference.get(STORE).set(store); } if (alias != null) { credentialReference.get(ALIAS).set(alias); } if (secret != null) { credentialReference.get(CLEAR_TEXT).set(secret); } operation.get(ClientConstants.VALUE).set(credentialReference); ModelNode response = services.executeOperation(operation); if (assertFailed) { assertEquals(FAILED, response.get(OUTCOME).asString()); assertTrue(response.get(FAILURE_DESCRIPTION).asString().contains(CREDENTIAL_REFERENCE)); } else { assertSuccess(response); } }
Source:
<code>public int execute() { Task<?> rootTask = work.getRootTask(); if (rootTask != null) { rootTask.setChildTasks(null); } work.setRootTask(this); this.parentTasks = null; if (shouldLoadAuthorizationMetadata()) { LOG.info("Loading authorization data"); <START> try { <END> initiateAuthorizationLoadTask(work.dumpDirectory); } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } } if (work.isIncrementalLoad()) { return executeIncrementalLoad(); } else { return executeBootStrapLoad(); } }</code><technical_language>move exception handling executeIncrementalLoad() executeBootStrapLoad() try/catch block for of method execution handle initiateAuthorizationLoadTask() related exception that. more aligned. I prefer if possible</technical_language>

Target:
public int execute() { try { Task<?> rootTask = work.getRootTask(); if (rootTask != null) { rootTask.setChildTasks(null); } work.setRootTask(this); this.parentTasks = null; if (shouldLoadAuthorizationMetadata()) { initiateAuthorizationLoadTask(); } if (work.isIncrementalLoad()) { return executeIncrementalLoad(); } else { return executeBootStrapLoad(); } } catch (RuntimeException e) { LOG.error("replication failed with run time exception", e); throw e; } catch (Exception e) { LOG.error("replication failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } }
Source:
<code>public void testInvalidSequenceOffset() throws IOException { <START> byte[] compressed = Resources.toByteArray(getClass().getClassLoader().getResource("data/zstd/invalid-offset.zst")); <END> byte[] output = new byte[compressed.length * 10]; getDecompressor().decompress(compressed, 0, compressed.length, output, 0, output.length); }</code><technical_language>name this, offset-before-start.zst</technical_language>

Target:
public void testInvalidSequenceOffset() throws IOException { byte[] compressed = Resources.toByteArray(getClass().getClassLoader().getResource("data/zstd/offset-before-start.zst")); byte[] output = new byte[compressed.length * 10]; getDecompressor().decompress(compressed, 0, compressed.length, output, 0, output.length); }
Source:
<code><START> public synchronized void start() <END> { log.info("Loading stored supervisors from database"); Map<String, SupervisorSpec> supervisors = metadataSupervisorManager.getLatest(); for (String id : supervisors.keySet()) { SupervisorSpec spec = supervisors.get(id); if (!(spec instanceof NoopSupervisorSpec)) { createAndStartSupervisorInternal(spec, false); } } }</code><technical_language>a lock instead of syncing entire start method</technical_language>

Target:
public void start() { Preconditions.checkState(!started, "SupervisorManager already started"); log.info("Loading stored supervisors from database"); synchronized (lock) { Map<String, SupervisorSpec> supervisors = metadataSupervisorManager.getLatest(); for (String id : supervisors.keySet()) { SupervisorSpec spec = supervisors.get(id); if (!(spec instanceof NoopSupervisorSpec)) { createAndStartSupervisorInternal(spec, false); } } started = true; } }
Source:
<code>private void handleAdditionalConfiguration() { new DefaultHyperlink().activate(); new DefaultShell("Modify Faceted Project"); new LabeledCombo("Type:").setSelection("Pure JEE6 Implementation"); Button okButton = new OkButton(); assertTrue("OK Button should be enabled.", okButton.isEnabled()); okButton.click(); <START> new WaitWhile(new ShellIsActive("Modify Faceted Project")); <END> new DefaultHyperlink().activate(); new DefaultShell("Modify Faceted Project"); new OkButton().click(); new WaitWhile(new ShellIsActive("Modify Faceted Project")); }</code><technical_language>ShellIsAvailable</technical_language>

Target:
private void handleAdditionalConfiguration() { new DefaultHyperlink().activate(); new DefaultShell("Modify Faceted Project"); new LabeledCombo("Type:").setSelection("Pure JEE6 Implementation"); Button okButton = new OkButton(); assertTrue("OK Button should be enabled.", okButton.isEnabled()); okButton.click(); new WaitWhile(new ShellIsAvailable("Modify Faceted Project")); new DefaultHyperlink().activate(); new DefaultShell("Modify Faceted Project"); new OkButton().click(); new WaitWhile(new ShellIsAvailable("Modify Faceted Project")); }
Source:
<code>protected Void doInBackground(Void... voids) { SyncthingService syncthingService = refSyncthingService.get(); if (syncthingService == null) { <START> cancel(true); <END> } try { syncthingService.mConfig = new ConfigXml(syncthingService); syncthingService.mConfig.updateIfNeeded(); } catch (ConfigXml.OpenConfigException e) { syncthingService.mNotificationHandler.showCrashedNotification(R.string.config_create_failed, true); synchronized (syncthingService.mStateLock) { syncthingService.onServiceStateChange(State.ERROR); } cancel(true); } return null; }</code><technical_language>return here</technical_language>

Target:
protected Void doInBackground(Void... voids) { SyncthingService syncthingService = refSyncthingService.get(); if (syncthingService == null) { cancel(true); return null; } try { syncthingService.mConfig = new ConfigXml(syncthingService); syncthingService.mConfig.updateIfNeeded(); } catch (ConfigXml.OpenConfigException e) { syncthingService.mNotificationHandler.showCrashedNotification(R.string.config_create_failed, true); synchronized (syncthingService.mStateLock) { syncthingService.onServiceStateChange(State.ERROR); } cancel(true); } return null; }
Source:
<code>public void decorate(World world, Random random, Chunk source) { int sourceX = (source.getX() << 4) + random.nextInt(16); int sourceZ = (source.getZ() << 4) + random.nextInt(16); int sourceY = random.nextInt(random.nextInt(type == Material.LAVA ? random.nextInt(240) + 8 : 248) + 8); final Block block = world.getBlockAt(sourceX, sourceY, sourceZ); if (block.getType() != Material.STONE && block.getType() != Material.AIR && block.getRelative(BlockFace.DOWN).getType() == Material.STONE && block.getRelative(BlockFace.UP).getType() == Material.STONE) { int stoneBlockCount = 0; <START> if (block.getRelative(BlockFace.EAST).getType() == Material.STONE) { <END> stoneBlockCount++; } if (block.getRelative(BlockFace.WEST).getType() == Material.STONE) { stoneBlockCount++; } if (block.getRelative(BlockFace.NORTH).getType() == Material.STONE) { stoneBlockCount++; } if (block.getRelative(BlockFace.SOUTH).getType() == Material.STONE) { stoneBlockCount++; } if (stoneBlockCount == 3) { int airBlockCount = 0; if (block.getRelative(BlockFace.EAST).isEmpty()) { airBlockCount++; } if (block.getRelative(BlockFace.WEST).isEmpty()) { airBlockCount++; } if (block.getRelative(BlockFace.NORTH).isEmpty()) { airBlockCount++; } if (block.getRelative(BlockFace.SOUTH).isEmpty()) { airBlockCount++; } if (airBlockCount == 1) { final BlockState state = block.getState(); state.setType(type); state.update(true); } } } }</code><technical_language>want a constant array BlockFaces instead</technical_language>

Target:
public void decorate(World world, Random random, Chunk source) { int sourceX = (source.getX() << 4) + random.nextInt(16); int sourceZ = (source.getZ() << 4) + random.nextInt(16); int sourceY = random.nextInt(random.nextInt(type == Material.LAVA ? random.nextInt(240) + 8 : 248) + 8); final Block block = world.getBlockAt(sourceX, sourceY, sourceZ); if (block.getType() != Material.STONE && block.getType() != Material.AIR && block.getRelative(BlockFace.DOWN).getType() == Material.STONE && block.getRelative(BlockFace.UP).getType() == Material.STONE) { int stoneBlockCount = 0; for (BlockFace face : SIDES) { if (block.getRelative(face).getType() == Material.STONE) { stoneBlockCount++; } } if (stoneBlockCount == 3) { int airBlockCount = 0; for (BlockFace face : SIDES) { if (block.getRelative(face).isEmpty()) { airBlockCount++; } } if (airBlockCount == 1) { final BlockState state = block.getState(); state.setType(type); state.update(true); } } } }
Source:
<code>protected void postLoad(Group group, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION) < 0) { for (Viewpoint viewpoint : group.getOwnedViewpoints()) { for (DiagramDescription diagramDescription : Iterables.filter(viewpoint.getOwnedRepresentations(), DiagramDescription.class)) { <START> migrateStyleOfContainerMappingInLayer(LayerHelper.getAllLayers(diagramDescription)); <END> migrateStyleOfContainerMapping(diagramDescription.getAllContainerMappings()); } for (DiagramExtensionDescription diagramExtensionDescription : Iterables.filter(viewpoint.getOwnedRepresentationExtensions(), DiagramExtensionDescription.class)) { migrateStyleOfContainerMappingInLayer(diagramExtensionDescription.getLayers()); } } } }</code><technical_language>cancel this draft try</technical_language>

Target:
protected void postLoad(Group group, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION) < 0) { for (Viewpoint viewpoint : group.getOwnedViewpoints()) { for (DiagramDescription diagramDescription : Iterables.filter(viewpoint.getOwnedRepresentations(), DiagramDescription.class)) { migrateStyleOfContainerMappingInLayer(diagramDescription.getAllLayers()); migrateStyleOfContainerMapping(diagramDescription.getAllContainerMappings()); } for (DiagramExtensionDescription diagramExtensionDescription : Iterables.filter(viewpoint.getOwnedRepresentationExtensions(), DiagramExtensionDescription.class)) { migrateStyleOfContainerMappingInLayer(diagramExtensionDescription.getLayers()); } } } }
Source:
<code>public void testValidationChecksumBuilderArtifactsNull() { <START> final Builder builder = new ValidationChecksum.Builder().destination(checksumdirectory); assertThatThrownBy(() -> builder.artifacts(null)) .isExactlyInstanceOf(NullPointerException.class); <END> }</code><technical_language>method throw exception? change assertThatCode -> assertThatThrownBy</technical_language>

Target:
public void testValidationChecksumBuilderArtifactsNull() { final Builder builder = new ValidationChecksum.Builder().destination(checksumdirectory); assertThatCode(() -> builder.artifacts(null)) .isExactlyInstanceOf(NullPointerException.class); }
Source:
<code>public void testCannotUpdateOSNotSupportVirtioScsi() { prepareVmToPassValidate(); group.setCompatibilityVersion(Version.v4_0); when(command.isVirtioScsiEnabledForVm(any(Guid.class))).thenReturn(true); when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn( <START> new ArrayList<>(Collections.singletonList("VirtIO"))); <END> ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_OS_TYPE_DOES_NOT_SUPPORT_VIRTIO_SCSI); }</code><technical_language>drop new ArrayList<>(...) surroundings. sufficient return singletonList</technical_language>

Target:
public void testCannotUpdateOSNotSupportVirtioScsi() { prepareVmToPassValidate(); group.setCompatibilityVersion(Version.v4_0); when(command.isVirtioScsiEnabledForVm(any(Guid.class))).thenReturn(true); when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn( Collections.singletonList("VirtIO")); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_OS_TYPE_DOES_NOT_SUPPORT_VIRTIO_SCSI); }
Source:
<code>public void run () { while (!Thread.interrupted()) { final byte[] headBuffer = new byte[DMResponse.packetsize]; final byte[] bodyBuffer; DMResponse header; try { in.read(headBuffer, 0, headBuffer.length); header = new DMResponse (headBuffer); if(header.isValid()) { bodyBuffer = new byte[header.getsize()]; in.read(bodyBuffer, 0, bodyBuffer.length); if(header.getsource() == DMResponse.SUBSCRIPTION_MGR) { if(!mbox.containsKey(header.getscriptID())) mbox.put(header.getscriptID (), new LinkedBlockingQueue<byte[]> ()); mbox.get(header.getscriptID()).put(header.tobytes()); mbox.get(header.getscriptID()).put(bodyBuffer); } else { if(!mbox.containsKey(header.getscriptID())) mbox.put(header.getscriptID (), new LinkedBlockingQueue<byte[]> ()); mbox.get(header.getscriptID()).put(header.tobytes()); mbox.get(header.getscriptID()).put(bodyBuffer); } } else { } } catch (InterruptedException ie) { System.err.println ("Interrupted: " + ie.getMessage()); break; } catch (IOException ioe) { new ErrorMessage("I/O Error Check host!", "See stderr for more details").open(); System.err.println ("i/o error: " + ioe.getMessage()); return; <START> } catch (Exception e) { <END> new ErrorMessage("Check if DMD is running", "See stderr for more details").open(); System.err.println ("Server terminated unexpectedly?," + e.getMessage()); return; } } this.destroyConnection(); }</code><technical_language>Exception is catched here</technical_language>

Target:
public void run () { while (!Thread.interrupted()) { final byte[] headBuffer = new byte[DMResponse.packetsize]; final byte[] bodyBuffer; DMResponse header; try { in.read(headBuffer, 0, headBuffer.length); header = new DMResponse (headBuffer); if(header.isValid()) { bodyBuffer = new byte[header.getsize()]; in.read(bodyBuffer, 0, bodyBuffer.length); if(header.getsource() == DMResponse.SUBSCRIPTION_MGR) { if(!mbox.containsKey(header.getscriptID())) mbox.put(header.getscriptID (), new LinkedBlockingQueue<byte[]> ()); mbox.get(header.getscriptID()).put(header.tobytes()); mbox.get(header.getscriptID()).put(bodyBuffer); } else { if(!mbox.containsKey(header.getscriptID())) mbox.put(header.getscriptID (), new LinkedBlockingQueue<byte[]> ()); mbox.get(header.getscriptID()).put(header.tobytes()); mbox.get(header.getscriptID()).put(bodyBuffer); } } else { } } catch (InterruptedException ie) { System.err.println ("Interrupted: " + ie.getMessage()); break; } catch (IOException ioe) { new ErrorMessage("I/O Error Check host!", "See stderr for more details").open(); System.err.println ("i/o error: " + ioe.getMessage()); return; } } this.destroyConnection(); }
Source:
<code>private void setTemperatureMeasurementValue(float temperatureMeasurementValue) { mTemperatureMeasurementCharacteristic.setValue(new byte[]{0b00000000, 0, 0, 0, 0}); int bits = Float.floatToIntBits(temperatureMeasurementValue); int sign = bits >>> 31; int exp = (bits >>> 23 & ((1 << 8) - 1)) - ((1 << 7) - 1); <START> int mantissa = bits & ((1 << 23) - 1); <END> mTemperatureMeasurementCharacteristic.setValue(mantissa, exp, TEMPERATURE_MEASUREMENT_VALUE_FORMAT, 1); }</code><technical_language>do of following: java int EXPONENT_MASK = 0x7f800000; int EXPONENT_SHIFT = 23; int MANTISSA_MASK = 0x007fffff int MANTISSA_SHIFT = 0; // ... private void setTemperatureMeasurementValue(...) { // ... int exponent = (bits & EXPONENT_MASK) >>> EXPONENT_SHIFT; int mantissa = (bits & MANTISSA_MASK) >>> MANTISSA_SHIFT; // ... }</technical_language>

Target:
private void setTemperatureMeasurementValue(float temperatureMeasurementValue) { mTemperatureMeasurementCharacteristic.setValue(new byte[]{0b00000000, 0, 0, 0, 0}); int bits = Float.floatToIntBits(temperatureMeasurementValue); int exponent = (bits & EXPONENT_MASK) >>> EXPONENT_SHIFT; int mantissa = (bits & MANTISSA_MASK) >>> MANTISSA_SHIFT; mTemperatureMeasurementCharacteristic.setValue(mantissa, exponent, TEMPERATURE_MEASUREMENT_VALUE_FORMAT, 1); }
Source:
<code>public void testApplySessionPropertyConfigurationManager() throws Exception { HttpServletRequest request = new MockHttpServletRequest( <START> ImmutableListMultimap.<String, String>builder() <END> .put(PRESTO_USER, "testUser") .put(PRESTO_SOURCE, "testSource") .put(PRESTO_CATALOG, "testCatalog") .put(PRESTO_SCHEMA, "testSchema") .put(PRESTO_LANGUAGE, "zh-TW") .put(PRESTO_TIME_ZONE, "Asia/Taipei") .put(PRESTO_CLIENT_INFO, "client-info") .put(PRESTO_CLIENT_TAGS, "tag1,tag2 ,tag3, tag2") .put(PRESTO_SESSION, QUERY_MAX_MEMORY + "=1GB") .put(PRESTO_SESSION, DISTRIBUTED_JOIN + "=true," + HASH_PARTITION_COUNT + " = 43") .put(PRESTO_PREPARED_STATEMENT, "query1=select * from foo,query2=select * from bar") .build(), "testRemote"); HttpRequestSessionContext context = new HttpRequestSessionContext(request); QuerySessionSupplier sessionSupplier = new QuerySessionSupplier( createTestTransactionManager(), new AllowAllAccessControl(), new SessionPropertyManager()); SessionPropertyConfigurationManagerFactory factory = new TestingSessionPropertyConfigurationManagerFactory( ImmutableMap.of(QUERY_MAX_MEMORY, "10GB", "key2", "20", "key3", "3"), ImmutableMap.of("testCatalog", ImmutableMap.of("key1", "10"))); sessionSupplier.addConfigurationManager(factory); sessionSupplier.setConfigurationManager(factory.getName(), ImmutableMap.of()); Session session = sessionSupplier.createSession(new QueryId("test_query_id"), context); assertEquals(session.getSystemProperties(), ImmutableMap.<String, String>builder() .put(QUERY_MAX_MEMORY, "1GB") .put(DISTRIBUTED_JOIN, "true") .put(HASH_PARTITION_COUNT, "43") .put("key2", "20") .put("key3", "3") .build()); assertEquals(session.getUnprocessedCatalogProperties(), ImmutableMap.of("testCatalog", ImmutableMap.of("key1", "10"))); }</code><technical_language>This map duplicated above, extract a constant</technical_language>

Target:
public void testApplySessionPropertyConfigurationManager() throws Exception { HttpRequestSessionContext context = new HttpRequestSessionContext(TEST_REQUEST); QuerySessionSupplier sessionSupplier = new QuerySessionSupplier( createTestTransactionManager(), new AllowAllAccessControl(), new SessionPropertyManager()); SessionPropertyConfigurationManagerFactory factory = new TestingSessionPropertyConfigurationManagerFactory( ImmutableMap.of(QUERY_MAX_MEMORY, "10GB", "key2", "20", "key3", "3"), ImmutableMap.of("testCatalog", ImmutableMap.of("key1", "10"))); sessionSupplier.addConfigurationManager(factory); sessionSupplier.setConfigurationManager(factory.getName(), ImmutableMap.of()); Session session = sessionSupplier.createSession(new QueryId("test_query_id"), context); assertEquals(session.getSystemProperties(), ImmutableMap.<String, String>builder() .put(QUERY_MAX_MEMORY, "1GB") .put(DISTRIBUTED_JOIN, "true") .put(HASH_PARTITION_COUNT, "43") .put("key2", "20") .put("key3", "3") .build()); assertEquals(session.getUnprocessedCatalogProperties(), ImmutableMap.of("testCatalog", ImmutableMap.of("key1", "10"))); }
Source:
<code>public void setDeprecated(String itemId, boolean deprecated) { if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_CATALOG_ITEM, StringAndArgument.of(itemId, "deprecated"))) { throw WebResourceUtils.unauthorized("User '%s' is not authorized to modify catalog", Entitlements.getEntitlementContext().user()); } CatalogItem<?, ?> item = CatalogUtils.getCatalogItemOptionalVersion(mgmt(), itemId); if (item==null) throw WebResourceUtils.notFound("Catalog item with id '%s' not found", itemId); <START> item.setDeprecated(deprecated); <END> }</code><technical_language>This persisted - if stopped restarted Brooklyn catalog item longer deprecated (I think). RebindCatalogItemTest for testing catalog persistence. call mgmt.getCatalog().... persist this change</technical_language>

Target:
public void setDeprecated(String itemId, boolean deprecated) { if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_CATALOG_ITEM, StringAndArgument.of(itemId, "deprecated"))) { throw WebResourceUtils.unauthorized("User '%s' is not authorized to modify catalog", Entitlements.getEntitlementContext().user()); } CatalogItem<?, ?> item = CatalogUtils.getCatalogItemOptionalVersion(mgmt(), itemId); if (item==null) throw WebResourceUtils.notFound("Catalog item with id '%s' not found", itemId); item.setDeprecated(deprecated); mgmt().getCatalog().persist(item); }
Source:
<code>private static void killIAM() throws InterruptedException { if (iamProcess != null) { System.out.println("Stopping IAM microservice..."); iamProcess.destroy(); <START> iamProcess.waitFor(); <END> iamProcess = null; } }</code><technical_language>I need a timeout here. apply in RestFuncTUtils</technical_language>

Target:
private static void killIAM() throws InterruptedException { if (iamProcess != null) { System.out.println("Stopping IAM microservice..."); iamProcess.destroy(); if (!iamProcess.waitFor(1, TimeUnit.MINUTES)) { iamProcess.destroyForcibly(); iamProcess.waitFor(1, TimeUnit.MINUTES); } iamProcess = null; } }
Source:
<code>public void beforeMethodWithBeforeGroupsShouldOnlyRunBeforeGroupMethods() { TestNG suite = create(new Class[] { BeforeMethodWithGroupFiltersSampleTest.class } ); suite.run(); for (String[] expectedSequence : BeforeMethodWithGroupFiltersSampleTest.EXPECTED_INVOCATION_SEQUENCES) <START> assertThat(BeforeMethodWithGroupFiltersSampleTest.invocations) <END> .containsSequence(expectedSequence); assertThat(BeforeMethodWithGroupFiltersSampleTest.invocations) .hasSize(BeforeMethodWithGroupFiltersSampleTest.EXPECTED_TOTAL_INVOCATIONS); }</code><technical_language>assertion is strong enough: order change provide exact list of invoked methods</technical_language>

Target:
public void beforeMethodWithBeforeGroupsShouldOnlyRunBeforeGroupMethods() { InvokedMethodNameListener nameListener = run(BeforeMethodWithGroupFiltersSampleTest.class); assertThat(nameListener.getInvokedMethodNames()) .containsExactly(BeforeMethodWithGroupFiltersSampleTest.EXPECTED_INVOCATIONS); }
Source:
<code>public void testValidateSuccessful() { PlanNode root = new OutputNode(idAllocator.getNextId(), new ProjectNode(idAllocator.getNextId(), new ValuesNode( idAllocator.getNextId(), ImmutableList.of(), ImmutableList.of(), ImmutableList.of()), Assignments.of() <START> ), ImmutableList.of(), ImmutableList.of(), ImmutableList.of()); <END> new VerifyOnlyOneOutputNode().validate(root, null, null, null, null, WarningCollector.NOOP); }</code><technical_language>sad multiple params line before. fix param line</technical_language>

Target:
public void testValidateSuccessful() { PlanNode root = new OutputNode(idAllocator.getNextId(), new ProjectNode(idAllocator.getNextId(), new ValuesNode( idAllocator.getNextId(), ImmutableList.of(), ImmutableList.of()), Assignments.of() ), ImmutableList.of(), ImmutableList.of()); new VerifyOnlyOneOutputNode().validate(root, null, null, null, null, WarningCollector.NOOP); }
Source:
<code>protected void configureParameters(InterfaceList interfaceList, String parentNodeName) throws TypeImportException, XMLStreamException { processChildren(parentNodeName, name -> { if <START> (name.equals(LibraryElementTags.PARAMETER_ELEMENT)) <END> { VarDeclaration paramter = parseParameter(); VarDeclaration vInput = getVarNamed(interfaceList, paramter.getName(), true); if (null != vInput) { vInput.setValue(paramter.getValue()); } return true; } return false; }); }</code><technical_language>call equals constant name</technical_language>

Target:
protected void configureParameters(InterfaceList interfaceList, String parentNodeName) throws TypeImportException, XMLStreamException { processChildren(parentNodeName, name -> { if (LibraryElementTags.PARAMETER_ELEMENT.equals(name)) { VarDeclaration paramter = parseParameter(); VarDeclaration vInput = getVarNamed(interfaceList, paramter.getName(), true); if (null != vInput) { vInput.setValue(paramter.getValue()); } return true; } return false; }); }
Source:
<code>public Array<T> dropUntil(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = 0; i < length(); i++) { <START> if (predicate.test(get(i))) { <END> return drop(i); } } return empty(); }</code><technical_language>great</technical_language>

Target:
public Array<T> dropUntil(Predicate<? super T> predicate) { return Collections.dropUntil(this, predicate); }
Source:
<code>public static CoordinateReferenceSystem get( int tableId, int code ) { CRSTable table = CRSTable.find( tableId ); <START> return new CoordinateReferenceSystem( table.name + "-" + code, table, code ); <END> }</code><technical_language>do need create new instances of reference system here? fixed number of systems, right</technical_language>

Target:
public static CoordinateReferenceSystem get( int tableId, int code ) { CRSTable table = CRSTable.find( tableId ); if ( tableId == CRSTable.SR_ORG.getTableId() && code == Cartesian.code ) { return CoordinateReferenceSystem.Cartesian; } else if ( tableId == CRSTable.EPSG.getTableId() && code == WGS84.code ) { return CoordinateReferenceSystem.WGS84; } else { return new CoordinateReferenceSystem( table.getName() + "-" + code, table, code ); } }
Source:
<code>private void checkTarUntarRoundTrip(String filePrefix, long fileSize) throws Exception { File tempFile = null, tarFile = null; FilePath outDir = null; try { <START> tempFile = File.createTempFile(filePrefix, ".log"); <END> RandomAccessFile file = new RandomAccessFile(tempFile, "rw"); tarFile = new File(tempFile.getParent(), filePrefix + ".tar"); file.setLength(fileSize); assumeTrue(fileSize == file.length()); file.close(); final FilePath tmpDir = new FilePath(tempFile.getParentFile()); int tar = tmpDir.tar(new FileOutputStream(tarFile), tempFile.getName()); assertEquals("One file should have been compressed", 1, tar); outDir = tmpDir.createTempDir(filePrefix, "out"); final FilePath outFile = outDir.child(tempFile.getName()); tmpDir.child( filePrefix + ".tar").untar(outDir, TarCompression.NONE); assertEquals("Result file after the roundtrip differs from the initial file", new FilePath(tempFile).digest(), outFile.digest()); } finally { if (tempFile != null && tempFile.exists()) { tempFile.delete(); } if (tarFile != null && tarFile.exists()) { tarFile.delete(); } if (outDir != null && outDir.exists()) { outDir.deleteRecursive(); } } }</code><technical_language>FilePathTest.temp allocate temporary files bothering a finally-block</technical_language>

Target:
private void checkTarUntarRoundTrip(String filePrefix, long fileSize) throws Exception { final File tmpDir = temp.newFolder(filePrefix); final File tempFile = new File(tmpDir, filePrefix + ".log"); RandomAccessFile file = new RandomAccessFile(tempFile, "rw"); final File tarFile = new File(tmpDir, filePrefix + ".tar"); file.setLength(fileSize); assumeTrue(fileSize == file.length()); file.close(); final FilePath tmpDirPath = new FilePath(tmpDir); int tar = tmpDirPath.tar(new FileOutputStream(tarFile), tempFile.getName()); assertEquals("One file should have been compressed", 1, tar); FilePath outDir = new FilePath(temp.newFolder(filePrefix + "_out")); final FilePath outFile = outDir.child(tempFile.getName()); tmpDirPath.child( filePrefix + ".tar").untar(outDir, TarCompression.NONE); assertEquals("Result file after the roundtrip differs from the initial file", new FilePath(tempFile).digest(), outFile.digest()); }
Source:
<code>public void testFilterNicsWithUnmanagedNetworksUmngmtNetRemoved(){ VdsNetworkInterface nicWithUnmanagedToBeRemoved = createNicWithNetworkImplementationDetails("eth_unmanaged1_toBeRemoved", false); VdsNetworkInterface nicWithUnmanaged = createNicWithNetworkImplementationDetails("eth_unmanaged", false); VdsNetworkInterface nicWithManagedToBeRemoved = createNicWithNetworkImplementationDetails("eth_managed_toBeRemoved", true); <START> VdsNetworkInterface nicWithManaged = createNicWithNetworkImplementationDetails("eth_managed", true); <END> List<VdsNetworkInterface> existingInterfaces = Arrays.asList(nicWithUnmanagedToBeRemoved, nicWithUnmanaged, nicWithManagedToBeRemoved, nicWithManaged); Set<String> removedUnmanagedNetworks = new HashSet<>(Arrays.asList("eth_unmanaged1_toBeRemoved", "eth_managed_toBeRemoved")); List<VdsNetworkInterface> unmanagedNicsList = validator.filterNicsWithUnmanagedNetworks(existingInterfaces, removedUnmanagedNetworks); assertEquals(1, unmanagedNicsList.size()); assertEquals("eth_unmanaged", unmanagedNicsList.get(0).getName()); }</code><technical_language>validation caused realize is another validation add unmanagedNetworkValidator. check if networks in 'removedUnmanagedNetworks' parameter unmanaged networks (don't exist in cluster)! I passing in this list a name of a network exist in cluster exist in host is harmful (please verify). I if pass a network is attached host (and cluster, aka managed). end removing this managed network host. this blocked</technical_language>

Target:
public void testFilterNicsWithUnmanagedNetworksUmngmtNetRemoved(){ VdsNetworkInterface nicWithUnmanagedToBeRemoved = createNicWithNetworkImplementationDetails("eth_unmanaged1_toBeRemoved", false); VdsNetworkInterface nicWithUnmanaged = createNicWithNetworkImplementationDetails("eth_unmanaged", false); VdsNetworkInterface nicWithManagedToBeRemoved = createNicWithNetworkImplementationDetails("eth_managed_toBeRemoved", true); VdsNetworkInterface nicWithManaged = createNicWithNetworkImplementationDetails("eth_managed", true); List<VdsNetworkInterface> existingInterfaces = Arrays.asList(nicWithUnmanagedToBeRemoved, nicWithUnmanaged, nicWithManagedToBeRemoved, nicWithManaged); Collection<String> removedUnmanagedNetworks = Arrays.asList("eth_unmanaged1_toBeRemoved", "eth_managed_toBeRemoved"); Set<String> unmanagedNicsSet = validator.filterNicsWithUnmanagedNetworks(existingInterfaces, removedUnmanagedNetworks); assertEquals(1, unmanagedNicsSet.size()); assertTrue(unmanagedNicsSet.contains("eth_unmanaged")); }
Source:
<code>public AggregatedVcfLineMapper(VariantSource source) { switch (source.getAggregation()) { case EVS: factory = new VariantVcfEVSFactory(); break; case EXAC: factory = new VariantVcfExacFactory(); break; case BASIC: factory = new VariantAggregatedVcfFactory(); break; case NONE: factory = null; throw new IllegalArgumentException( this.getClass().getSimpleName() + " should not take non-aggregated " + <START> "VCFs, but the VariantSource is marked as Aggregation.NONE"); <END> } this.source = source; }</code><technical_language>Double negatives hard understand. this.getClass().getSimpleName() + " read aggregated VCFs only, VariantSource.Aggregation is set NONE"</technical_language>

Target:
public AggregatedVcfLineMapper(VariantSource source) { switch (source.getAggregation()) { case EVS: factory = new VariantVcfEVSFactory(); break; case EXAC: factory = new VariantVcfExacFactory(); break; case BASIC: factory = new VariantAggregatedVcfFactory(); break; case NONE: throw new IllegalArgumentException( this.getClass().getSimpleName() + " should be used to read aggregated VCFs only, " + "but the VariantSource.Aggregation is set to NONE"); } this.source = source; }
Source:
<code>public FailureInfo getLastFailureInfo() { Exception lastFailureException = getLastFailureException(); if (lastFailureException == null) { return null; } <START> else { <END> return Failures.toFailure(lastFailureException).toFailureInfo(); } }</code><technical_language>unnecessary else previous if returns</technical_language>

Target:
public FailureInfo getLastFailureInfo() { Exception lastFailureException = getLastFailureException(); if (lastFailureException == null) { return null; } return Failures.toFailure(lastFailureException).toFailureInfo(); }
Source:
<code>public TestRunner addConfig(String key, String value) { Preconditions.checkNotNull(key); Preconditions.checkNotNull(value); <START> String configKeyPrefix = String.format(JobConfig.CONFIG_JOB_PREFIX(), JOB_NAME); <END> configs.put(String.format("%s%s", configKeyPrefix, key), value); return this; }</code><technical_language>Please refer PR #642 , need full jobNameAndId in config job prefix</technical_language>

Target:
public TestRunner addConfig(String key, String value) { Preconditions.checkNotNull(key); Preconditions.checkNotNull(value); String configPrefix = String.format(JobConfig.CONFIG_OVERRIDE_JOBS_PREFIX(), getJobNameAndId()); configs.put(String.format("%s%s", configPrefix, key), value); return this; }
Source:
<code>protected Control createPageControls(final Composite parent) { setTitle("Rebase Change"); setMessage(""); Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Label label = new Label(composite, SWT.NONE); <START> label.setText("Rebase Change?"); <END> parent.getDisplay().asyncExec(new Runnable() { @Override public void run() { if (!parent.isDisposed()) { setReturnCode(Window.OK); close(); } } }); return composite; }</code><technical_language>some kind of detail here, e.g. "Rebase this patch set master head?"</technical_language>

Target:
protected Control createPageControls(final Composite parent) { setTitle("Rebase Patch Set"); setMessage(""); Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Label label = new Label(composite, SWT.NONE); label.setText(NLS.bind("Rebase patch set {0}", patchSet.getRefName())); parent.getDisplay().asyncExec(new Runnable() { @Override public void run() { if (!parent.isDisposed()) { setReturnCode(Window.OK); close(); } } }); return composite; }
Source:
<code>private static ParametersRunnerFactory getParametersRunnerFactory( Class<?> klass) throws InstantiationException, IllegalAccessException { UseParametersRunnerFactory annotation = klass .getAnnotation(UseParametersRunnerFactory.class); if (annotation == null) { return DEFAULT_FACTORY; } else { Class<? extends ParametersRunnerFactory> factoryClass = annotation .value(); <START> return factoryClass.newInstance(); <END> } }</code><technical_language>Do need some error handling here</technical_language>

Target:
private ParametersRunnerFactory getParametersRunnerFactory(Class<?> klass) throws InstantiationException, IllegalAccessException { UseParametersRunnerFactory annotation = klass .getAnnotation(UseParametersRunnerFactory.class); if (annotation == null) { return DEFAULT_FACTORY; } else { Class<? extends ParametersRunnerFactory> factoryClass = annotation .value(); return factoryClass.newInstance(); } }
Source:
<code>public static ConnectionInfo fromURI(URI originalUri) { final String uriStr = originalUri.toASCIIString(); URI uri = originalUri; final ConnectionInfo connInfo = new ConnectionInfo(); <START> connInfo.scheme = uriStr.substring(0, uriStr.indexOf("://")); <END> if (connInfo.scheme.split(":").length > 1) { int idx = uriStr.indexOf(':'); uri = URI.create(uriStr.substring(idx + 1)); } String path = uri.getPath(); if (path != null && !path.isEmpty()) { String pathElements = path.substring(1).split("/"); if (pathElements.length != 1) { throw new TajoInternalError("Invalid JDBC path: " + path); } connInfo.dbName = pathElements[0]; } Map<String, String> params = new HashMap<>(); int paramIndex = uriStr.indexOf("?"); if (paramIndex > 0) { String parameterPart = uriStr.substring(paramIndex+1, uriStr.length()); String eachParam = parameterPart.split("&"); for (String each: eachParam) { String keyValues = each.split("="); if (keyValues.length != 2) { throw new TajoInternalError("Invalid URI Parameters: " + parameterPart); } params.put(keyValues[0], keyValues[1]); } } if (params.containsKey("table")) { connInfo.tableName = params.remove("table"); } if (params.containsKey("user")) { connInfo.user = params.remove("user"); } if (params.containsKey("password")) { connInfo.password = params.remove("password"); } connInfo.params = params; return connInfo; }</code><technical_language>Please UriUtil</technical_language>

Target:
public static ConnectionInfo fromURI(URI originalUri) { final String uriStr = originalUri.toASCIIString(); URI uri = originalUri; final ConnectionInfo connInfo = new ConnectionInfo(); connInfo.scheme = uriStr.substring(0, uriStr.indexOf("://")); if (connInfo.scheme.split(":").length > 1) { int idx = uriStr.indexOf(':'); uri = URI.create(uriStr.substring(idx + 1)); } connInfo.host = uri.getHost(); String path = uri.getPath(); if (path != null && !path.isEmpty()) { String pathElements = path.substring(1).split("/"); if (pathElements.length != 1) { throw new TajoInternalError("Invalid JDBC path: " + path); } connInfo.dbName = pathElements[0]; } Map<String, String> params = new HashMap<>(); int paramIndex = uriStr.indexOf("?"); if (paramIndex > 0) { String parameterPart = uriStr.substring(paramIndex+1, uriStr.length()); String eachParam = parameterPart.split("&"); for (String each: eachParam) { String keyValues = each.split("="); if (keyValues.length != 2) { throw new TajoInternalError("Invalid URI Parameters: " + parameterPart); } params.put(keyValues[0], keyValues[1]); } } if (params.containsKey("table")) { connInfo.tableName = params.remove("table"); } if (params.containsKey("user")) { connInfo.user = params.remove("user"); } if (params.containsKey("password")) { connInfo.password = params.remove("password"); } connInfo.params = params; return connInfo; }