auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testBooleanExplosion() { <START> Stopwatch stopwatch = <END> Stopwatch.createStarted(); String regex = "[0-9]*a[0-9]{50,80}"; int maxExpand = 10; int maxStatesTraced = 10000; int maxDeterminizedStates = 20000; int maxNgramsExtracted = 10000; Automaton automaton = new RegExp( regex.toLowerCase(Locale.ENGLISH), RegExp.ALL ^ RegExp.AUTOMATON ).toAutomaton(maxDeterminizedStates); NGramExtractor extractor = new NGramExtractor(3, maxExpand, maxStatesTraced, maxNgramsExtracted); Expression<String> expression = extractor.extract(automaton); assertTrue(expression.countClauses() == Integer.MAX_VALUE); expression = new ExpressionRewriter<>(expression).degradeAsDisjunction(maxNgramsExtracted); assertTrue(expression.getClass() == Or.class); assertFalse(expression.alwaysFalse()); assertFalse(expression.alwaysTrue()); assertTrue(expression.countClauses() <= maxNgramsExtracted); stopwatch.stop(); assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < 500); }</code><technical_language>converting a standard junit timeout explicit stopwatch? surprised. sense move this test a specific class a TimeoutRule instead (<LINK_0> extract timeout checking code (now Java 8 closures, easy do in a clean way)</technical_language>

Target:
public void testBooleanExplosion() { TestUtils.assertExecTime(500, () -> { String regex = "[0-9]*a[0-9]{50,80}"; int maxExpand = 10; int maxStatesTraced = 10000; int maxDeterminizedStates = 20000; int maxNgramsExtracted = 10000; Automaton automaton = new RegExp( regex.toLowerCase(Locale.ENGLISH), RegExp.ALL ^ RegExp.AUTOMATON ).toAutomaton(maxDeterminizedStates); NGramExtractor extractor = new NGramExtractor(3, maxExpand, maxStatesTraced, maxNgramsExtracted); Expression<String> expression = extractor.extract(automaton); assertTrue(expression.countClauses() == Integer.MAX_VALUE); expression = new ExpressionRewriter<>(expression).degradeAsDisjunction(maxNgramsExtracted); assertTrue(expression.getClass() == Or.class); assertFalse(expression.alwaysFalse()); assertFalse(expression.alwaysTrue()); assertTrue(expression.countClauses() <= maxNgramsExtracted); } ); }
Source:
<code>public void getRegisters(final IDMContext dmc, final DataRequestMonitor<IRegisterDMContext[]> rm) { final MIRegisterGroupDMC groupDmc = DMContexts.getAncestorOfType(dmc, MIRegisterGroupDMC.class); if (groupDmc == null) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "RegisterGroup context not found", null)); rm.done(); return; } final IContainerDMContext containerDmc = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); if (containerDmc == null) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "Container context not found", null)); rm.done(); return; } if (groupDmc.getGroupNo() == 0) { final IFrameDMContext frameDmc = DMContexts.getAncestorOfType(dmc, IFrameDMContext.class); if (frameDmc == null) { IMIExecutionDMContext execDmc = DMContexts.getAncestorOfType(dmc, IMIExecutionDMContext.class); if (execDmc != null) { <START> MIStack stackService = getServicesTracker().getService(MIStack.class); <END> if (stackService != null) { stackService.getTopFrame(execDmc, new DataRequestMonitor<IStack.IFrameDMContext>(getSession() .getExecutor(), rm) { @Override protected void handleSuccess() { getRegisters(getData(), groupDmc, containerDmc, rm); } @Override protected void handleFailure() { getRegisters(null, groupDmc, containerDmc, rm); } }); return; } } } getRegisters(frameDmc, groupDmc, containerDmc, rm); } else { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid group = " + groupDmc, null)); rm.done(); } }</code><technical_language>Please IStack instead of MIStack. Someday, a instance of IStack service, this break</technical_language>

Target:
public void getRegisters(final IDMContext dmc, final DataRequestMonitor<IRegisterDMContext[]> rm) { final MIRegisterGroupDMC groupDmc = DMContexts.getAncestorOfType(dmc, MIRegisterGroupDMC.class); if (groupDmc == null) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "RegisterGroup context not found", null)); rm.done(); return; } final IContainerDMContext containerDmc = DMContexts.getAncestorOfType(dmc, IContainerDMContext.class); if (containerDmc == null) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "Container context not found", null)); rm.done(); return; } if (groupDmc.getGroupNo() == 0) { final IFrameDMContext frameDmc = DMContexts.getAncestorOfType(dmc, IFrameDMContext.class); if (frameDmc == null) { IMIExecutionDMContext execDmc = DMContexts.getAncestorOfType(dmc, IMIExecutionDMContext.class); if (execDmc != null) { IStack stackService = getServicesTracker().getService(IStack.class); if (stackService != null) { stackService.getTopFrame(execDmc, new ImmediateDataRequestMonitor<IStack.IFrameDMContext>(rm) { @Override protected void handleSuccess() { getRegisters(getData(), groupDmc, containerDmc, rm); } @Override protected void handleFailure() { getRegisters(null, groupDmc, containerDmc, rm); } }); return; } } } getRegisters(frameDmc, groupDmc, containerDmc, rm); } else { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid group = " + groupDmc, null)); rm.done(); } }
Source:
<code><START> @Override public TaskResult syncShards() { <END> return periodicShardSyncManager.start(); }</code><technical_language>nit: Override in line</technical_language>

Target:
public TaskResult syncShards() { return periodicShardSyncManager.start(); }
Source:
<code>boolean isInWorkspace(IStorage storage) { final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); if (root != null) { <START> if (root.getFile(storage.getFullPath()).exists()) { <END> return true; } } return false; }</code><technical_language>change this "return root.getFile(storage.getFullPath()).isAccessible()" - in "if" return a boolean. - isAccessible() instead of exists() check project is open</technical_language>

Target:
boolean isInWorkspace(IStorage storage) { final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); if (root != null) { return root.getFile(storage.getFullPath()).isAccessible(); } return false; }
Source:
<code><START> public Secret getClientKey() { <END> return clientKey; }</code><technical_language>breaks binary compatibility. Usage example: <LINK_0></technical_language>

Target:
public String getClientKey() { return Secret.toString(clientKey); }
Source:
<code>private void awaitServerInitializationForJBossModulesBasedContainer(Instrumentation instrumentation) { while (true) { String loggingManagerClassName = System.getProperty("java.util.logging.manager"); if (loggingManagerClassName != null) { if (isClassLoaded(loggingManagerClassName, instrumentation)) { break; } } try { <START> Thread.sleep(200); <END> } catch (InterruptedException e) { throw new RuntimeException(e); } } }</code><technical_language>In fact I add some sort of (long) default timeout a resort log error. sth 5 minutes</technical_language>

Target:
private void awaitServerInitializationForJBossModulesBasedContainer(Instrumentation instrumentation) { int count = 0; while (count * LOGGING_DETECT_INTERVAL < LOGGING_DETECT_TIMEOUT) { String loggingManagerClassName = System.getProperty("java.util.logging.manager"); if (loggingManagerClassName != null) { if (isClassLoaded(loggingManagerClassName, instrumentation)) { return; } } try { Thread.sleep(LOGGING_DETECT_INTERVAL); count++; } catch (InterruptedException e) { throw new RuntimeException(e); } } throw new IllegalStateException(String.format("Detected JBoss Module loader, but property java.util.logging.manager is not set after %d seconds", LOGGING_DETECT_TIMEOUT / 1000)); }
Source:
<code>private void search() { <START> if (model != null) { <END> int fieldIndex = searchInput.getCmbFilterTypeIndex(); if (fieldIndex != -1) { JournalParameters parameters = new JournalParameters(); final JournalField field = FIELDS[fieldIndex]; parameters.setField(field); if (field == JournalField.RUN_NUMBER) { parameters.setNumbers(searchInput.getRunNumberFrom(), searchInput.getRunNumberTo()); } else if (field == JournalField.START_TIME) { parameters.setTimes(searchInput.getStartTimeFrom(), searchInput.getStartTimeTo()); } else { parameters.setSearchString(searchInput.getActiveSearchText()); } runSearchJob(parameters); } } }</code><technical_language>model null</technical_language>

Target:
private void search() { resetPageNumber(); int fieldIndex = searchInput.getCmbFilterTypeIndex(); JournalSearch search = null; final JournalField field = model.getSearchableFields().get(fieldIndex); if (field == JournalField.RUN_NUMBER) { search = new SearchNumber(field, searchInput.getRunNumberFrom(), searchInput.getRunNumberTo()); } else if (field == JournalField.START_TIME) { search = new SearchTime(field, searchInput.getStartTimeFrom(), searchInput.getStartTimeTo()); } else { search = new SearchString(field, searchInput.getActiveSearchText()); } model.setActiveSearch(search); setProgressIndicatorsVisible(true); model.setPageNumber(1).thenAccept(ignored -> setProgressIndicatorsVisible(false)); }
Source:
<code>private void handleException(VDSExceptionBase e, String reason) { final VDSReturnValue <START> vdsReturnValue = <END> getVDSReturnValue(); vdsReturnValue.setSucceeded(false); vdsReturnValue.setExceptionString(e.toString()); vdsReturnValue.setExceptionObject(e); vdsReturnValue.setVdsError(e.getVdsError()); final String msg = MessageFormatter .format("Failed to poll host - {}.", getParameters().getVdsId(), reason) .getMessage(); log.debug(msg, e); }</code><technical_language>this variable is used, forget something</technical_language>

Target:
private void handleException(VDSExceptionBase e, String reason) { setVdsRuntimeError(e); final String msg = MessageFormatter .format("Failed to poll host - {}.", getParameters().getVdsId(), reason) .getMessage(); log.debug(msg, e); }
Source:
<code>public default Type getCommonType() { <START> return getVariables().stream().map(v -> v.getType()) <END> .sorted((Comparator<Type<?>>) (a, b) -> a.getArrayLevel() - b.getArrayLevel()) .findFirst() .orElse(null); }</code><technical_language>conflicting #631 :-O I pull some PR's</technical_language>

Target:
default Type getCommonType() { NodeList<VariableDeclarator> variables = getVariables(); if (variables.isEmpty()) { throw new AssertionError("There is no common type since there are no variables."); } Type type = variables.get(0).getType(); for (int i = 1; i < variables.size(); i++) { if (!variables.get(i).getType().equals(type)) { throw new AssertionError("The variables do not have a common type."); } } return type; }
Source:
<code><START> protected DatastreamRuntimeException generateSendFailure(Exception exception) { <END> _dynamicMetricsManager.createOrUpdateMeter(_metricsNamesPrefix, AGGREGATE, PRODUCER_ERROR, 1); if (exception instanceof IllegalStateException) { _log.warn("sent failure transiently, exception: ", exception); return new DatastreamTransientException(exception); } else { _log.warn("sent failure, restart producer, exception: ", exception); shutdownProducer(); return new DatastreamRuntimeException(exception); } }</code><technical_language>I overriding this in Bounded implementation, this protected</technical_language>

Target:
DatastreamRuntimeException generateSendFailure(Exception exception) { _dynamicMetricsManager.createOrUpdateMeter(_metricsNamesPrefix, AGGREGATE, PRODUCER_ERROR, 1); if (exception instanceof IllegalStateException) { _log.warn("sent failure transiently, exception: ", exception); return new DatastreamTransientException(exception); } else { _log.warn("sent failure, restart producer, exception: ", exception); shutdownProducer(); return new DatastreamRuntimeException(exception); } }
Source:
<code>public void setupTopologyConfigId(long topologyConfigId) { CorfuStoreMetadata.Timestamp timestamp = corfuStore.getTimestamp(); long persistedTopologyConfigId = query(timestamp, LogReplicationMetadataType.TOPOLOGY_CONFIG_ID); if (topologyConfigId <= persistedTopologyConfigId) { log.warn("Skip setupTopologyConfigId. the current topologyConfigId is not larger than the persistedTopologyConfigID {}", topologyConfigId, persistedTopologyConfigId); return; } <START> TxBuilder txBuilder = corfuStore.tx(NAMESPACE, IsolationLevel.snapshot(timestamp)); <END> for (LogReplicationMetadataType type : LogReplicationMetadataType.values()) { long val = Address.NON_ADDRESS; if (type == LogReplicationMetadataType.TOPOLOGY_CONFIG_ID) { val = topologyConfigId; } appendUpdate(txBuilder, type, val); } txBuilder.commit(); log.info("Update topologyConfigId, new metadata {}", this); }</code><technical_language>replace getTxBuilder()</technical_language>

Target:
public void setupTopologyConfigId(long topologyConfigId) { CorfuStoreMetadata.Timestamp timestamp = corfuStore.getTimestamp(); long persistedTopologyConfigId = query(timestamp, LogReplicationMetadataType.TOPOLOGY_CONFIG_ID); if (topologyConfigId <= persistedTopologyConfigId) { log.warn("Skip setupTopologyConfigId. the current topologyConfigId is not larger than the persistedTopologyConfigID {}", topologyConfigId, persistedTopologyConfigId); return; } TxBuilder txBuilder = corfuStore.tx(NAMESPACE); for (LogReplicationMetadataType type : LogReplicationMetadataType.values()) { long val = Address.NON_ADDRESS; if (type == LogReplicationMetadataType.TOPOLOGY_CONFIG_ID) { val = topologyConfigId; } appendUpdate(txBuilder, type, val); } txBuilder.commit(timestamp); log.info("Update topologyConfigId, new metadata {}", this); }
Source:
<code>public void testNoCaching() throws Throwable { <START> MetadataManager metadata = METADATA_MANAGER; <END> ExpressionCompiler compiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, false)); ImmutableList.Builder<RowExpression> projectionsBuilder = ImmutableList.builder(); ArrayType arrayType = new ArrayType(VARCHAR); Signature signature = new Signature("concat", SCALAR, arrayType.getTypeSignature(), arrayType.getTypeSignature(), arrayType.getTypeSignature()); projectionsBuilder.add(new CallExpression(signature, arrayType, ImmutableList.of(field(0, arrayType), field(1, arrayType)))); ImmutableList<RowExpression> projections = projectionsBuilder.build(); PageProcessor pageProcessor = compiler.compilePageProcessor(Optional.empty(), projections).get(); PageProcessor pageProcessor2 = compiler.compilePageProcessor(Optional.empty(), projections).get(); assertTrue(pageProcessor != pageProcessor2); }</code><technical_language>test is this static METADATA_MANAGER, consistent other tests remove this create a new instance before/after methods (see below)</technical_language>

Target:
public void testNoCaching() throws Throwable { ImmutableList.Builder<RowExpression> projectionsBuilder = ImmutableList.builder(); ArrayType arrayType = new ArrayType(VARCHAR); Signature signature = new Signature("concat", SCALAR, arrayType.getTypeSignature(), arrayType.getTypeSignature(), arrayType.getTypeSignature()); projectionsBuilder.add(new CallExpression(signature, arrayType, ImmutableList.of(field(0, arrayType), field(1, arrayType)))); ImmutableList<RowExpression> projections = projectionsBuilder.build(); PageProcessor pageProcessor = compiler.compilePageProcessor(Optional.empty(), projections).get(); PageProcessor pageProcessor2 = compiler.compilePageProcessor(Optional.empty(), projections).get(); assertTrue(pageProcessor != pageProcessor2); }
Source:
<code>private RequestLog createRequestLog() { final Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); <START> requestLog.setLogTimeZone("GMT"); <END> requestLog.setLogLatency(true); return requestLog; }</code><technical_language>current http log files in UTC CEST</technical_language>

Target:
private RequestLog createRequestLog() { final Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone(ZoneId.systemDefault().getId()); requestLog.setLogLatency(true); return requestLog; }
Source:
<code>public void testToExecuteNotInstalledCommand_shouldThrowException() throws Exception { CommandProcessor cp = getOsgiService(CommandProcessor.class); CommandSession cs = cp.createSession(System.in, System.out, System.err); cs.execute("failing-command"); <START> fail("Exception should be thrown that the command does not exist"); <END> cs.close(); }</code><technical_language>CommandSession closed call of fail</technical_language>

Target:
public void testToExecuteNotInstalledCommand_shouldThrowException() throws Exception { CommandProcessor cp = getOsgiService(CommandProcessor.class); CommandSession cs = cp.createSession(System.in, System.out, System.err); cs.execute("failing-command"); cs.close(); fail("Exception should be thrown that the command does not exist"); }
Source:
<code>public RedisResponse executeCommand(Command command, ExecutionHandlerContext executionHandlerContext) { parameterRequirements.checkParameters(command, executionHandlerContext); <START> if (executor instanceof ResponseExecutor) { <END> return ((ResponseExecutor) executor).executeCommandWithResponse(command, executionHandlerContext); } executor.executeCommand(command, executionHandlerContext); return null; }</code><technical_language>change "Executor" "executeCommandsWithResponse"? For executors converted yet, executeCommandsWithResponse call executeCommand return null. get rid of this instanceof check</technical_language>

Target:
public RedisResponse executeCommand(Command command, ExecutionHandlerContext executionHandlerContext) { parameterRequirements.checkParameters(command, executionHandlerContext); return executor.executeCommandWithResponse(command, executionHandlerContext); }
Source:
<code>protected List<org.junit.rules.MethodRule> rules(Object target) { <START> List<org.junit.rules.MethodRule> rules = getTestClass().getAnnotatedFieldValues(target, Rule.class, <END> org.junit.rules.MethodRule.class); rules.addAll(getTestClass().getAnnotatedMethodValues(target, Rule.class, org.junit.rules.MethodRule.class)); return rules; }</code><technical_language>nit: need fully qualify MethodRule</technical_language>

Target:
protected List<MethodRule> rules(Object target) { List<MethodRule> rules = getTestClass().getAnnotatedMethodValues(target, Rule.class, MethodRule.class); rules.addAll(getTestClass().getAnnotatedFieldValues(target, Rule.class, MethodRule.class)); return rules; }
Source:
<code>public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof File, "this binder is only valid for File!"); checkNotNull(request, "request"); File dockerFile = (File) input; File tmpDir = Files.createTempDir(); final File targetFile = new File(tmpDir + File.separator + "Dockerfile"); try { Files.copy(dockerFile, targetFile); File archive = Archives.tar(tmpDir, File.createTempFile("archive", ".tar")); FileInputStream data = new FileInputStream(archive); Payload payload = Payloads.newInputStreamPayload(data); payload.getContentMetadata().setContentLength(data.getChannel().size()); payload.getContentMetadata().setContentType(MediaType.TEXT_PLAIN); request.setPayload(payload); } catch (IOException e) { <START> e.printStackTrace(); <END> } return request; }</code><technical_language>Properly log propagate exception prevent request sent</technical_language>

Target:
public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof File, "this binder is only valid for File!"); checkNotNull(request, "request"); File dockerFile = (File) input; File tmpDir = Files.createTempDir(); final File targetFile = new File(tmpDir + File.separator + "Dockerfile"); try { Files.copy(dockerFile, targetFile); File archive = Archives.tar(tmpDir, File.createTempFile("archive", ".tar")); FileInputStream data = new FileInputStream(archive); Payload payload = Payloads.newInputStreamPayload(data); payload.getContentMetadata().setContentLength(data.getChannel().size()); payload.getContentMetadata().setContentType("application/tar"); request.setPayload(payload); } catch (IOException e) { logger.error(e, "Couldn't create a tarball for %s", targetFile); throw Throwables.propagate(e); } return request; }
Source:
<code>protected String getSqlType(String schemaName, Schema.Type type) { final String sqlType; if (schemaName != null && logicalNameToSqlTypeMap.containsKey(schemaName)) { <START> sqlType = logicalNameToSqlTypeMap.get(schemaName); <END> } else { sqlType = schemaTypeToSqlTypeMap.get(type); } if (sqlType == null) { throw new ConnectException(String.format("%s type doesn't have a mapping to the SQL database column type", type)); } return sqlType; }</code><technical_language>avoid containsKey() lookup do get(), do a schemaTypeToSqlTypeMap lookup if (sqlType == null)</technical_language>

Target:
protected String getSqlType(String schemaName, Schema.Type type) { String sqlType = null; if (schemaName != null) { sqlType = logicalNameToSqlTypeMap.get(schemaName); } if (sqlType == null) { sqlType = schemaTypeToSqlTypeMap.get(type); } if (sqlType == null) { throw new ConnectException(String.format("%s type doesn't have a mapping to the SQL database column type", type)); } return sqlType; }
Source:
<code>public void simpleIntegrationTestNeg() throws Exception { TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, 4, 1, 1, "MasterSlave", true); ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient); ClusterConfig clusterConfig = configAccessor.getClusterConfig(clusterName); clusterConfig.getRecord() .setListField(ClusterConfig.ClusterConfigProperty.INSTANCE_CAPACITY_KEYS.name(), new ArrayList<>()); clusterConfig.setTopologyAwareEnabled(true); clusterConfig.setTopology("/Rack/Sub-Rack/Host/Instance"); clusterConfig.setFaultZoneType("Host"); configAccessor.setClusterConfig(clusterName, clusterConfig); String instanceName = "localhost_12918"; HelixManager participant = new ZKHelixManager(clusterName, instanceName , InstanceType.PARTICIPANT, ZK_ADDR); participant.getStateMachineEngine().registerStateModelFactory("MasterSlave", new MockMSModelFactory()); try { <START> participant.connect(); <END> } catch (IllegalArgumentException expected) { Assert.assertEquals(expected.getMessage(), "Domain for instance localhost_12918 is not set, fail the topology-aware placement!"); } ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance("localhost_12918"))); Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader())); }</code><technical_language>Assert fail protect test. if expecting exception is throw, test pass. fail</technical_language>

Target:
public void simpleIntegrationTestNeg() throws Exception { TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, 4, 1, 1, "MasterSlave", true); ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient); ClusterConfig clusterConfig = configAccessor.getClusterConfig(clusterName); clusterConfig.getRecord() .setListField(ClusterConfig.ClusterConfigProperty.INSTANCE_CAPACITY_KEYS.name(), new ArrayList<>()); clusterConfig.setTopologyAwareEnabled(true); clusterConfig.setTopology("/Rack/Sub-Rack/Host/Instance"); clusterConfig.setFaultZoneType("Host"); configAccessor.setClusterConfig(clusterName, clusterConfig); String instanceName = "localhost_12918"; HelixManager participant = new ZKHelixManager(clusterName, instanceName , InstanceType.PARTICIPANT, ZK_ADDR); participant.getStateMachineEngine().registerStateModelFactory("MasterSlave", new MockMSModelFactory()); try { participant.connect(); Assert.fail(); } catch (IllegalArgumentException expected) { Assert.assertEquals(expected.getMessage(), "Domain for instance localhost_12918 is not set, fail the topology-aware placement!"); } ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance("localhost_12918"))); Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader())); }
Source:
<code><START> public Builder withInteractive(Boolean interactive) { <END> this.interactive = interactive; return this; }</code><technical_language>@Nullable Boolean interactive</technical_language>

Target:
public Builder withInteractive(Boolean interactive) { this.interactive = checkNotNull(interactive); return this; }
Source:
<code>public void execute(Tuple input) { try { final Object tupleField = input.getValueByField(StreamlineEvent.STREAMLINE_EVENT); if (tupleField instanceof StreamlineEvent) { String genId = Long.toString(rand.nextLong()); StreamlineEvent event = (StreamlineEvent) tupleField; StreamlineEvent eventWithStream = getStreamlineEventWithStream((StreamlineEvent) event, input, genId); for (Result result : processorRuntime.process(eventWithStream)) { for (StreamlineEvent e : result.events) { collector.emit(result.stream, input, new Values(e)); } <START> } <END> } else { LOG.debug("Invalid tuple received. Tuple disregarded and rules not evaluated.\n\tTuple [{}]." + "\n\tStreamlineEvent [{}].", input, tupleField); collector.ack(input); } } catch (Exception e) { collector.fail(input); collector.reportError(e); LOG.debug("", e); } }</code><technical_language>input tuple is acked here</technical_language>

Target:
public void execute(Tuple input) { try { final Object tupleField = input.getValueByField(StreamlineEvent.STREAMLINE_EVENT); if (tupleField instanceof StreamlineEvent) { String genId = Long.toString(rand.nextLong()); StreamlineEvent event = (StreamlineEvent) tupleField; StreamlineEvent eventWithStream = getStreamlineEventWithStream(event, input, genId); for (Result result : processorRuntime.process(eventWithStream)) { for (StreamlineEvent e : result.events) { collector.emit(result.stream, input, new Values(e)); } } } else { LOG.debug("Invalid tuple received. Tuple disregarded and rules not evaluated.\n\tTuple [{}]." + "\n\tStreamlineEvent [{}].", input, tupleField); } collector.ack(input); } catch (Exception e) { collector.fail(input); collector.reportError(e); LOG.debug("", e); } }
Source:
<code>public void testInfo() throws Exception { String url = String.format("http://localhost:%d/rest/v2/cache-managers/default/", restServer().getPort()); ContentResponse response = client.newRequest(url).send(); ResponseAssertion.assertThat(response).isOk(); String json = response.getContentAsString(); JsonNode cmInfo = mapper.readTree(json); assertFalse(cmInfo.get("version").asText().isEmpty()); assertEquals(2, cmInfo.get("cluster_members").size()); assertEquals(2, cmInfo.get("cluster_members_physical_addresses").size()); assertTrue(cmInfo.get("local_site").isNull()); <START> } <END></code><technical_language>useful this test is :)</technical_language>

Target:
public void testInfo() throws Exception { String url = String.format("http://localhost:%d/rest/v2/cache-managers/default/", restServer().getPort()); ContentResponse response = client.newRequest(url).send(); ResponseAssertion.assertThat(response).isOk(); String json = response.getContentAsString(); JsonNode cmInfo = mapper.readTree(json); assertFalse(cmInfo.get("version").asText().isEmpty()); assertEquals(2, cmInfo.get("cluster_members").size()); assertEquals(2, cmInfo.get("cluster_members_physical_addresses").size()); assertEquals("LON-1", cmInfo.get("local_site").asText()); }
Source:
<code>public ModuleDefinition findDefinition(String name, ModuleType moduleType) { try { <START> for (String ext : SUFFIXES) { <END> String location = String.format("%s/%s/%s%s", root, moduleType.name(), name, ext); Resource[] resources = resolver.getResources(location); for (Resource resource : resources) { ModuleDefinition candidate = fromResource(resource); if (candidate != null) { return candidate; } } } } catch (IOException e) { throw new RuntimeIOException("An error occurred trying to locate modules", e); } return null; }</code><technical_language>prevent exploded jar version of name type</technical_language>

Target:
public ModuleDefinition findDefinition(String name, ModuleType moduleType) { List<ModuleDefinition> result = new ArrayList<ModuleDefinition>(); try { for (String ext : SUFFIXES) { String location = String.format("%s/%s/%s%s", root, moduleType.name(), name, ext); Resource[] resources = resolver.getResources(location); for (Resource resource : resources) { fromResource(resource, result); } } } catch (IOException e) { throw new RuntimeIOException(String.format("An error occurred trying to locate module '%s:%s'", moduleType, name), e); } return result.size() == 1 ? result.iterator().next() : null; }
Source:
<code>public Task importTask(String json) throws IOException { <START> LOGGER.info("Importing the task from json"); <END> ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); removeIgnoredFields(node); Task task = mapper.readValue(node, Task.class); List<DataSource> sources = task.getTaskConfig().getDataSources(); for (DataSource ds : sources) { TaskDataProvider provider = findProviderByName(ds); if (null != provider) { Long oldId = ds.getProviderId(); Long newId = provider.getId(); if (!oldId.equals(newId)) { replaceProviderId(task, oldId, newId); ds.setProviderId(newId); } } } save(task); return task; }</code><technical_language>a task</technical_language>

Target:
public Task importTask(String json) throws IOException { LOGGER.info("Importing a task from json"); LOGGER.trace("The json file: {}", json); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); removeIgnoredFields(node); Task task = mapper.readValue(node, Task.class); List<DataSource> sources = task.getTaskConfig().getDataSources(); for (DataSource ds : sources) { TaskDataProvider provider = findProviderByName(ds); if (null != provider) { Long oldId = ds.getProviderId(); Long newId = provider.getId(); if (!oldId.equals(newId)) { replaceProviderId(task, oldId, newId); ds.setProviderId(newId); } } } save(task); return task; }
Source:
<code>public static boolean callSpawnEntitySpawner(final List<Entity> entities, final PhaseContext<?> context) { try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.WORLD_SPAWNER); final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEventSpawner(frame.getCurrentCause(), entities); <START> if (ShouldFire.SPAWN_ENTITY_EVENT_SPAWNER) { <END> SpongeImpl.postEvent(event); } if (!event.isCancelled() && event.getEntities().size() > 0) { return EntityUtil.processEntitySpawnsFromEvent(context, event); } return false; } }</code><technical_language>this is intrinsically checked tracker captured for spawning if spawn events listened to</technical_language>

Target:
public static boolean callSpawnEntitySpawner(final List<Entity> entities, final PhaseContext<?> context) { try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.WORLD_SPAWNER); final SpawnEntityEvent event = SpongeEventFactory.createSpawnEntityEventSpawner(frame.getCurrentCause(), entities); SpongeImpl.postEvent(event); if (!event.isCancelled() && event.getEntities().size() > 0) { return EntityUtil.processEntitySpawnsFromEvent(context, event); } return false; } }
Source:
<code>public String getProcessorName() { return <START> RefactoringCoreMessages.RenameResourceProcessor_processor_name; <END> }</code><technical_language>a name RenameResourceProcessor</technical_language>

Target:
public String getProcessorName() { return RefactoringCoreMessages.MoveRenameResourceProcessor_processor_name; }
Source:
<code>public ConcurrentGrouper( final ByteBuffer buffer, final KeySerdeFactory<KeyType> keySerdeFactory, final ColumnSelectorFactory columnSelectorFactory, final AggregatorFactory[] aggregatorFactories, final int bufferGrouperMaxSize, final float bufferGrouperMaxLoadFactor, final int bufferGrouperInitialBuckets, final LimitedTemporaryStorage temporaryStorage, final ObjectMapper spillMapper, final int concurrencyHint ) { Preconditions.checkArgument(concurrencyHint > 0, "concurrencyHint > 0"); this.groupers = new ArrayList<>(concurrencyHint); this.threadLocalGrouper = new ThreadLocal<SpillingGrouper<KeyType>>() { @Override protected SpillingGrouper<KeyType> initialValue() { return groupers.get(threadNumber.getAndIncrement()); } }; final int sliceSize = (buffer.capacity() / concurrencyHint); for (int i = 0; i < concurrencyHint; i++) { final ByteBuffer slice = buffer.duplicate(); slice.position(sliceSize * i); slice.limit(slice.position() + sliceSize); groupers.add( new SpillingGrouper<>( slice.slice(), keySerdeFactory, columnSelectorFactory, aggregatorFactories, bufferGrouperMaxSize, bufferGrouperMaxLoadFactor, bufferGrouperInitialBuckets, temporaryStorage, spillMapper, false ) ); } <START> this.entryComparator = keySerdeFactory.factorize().entryComparator(); <END> }</code><technical_language>Factorizing throwing unused keySerde wrong; this a method KeySerdeFactory instead? KeySerdeFactory KeySerde, if life easier</technical_language>

Target:
public ConcurrentGrouper( final ByteBuffer buffer, final KeySerdeFactory<KeyType> keySerdeFactory, final ColumnSelectorFactory columnSelectorFactory, final AggregatorFactory[] aggregatorFactories, final int bufferGrouperMaxSize, final float bufferGrouperMaxLoadFactor, final int bufferGrouperInitialBuckets, final LimitedTemporaryStorage temporaryStorage, final ObjectMapper spillMapper, final int concurrencyHint ) { Preconditions.checkArgument(concurrencyHint > 0, "concurrencyHint > 0"); this.groupers = new ArrayList<>(concurrencyHint); this.threadLocalGrouper = new ThreadLocal<SpillingGrouper<KeyType>>() { @Override protected SpillingGrouper<KeyType> initialValue() { return groupers.get(threadNumber.getAndIncrement()); } }; final int sliceSize = (buffer.capacity() / concurrencyHint); for (int i = 0; i < concurrencyHint; i++) { final ByteBuffer slice = buffer.duplicate(); slice.position(sliceSize * i); slice.limit(slice.position() + sliceSize); groupers.add( new SpillingGrouper<>( slice.slice(), keySerdeFactory, columnSelectorFactory, aggregatorFactories, bufferGrouperMaxSize, bufferGrouperMaxLoadFactor, bufferGrouperInitialBuckets, temporaryStorage, spillMapper, false ) ); } this.keyObjComparator = keySerdeFactory.objectComparator(); }
Source:
<code>public void testExecute() throws Exception { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); String instructorId = instructor1OfCourse1.googleId; String courseId = instructor1OfCourse1.courseId; <START> <END> ______TS("Typical case, delete a soft-deleted course in Recycle Bin"); String[] submissionParams = new String[] { Const.ParamsNames.INSTRUCTOR_ID, instructorId, Const.ParamsNames.COURSE_ID, courseId, }; loginAsInstructor(instructorId); CoursesLogic.inst().moveCourseToRecycleBin(courseId); assertEquals(courseId, CoursesLogic.inst().getSoftDeletedCourseForInstructor(instructor1OfCourse1).getId()); DeleteCourseAction action = getAction(submissionParams); JsonResult result = getJsonResult(action); MessageOutput message = (MessageOutput) result.getOutput(); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); assertEquals("The course " + courseId + " has been permanently deleted.", message.getMessage()); }</code><technical_language>Add a case a is in recycle bin? -> fail</technical_language>

Target:
public void testExecute() throws Exception { ______TS("Not enough parameters"); verifyHttpParameterFailure(); InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); String instructorId = instructor1OfCourse1.googleId; String courseId = instructor1OfCourse1.courseId; ______TS("Typical case, delete a soft-deleted course in Recycle Bin"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, courseId, }; CourseAttributes courseToBeDeleted = logic.getCourse(courseId); loginAsInstructor(instructorId); logic.moveCourseToRecycleBin(courseToBeDeleted.getId()); assertEquals(courseId, logic.getSoftDeletedCourseForInstructor(instructor1OfCourse1).getId()); DeleteCourseAction deleteCourseAction = getAction(submissionParams); JsonResult result = getJsonResult(deleteCourseAction); MessageOutput messageOutput = (MessageOutput) result.getOutput(); assertEquals(HttpStatus.SC_OK, result.getStatusCode()); assertEquals("OK", messageOutput.getMessage()); assertNull(logic.getCourse(instructor1OfCourse1.courseId)); }
Source:
<code>private int getReadBarcodeValue(final SAMRecord record, final String tag) { <START> if (null == READ_ONE_BARCODE_TAG) return 0; <END> final String attr = record.getStringAttribute(tag); if (null == attr) return 0; else return attr.hashCode(); }</code><technical_language>Is this supposed checking tag instead of READ_ONE_BARCODE_TAG</technical_language>

Target:
public static int getReadBarcodeValue(final SAMRecord record, final String tag) { if (null == tag) return 0; final String attr = record.getStringAttribute(tag); if (null == attr) return 0; else return attr.hashCode(); }
Source:
<code>private String getDefaultTextValue(FormField field) { Map<String, String> fieldAttributes = new HashMap<String, String>(); fieldAttributes.putAll(field.getFormControl().getAttributesMap()); fieldAttributes.put("Control Type", field.getFormControl().getFormControlType().name()); <START> return this.valueGenerator.getValue(null, null, fieldAttributes); <END> }</code><technical_language>modified SpiderHtmlFormParser return a URI DefaultValueGenerator instead of a null. this creating a new variable of type URI adding a line of code parsing method stored URI in new variable. this approach for supplying URI ValueGenerator, is another returning it</technical_language>

Target:
private List<String> getDefaultTextValue(FormField field) { String fieldId = field.getName(); Map<String, String> fieldAttributes = new HashMap<String, String>(); List<String> definedValues = new ArrayList<String>(); fieldAttributes.putAll(field.getFormControl().getAttributesMap()); fieldAttributes.put("Control Type", field.getFormControl().getFormControlType().name()); if (field.getFormControl().getFormControlType().isSubmit()) { List<String> submitFields = new ArrayList<String>(); for (String value : field.getPredefinedValues()){ String finalValue = this.valueGenerator.getValue(uri, url, fieldId, value, definedValues, envAttributes, fieldAttributes); submitFields.add(finalValue); } return submitFields; } List<String> values = field.getValues(); String defaultValue; if(field.getFormControl().getAttributesMap().containsKey("value")){ defaultValue = field.getFormControl().getAttributesMap().get("value"); } if (log.isDebugEnabled()) { log.debug("Existing values: " + values); } if (values.isEmpty() || (values.size() == 1 && values.get(0).isEmpty())) { defaultValue = DEFAULT_EMPTY_VALUE; Collection<String> predefValues = field.getPredefinedValues(); if (!predefValues.isEmpty()) { definedValues.addAll(predefValues); Iterator<String> iterator = predefValues.iterator(); defaultValue = iterator.next(); if (iterator.hasNext()) { defaultValue = iterator.next(); } } } else { defaultValue = values.get(0); } String finalValue = this.valueGenerator.getValue(uri, url, fieldId, defaultValue, definedValues, envAttributes, fieldAttributes); log.debug("Generated: " + finalValue + "For field " + field.getName()); values = new ArrayList<>(1); values.add(finalValue); return values; }
Source:
<code>private static void applyArtifactInNormalFilter(final M2FiltersArgumentCollection MTFAC, final VariantContext vc, final Collection<String> filters) { if (!vc.hasAttribute(SomaticGenotypingEngine.NORMAL_ARTIFACT_LOD_ATTRIBUTE)) { return; } <START> final double normalArtifactLod = MathUtils.arrayMax(GATKProtectedVariantContextUtils.getAttributeAsDoubleArray(vc, SomaticGenotypingEngine.NORMAL_ARTIFACT_LOD_ATTRIBUTE, () -> null, -1)); <END> if (normalArtifactLod > MTFAC.NORMAL_ARTIFACT_LOD_THRESHOLD) { filters.add(ARTIFACT_IN_NORMAL_FILTER_NAME); } }</code><technical_language>want normal artifact lod of alt allele highest tumor lod? alt alleles: A->C A->AC, A->C is a real somatic mutation A->AC is artifact. assume A->C a higher tumor lod. do want filter this site if get a high normal artifact lod for A->AC</technical_language>

Target:
private static void applyArtifactInNormalFilter(final M2FiltersArgumentCollection MTFAC, final VariantContext vc, final Collection<String> filters) { if (!( vc.hasAttribute(SomaticGenotypingEngine.NORMAL_ARTIFACT_LOD_ATTRIBUTE) && vc.hasAttribute(GATKVCFConstants.TUMOR_LOD_KEY))) { return; } final double[] normalArtifactLods = getArrayAttribute(vc, SomaticGenotypingEngine.NORMAL_ARTIFACT_LOD_ATTRIBUTE); final double[] tumorLods = getArrayAttribute(vc, GATKVCFConstants.TUMOR_LOD_KEY); final int indexOfMaxTumorLod = MathUtils.maxElementIndex(tumorLods); if (normalArtifactLods[indexOfMaxTumorLod] > MTFAC.NORMAL_ARTIFACT_LOD_THRESHOLD) { filters.add(ARTIFACT_IN_NORMAL_FILTER_NAME); } }
Source:
<code><START> public Secret getId() { properties.getId(); return this; } <END></code><technical_language>Huh</technical_language>

Target:
public String getId() { return properties.getId(); }
Source:
<code>public SearchResult query(final SearchQuery query) { final String input = query.getInput(); final CriteriaBuilder builder = new CriteriaBuilder(OnmsMonitoringLocation.class) .ilike("locationName", QueryUtils.ilike(input)) .orderBy("locationName") .distinct(); final int totalCount = monitoringLocationDao.countMatching(builder.toCriteria()); final Criteria criteria = builder.limit(query.getMaxResults()).toCriteria(); final List<OnmsMonitoringLocation> matchingResult = monitoringLocationDao.findMatching(criteria); final List<SearchResultItem> searchResultItems = matchingResult.stream().map(monitoringLocation -> { final SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setIdentifier(monitoringLocation.getLocationName()); searchResultItem.setLabel("Show nodes in location '" + monitoringLocation.getLocationName() + "'"); <START> searchResultItem.setUrl("element/nodeList.htm?monitoringLocation=" + monitoringLocation.getLocationName()); <END> return searchResultItem; }).collect(Collectors.toList()); final SearchResult searchResult = new SearchResult(Contexts.Action).withMore(totalCount > searchResultItems.size()).withResults(searchResultItems); return searchResult; }</code><technical_language>Similarly here, monitoringLocation.getLocationName() URL encoded</technical_language>

Target:
public SearchResult query(final SearchQuery query) { final String input = query.getInput(); final CriteriaBuilder builder = new CriteriaBuilder(OnmsMonitoringLocation.class) .ilike("locationName", QueryUtils.ilike(input)) .orderBy("locationName") .distinct(); final int totalCount = monitoringLocationDao.countMatching(builder.toCriteria()); final Criteria criteria = builder.limit(query.getMaxResults()).toCriteria(); final List<OnmsMonitoringLocation> matchingResult = monitoringLocationDao.findMatching(criteria); final List<SearchResultItem> searchResultItems = matchingResult.stream().map(monitoringLocation -> { final SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setIdentifier(monitoringLocation.getLocationName()); searchResultItem.setLabel("Show nodes in location '" + monitoringLocation.getLocationName() + "'"); searchResultItem.setUrl("element/nodeList.htm?monitoringLocation=" + UrlUtils.encode(monitoringLocation.getLocationName())); return searchResultItem; }).collect(Collectors.toList()); final SearchResult searchResult = new SearchResult(Contexts.Action).withMore(totalCount > searchResultItems.size()).withResults(searchResultItems); return searchResult; }
Source:
<code>protected void verifyOutput(UserDTO source, User dest, boolean childrenGenerated) { if (source != null) { assertEquals(source.getId(), dest.getId()); assertEquals(source.getUsername(), dest.getUsername()); assertEquals(source.getSuperAdmin(), dest.isSuperAdmin()); <START> assertNotNull(source.getPassword()); assertNotNull(dest.getPassword()); <END> } else { assertNull(dest); } }</code><technical_language>translating User UserDTO translating password, opposite, password get translated hashed. expect this kind of assertion here: assertEquals(Util.hash(source.getPassword()), dest.getHashedPassword())</technical_language>

Target:
protected void verifyOutput(UserDTO source, User dest, boolean childrenGenerated) { if (source != null) { assertEquals(source.getUsername(), dest.getUsername()); assertEquals(source.getSuperAdmin(), dest.isSuperAdmin()); assertEquals(Util.hash(source.getPassword()), dest.getHashedPassword()); } else { assertNull(dest); } }
Source:
<code>private void requestState() { <START> new Thread(new Runnable() { <END> @Override public void run() { for (String cmd : Arrays.asList("PW?", "MS?", "MV?", "ZM?", "MU?", "SI?", "Z2?", "Z2MU?", "Z3", "Z3MU?", "NSE")) { internSendCommandTelnet(cmd); try { Thread.sleep(300); } catch (InterruptedException e) { logger.trace("Interrupted while requesting state", e); } } } }).start(); }</code><technical_language>[Dev guidelines](<LINK_0> creation of threads avoided</technical_language>

Target:
private void requestState() { executor.execute(new Runnable() { @Override public void run() { for (String cmd : Arrays.asList("PW?", "MS?", "MV?", "ZM?", "MU?", "SI?", "Z2?", "Z2MU?", "Z3", "Z3MU?", "NSE")) { internSendCommandTelnet(cmd); try { Thread.sleep(300); } catch (InterruptedException e) { logger.trace("Interrupted while requesting state", e); } } } }); }
Source:
<code>private IWindowComponent wrapActivity(final Activity activity) { if (activity == null) { throw new IllegalArgumentException("activity"); } return new IWindowComponent() { <START> Activity mRefActivity = activity; <END> @Override public void startActivityForResult(Intent intent, int requestCode) { if (mRefActivity != null) { mRefActivity.startActivityForResult(intent, requestCode); } } }; }</code><technical_language>this, making this private? break anything? #Closed</technical_language>

Target:
private IWindowComponent wrapActivity(final Activity activity) { if (activity == null) { throw new IllegalArgumentException("activity"); } return new IWindowComponent() { private Activity mRefActivity = activity; @Override public void startActivityForResult(Intent intent, int requestCode) { if (mRefActivity != null) { mRefActivity.startActivityForResult(intent, requestCode); } } }; }