auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Execution onRegion(Region region) { if (region == null) { throw new FunctionException("Region instance passed is null"); } <START> if (region.getAttributes() == null) { <END> ((LocalRegion) region).getCancelCriterion().checkCancelInProgress(); throw new FunctionException("Region attributes is null"); } ProxyCache proxyCache = null; String poolName = region.getAttributes().getPoolName(); if (poolName != null) { Pool pool = findPool(poolName); if (pool == null) { throw new IllegalStateException(String.format("Could not find a pool named %s.", poolName)); } else { if (pool.getMultiuserAuthentication()) { if (region instanceof ProxyRegion) { ProxyRegion proxyRegion = (ProxyRegion) region; region = proxyRegion.getRealRegion(); proxyCache = proxyRegion.getAuthenticatedCache(); } else { throw new UnsupportedOperationException(); } } } } if (isClientRegion(region)) { return new ServerRegionFunctionExecutor(region, proxyCache); } if (PartitionRegionHelper.isPartitionedRegion(region)) { return new PartitionedRegionFunctionExecutor(region); } return new DistributedRegionFunctionExecutor(region); }</code><technical_language>check if (region.isDestroyed()) here? throw FunctionException region is destroyed</technical_language>

Target:
public Execution onRegion(Region region) { if (region == null) { throw new FunctionException("Region instance passed is null"); } if (region.isDestroyed()) { throw new FunctionException("Region is destroyed"); } ProxyCache proxyCache = null; String poolName = region.getAttributes().getPoolName(); if (poolName != null) { Pool pool = findPool(poolName); if (pool == null) { throw new IllegalStateException(String.format("Could not find a pool named %s.", poolName)); } else { if (pool.getMultiuserAuthentication()) { if (region instanceof ProxyRegion) { ProxyRegion proxyRegion = (ProxyRegion) region; region = proxyRegion.getRealRegion(); proxyCache = proxyRegion.getAuthenticatedCache(); } else { throw new UnsupportedOperationException(); } } } } if (isClientRegion(region)) { return new ServerRegionFunctionExecutor(region, proxyCache); } if (PartitionRegionHelper.isPartitionedRegion(region)) { return new PartitionedRegionFunctionExecutor(region); } return new DistributedRegionFunctionExecutor(region); }
Source:
<code>public void init(ICommonContentExtensionSite aConfig) { super.init(aConfig); this.model = new NestedProjectsProblemsModel(); this.refreshModelJob = refreshSeverities(); refreshSeveritiesOnProblemMarkerChange = event -> { if (event.getDelta() == null) { return; } MarkerManager markerManager = ((Workspace) WorkbenchNavigatorPlugin.getWorkspace()).getMarkerManager(); try { event.getDelta().accept(delta -> { IMarkerDelta[] markerDeltas = delta.getMarkerDeltas(); for (IMarkerDelta markerDelta : markerDeltas) { if (markerManager.isSubtype(markerDelta.getType(), IMarker.PROBLEM)) { <START> model.markDirty(Collections.singleton(markerDelta.getResource())); <END> } } return true; }); } catch (CoreException e) { WorkbenchNavigatorPlugin.log(e.getMessage(), new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, e.getMessage(), e)); } if (model.isDirty()) { this.refreshModelJob = refreshSeverities(); this.refreshModelJob.thenAccept(model -> { for (StructuredViewer viewer : viewersToUpdate) { viewer.update(model.getResourcesWithModifiedSeverity().toArray(), new String[] {}); } }); } }; WorkbenchNavigatorPlugin.getWorkspace().addResourceChangeListener(refreshSeveritiesOnProblemMarkerChange); }</code><technical_language>If I remember right, this return null</technical_language>

Target:
public void init(ICommonContentExtensionSite aConfig) { super.init(aConfig); this.model = new NestedProjectsProblemsModel(); this.refreshModelJob = refreshSeverities(); refreshSeveritiesOnProblemMarkerChange = event -> { if (event.getDelta() == null) { return; } MarkerManager markerManager = ((Workspace) WorkbenchNavigatorPlugin.getWorkspace()).getMarkerManager(); try { event.getDelta().accept(delta -> { IMarkerDelta[] markerDeltas = delta.getMarkerDeltas(); for (IMarkerDelta markerDelta : markerDeltas) { if (markerManager.isSubtype(markerDelta.getType(), IMarker.PROBLEM)) { IResource resource = markerDelta.getResource(); if (resource != null) { model.markDirty(Collections.singleton(markerDelta.getResource())); } } } return true; }); } catch (CoreException e) { WorkbenchNavigatorPlugin.log(e.getMessage(), new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, e.getMessage(), e)); } if (model.isDirty()) { this.refreshModelJob = refreshSeverities(); this.refreshModelJob.thenAccept(model -> { Object[] toUpdate = model.getResourcesWithModifiedSeverity().toArray(); for (StructuredViewer viewer : viewersToUpdate) { viewer.update(toUpdate, new String[] {}); } }); } }; WorkbenchNavigatorPlugin.getWorkspace().addResourceChangeListener(refreshSeveritiesOnProblemMarkerChange); }
Source:
<code>public void logsOnlyOnceEvenIfManyRequestsAreSlow() { makeOperationsTakeSpecifiedDuration(LONG_DURATION); for (int i = 0; i < 100; i++) { profilingTimelockService.lockImmutableTimestamp(); } makeOperationsTakeSpecifiedDuration(SHORT_DURATION); allowLogging(); profilingTimelockService.startIdentifiedAtlasDbTransaction(); <START> verifyLoggerInvokedWithSpecificProfile("lockImmutableTimestamp", LONG_DURATION); <END> verifyNoMoreInteractions(logger); }</code><technical_language>verify done once?, I remember if calling verify is once</technical_language>

Target:
public void logsOnlyOnceEvenIfManyRequestsAreSlow() { for (int i = 0; i < 100; i++) { accumulateLogsWithCall(LONG_DURATION, profilingTimelockService::lockImmutableTimestamp); } flushLogsWithCall(SHORT_DURATION, profilingTimelockService::startIdentifiedAtlasDbTransaction); verifyLoggerInvokedOnceWithSpecificProfile("lockImmutableTimestamp", LONG_DURATION); verifyNoMoreInteractions(logger); }
Source:
<code>public Stream<BooleanResult> nodeManualIndexExists( @Name( "indexName" ) String legacyIndexName ) { BooleanResult result = new BooleanResult( graphDatabaseAPI.index().existsForNodes( legacyIndexName ) ); <START> ArrayList<BooleanResult> arrayResult = new ArrayList<>(); <END> arrayResult.add( result ); return arrayResult.stream(); }</code><technical_language>Stream#of() convert single element stream</technical_language>

Target:
public Stream<BooleanResult> nodeManualIndexExists( @Name( "indexName" ) String legacyIndexName ) { return Stream.of( new BooleanResult( graphDatabaseAPI.index().existsForNodes( legacyIndexName ) ) ); }
Source:
<code>public void testGitHubAppEndpoints() throws Exception { CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = client.addService(serviceRepo, "admin@admin.com", installationId); assertNotNull(service); service = client.upsertServiceVersion(serviceRepo, "1.0", installationId); assertNotNull(service); assertEquals("Should have a new version", 1, service.getWorkflowVersions().size()); assertEquals("Should have 3 source files", 3, service.getWorkflowVersions().get(0).getSourceFiles().size()); service = client.addService(serviceRepo, "DockstoreTestUser2", installationId); assertNotNull(service); <START> assertEquals("Should have 2 users, has " + service.getUsers().size(), service.getUsers().size(), 2); <END> }</code><technical_language>Flip order of 2 parameters. need a short message automatically prints out expected actual</technical_language>

Target:
public void testGitHubAppEndpoints() throws Exception { final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = client.addService(serviceRepo, "admin@admin.com", installationId); assertNotNull(service); service = client.upsertServiceVersion(serviceRepo, "DockstoreTestUser2", "1.0", installationId); assertNotNull(service); assertEquals("Should have a new version", 1, service.getWorkflowVersions().size()); assertEquals("Should have 3 source files", 3, service.getWorkflowVersions().get(0).getSourceFiles().size()); assertEquals("Should have 2 users", 2, service.getUsers().size()); final long count = testingPostgres .runSelectStatement("select count(*) from service where sourcecontrol = 'github.com' and organization = 'DockstoreTestUser2' and repository = 'test-service'", new ScalarHandler<>()); Assert.assertEquals("there should be one matching service", 1, count); }
Source:
<code>public void setLeaderEventPublisher(LeaderEventPublisher leaderEventPublisher) { <START> Assert.notNull(leaderEventPublisher); <END> this.leaderEventPublisher = leaderEventPublisher; }</code><technical_language>Need some message. This method is deprecated in Spring 5.0 already..</technical_language>

Target:
public void setLeaderEventPublisher(LeaderEventPublisher leaderEventPublisher) { Assert.notNull(leaderEventPublisher, "leaderEventPublisher cannot be null"); this.leaderEventPublisher = leaderEventPublisher; }
Source:
<code>public DynamoDbDatastoreDialog(final WindowContext windowContext, final MutableDatastoreCatalog catalog, @Nullable final DynamoDbDatastore originalDatastore, final UserPreferences userPreferences) { super(originalDatastore, catalog, windowContext, userPreferences); <START> _regionField = new DCComboBox<>(Regions.values()); <END> _regionField.setSelectedItem(Regions.DEFAULT_REGION); _accessKeyField = WidgetFactory.createTextField(); _accessSecretField = WidgetFactory.createPasswordField(); _accessKeyField.getDocument().addDocumentListener(new DCDocumentListener() { @Override protected void onChange(final DocumentEvent event) { validateAndUpdate(); } }); _accessSecretField.getDocument().addDocumentListener(new DCDocumentListener() { @Override protected void onChange(final DocumentEvent event) { validateAndUpdate(); } }); if (originalDatastore == null) { _tableDefinitionWidget = new TableDefinitionOptionSelectionPanel(windowContext, this, null); } else { _datastoreNameTextField.setText(originalDatastore.getName()); _datastoreNameTextField.setEnabled(false); _accessKeyField.setText(originalDatastore.getAccessKey()); _accessSecretField.setText(originalDatastore.getAccessSecret()); final String originalRegion = originalDatastore.getRegion(); try { final Regions region = Regions.fromName(originalRegion); _regionField.setSelectedItem(region); } catch (IllegalArgumentException e) { } _tableDefinitionWidget = new TableDefinitionOptionSelectionPanel(windowContext, this, originalDatastore.getTableDefs()); } }</code><technical_language>nuke silly _ checkstyle, do I remember wrong</technical_language>

Target:
public DynamoDbDatastoreDialog(final WindowContext windowContext, final MutableDatastoreCatalog catalog, @Nullable final DynamoDbDatastore originalDatastore, final UserPreferences userPreferences) { super(originalDatastore, catalog, windowContext, userPreferences); _regionField = new DCComboBox<>(Regions.values()); _regionField.setSelectedItem(Regions.DEFAULT_REGION); _accessKeyIdField = WidgetFactory.createTextField(); _secretAccessKeyField = WidgetFactory.createPasswordField(); _accessKeyIdField.getDocument().addDocumentListener(new DCDocumentListener() { @Override protected void onChange(final DocumentEvent event) { validateAndUpdate(); } }); _secretAccessKeyField.getDocument().addDocumentListener(new DCDocumentListener() { @Override protected void onChange(final DocumentEvent event) { validateAndUpdate(); } }); if (originalDatastore == null) { _tableDefinitionWidget = new TableDefinitionOptionSelectionPanel(windowContext, this, null); } else { _datastoreNameTextField.setText(originalDatastore.getName()); _datastoreNameTextField.setEnabled(false); _accessKeyIdField.setText(originalDatastore.getAccessKeyId()); _secretAccessKeyField.setText(originalDatastore.getSecretAccessKey()); final String originalRegion = originalDatastore.getRegion(); try { final Regions region = Regions.fromName(originalRegion); _regionField.setSelectedItem(region); } catch (IllegalArgumentException e) { } _tableDefinitionWidget = new TableDefinitionOptionSelectionPanel(windowContext, this, originalDatastore.getTableDefs()); } }
Source:
<code>public Object executeScript(ScriptSource scriptSource, Map<String, Object> variables) { Object result = null; try { if (variables != null) { for (Entry<String, Object> entry : variables.entrySet()) { scriptEngine.put(entry.getKey(), entry.getValue()); } } scriptSource.isModified(); <START> String script = scriptSource.getScriptAsString(); <END> Date start = new Date(); if (logger.isDebugEnabled()) { logger.debug("executing script: " + script); } result = scriptEngine.eval(script); result = postProcess(result, scriptEngine, script); if (logger.isDebugEnabled()) { logger.debug("script executed in " + (new Date().getTime() - start.getTime()) + " ms"); } } catch (Exception e) { throw new ScriptingException(e.getMessage(), e); } return result; }</code><technical_language>code in GroovyScriptFactory ? if (...isModified()) {...getScriptAsString() } Or, simply embed isModified() call in getScriptAsString()</technical_language>

Target:
public Object executeScript(ScriptSource scriptSource, Map<String, Object> variables) { Object result = null; try { if (variables != null) { for (Entry<String, Object> entry : variables.entrySet()) { scriptEngine.put(entry.getKey(), entry.getValue()); } } String script = scriptSource.getScriptAsString(); Date start = new Date(); if (logger.isDebugEnabled()) { logger.debug("executing script: " + script); } result = scriptEngine.eval(script); result = postProcess(result, scriptEngine, script); if (logger.isDebugEnabled()) { logger.debug("script executed in " + (new Date().getTime() - start.getTime()) + " ms"); } } catch (Exception e) { throw new ScriptingException(e.getMessage(), e); } return result; }
Source:
<code>private static boolean isZeroDimension(ArrayDimensionTree dim) { ExpressionTree expression = dim.expression(); <START> return expression == null || (expression.is(Tree.Kind.INT_LITERAL) && "0".equals(((LiteralTree) expression).value())); <END> }</code><technical_language>method name match this behavior. If expression == null dimension of array is zero. means initializer defines size</technical_language>

Target:
private static boolean isZeroDimension(ArrayDimensionTree dim) { ExpressionTree expression = dim.expression(); return expression != null && expression.is(Tree.Kind.INT_LITERAL) && "0".equals(((LiteralTree) expression).value()); }
Source:
<code>public Team update(Long teamId, TeamDTO input) { Team current = this.getTeamById(teamId).get(); current.setTeamName(input.getTeamName()); <START> User captian = userService.getUserById(input.getCaptainID()).get(); <END> current.setCaptain(captian); return teamRepository.saveAndFlush(current); }</code><technical_language>typo</technical_language>

Target:
public Team update(Long teamId, TeamDTO input) { Team current = this.getTeamById(teamId).get(); current.setTeamName(input.getTeamName()); User captain = userService.getUserById(input.getCaptainID()).get(); current.setCaptain(captain); return teamRepository.saveAndFlush(current); }
Source:
<code>private Function<Void, CompletionStage<Void>> bootstrap( List<CompletableFuture<?>> toCancelFutures, KubernetesMachineImpl machine) { final Span activeSpan = tracerUtil.getActiveSpan(); return ignored -> { <START> Span tracingSpan = <END> tracerUtil.buildSpan( "BootstrapInstallers", activeSpan, getContext().getIdentity().getWorkspaceId(), machine.getName()); final InternalMachineConfig machineConfig = getContext().getEnvironment().getMachines().get(machine.getName()); LOG.debug( "Bootstrapping machine '{}' in workspace '{}'", machine.getName(), getContext().getIdentity().getWorkspaceId()); final CompletableFuture<Void> bootstrapperFuture; if (!machineConfig.getInstallers().isEmpty()) { bootstrapperFuture = bootstrapperFactory .create( getContext().getIdentity(), machineConfig.getInstallers(), machine, namespace, startSynchronizer) .bootstrapAsync(); bootstrapperFuture.whenComplete((res, ex) -> tracerUtil.finishSpan(tracingSpan)); toCancelFutures.add(bootstrapperFuture); } else { bootstrapperFuture = CompletableFuture.completedFuture(null); } return bootstrapperFuture; }; }</code><technical_language>Refactoring this moving span creation code a separate method simplify this method. this method is bootstrapping tracing benefit moving tracing details out of implementation details</technical_language>

Target:
private Function<Void, CompletionStage<Void>> bootstrap( List<CompletableFuture<?>> toCancelFutures, KubernetesMachineImpl machine) { final Span activeSpan = tracerUtil.getActiveSpan(); return ignored -> { Span tracingSpan = tracerUtil.buildSpan( "BootstrapInstallers", activeSpan, getContext().getIdentity().getWorkspaceId(), machine.getName()); final InternalMachineConfig machineConfig = getContext().getEnvironment().getMachines().get(machine.getName()); LOG.debug( "Bootstrapping machine '{}' in workspace '{}'", machine.getName(), getContext().getIdentity().getWorkspaceId()); final CompletableFuture<Void> bootstrapperFuture; if (!machineConfig.getInstallers().isEmpty()) { bootstrapperFuture = bootstrapperFactory .create( getContext().getIdentity(), machineConfig.getInstallers(), machine, namespace, startSynchronizer) .bootstrapAsync(); bootstrapperFuture.whenComplete( (res, ex) -> { if (ex != null) { tracerUtil.finishSpanAsFailure(tracingSpan, ex.getMessage()); } else { tracerUtil.finishSpan(tracingSpan); } }); toCancelFutures.add(bootstrapperFuture); } else { bootstrapperFuture = CompletableFuture.completedFuture(null); } return bootstrapperFuture; }; }
Source:
<code>public long getWrittenPositions() { return operatorSummaries.stream() .filter(stats -> stats.getOperatorType().equals(TableWriterOperator.class.getSimpleName())) <START> .map(stats -> stats.getInputPositions()) <END> .reduce(0L, Long::sum); }</code><technical_language>mapToLong sum()</technical_language>

Target:
public long getWrittenPositions() { return operatorSummaries.stream() .filter(stats -> stats.getOperatorType().equals(TableWriterOperator.class.getSimpleName())) .mapToLong(stats -> stats.getInputPositions()) .sum(); }
Source:
<code>private FieldValueCounter getOrCreate(String name) { <START> synchronized (map) { <END> FieldValueCounter result = findOne(name); if (result == null) { result = create(name); result = save(result); } return result; } }</code><technical_language>synchonized is needed here, increment/decrement protect</technical_language>

Target:
private FieldValueCounter getOrCreate(String name) { FieldValueCounter result = findOne(name); if (result == null) { synchronized (map) { result = create(name); } result = save(result); } return result; }
Source:
<code>private String getFileContents(String filename) throws FileNotFoundException, IOException { StringBuilder sb = new StringBuilder(); <START> BufferedReader br = new BufferedReader(new FileReader(filename)); <END> try { String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } } finally { br.close(); } return sb.toString(); }</code><technical_language>I read file contents lines of code, especially in Java 8. like: java return Files.lines(filename).collect(Collectors.joining(System.lineSeparator()));</technical_language>

Target:
private String getFileContents(String filename) throws IOException { Path filePath = Paths.get(filename); return Files.lines(filePath).collect(Collectors.joining(System.lineSeparator())); }
Source:
<code>public LocalPageStore(LocalPageStoreOptions options) { mRoot = options.getRootDir(); mPageSize = options.getPageSize(); mCacheSize = options.getCacheSize(); mFileBuckets = options.getFileBuckets(); mPagePattern = Pattern.compile( <START> String.format("%s/%d/(\\d+)/([^/]+)/(\\d+)", Pattern.quote(mRoot), mPageSize)); <END> }</code><technical_language>tricky for user deal trailing slash if configured path normalizing it</technical_language>

Target:
public LocalPageStore(LocalPageStoreOptions options) { mRoot = options.getRootDir(); mPageSize = options.getPageSize(); mCacheSize = options.getCacheSize(); mFileBuckets = options.getFileBuckets(); Path rootDir = Paths.get(mRoot); mPagePattern = Pattern.compile( String.format("%s/%d/(\\d+)/([^/]+)/(\\d+)", Pattern.quote(rootDir.toString()), mPageSize)); }
Source:
<code>protected void addCanDoActionMessageVariable(String varName, Object varValue) { <START> String message = String.format("$%s %s", varName, varValue); <END> getReturnValue().getCanDoActionMessages().add(message); }</code><technical_language>feel free inline this. need for String message temp variable</technical_language>

Target:
protected void addCanDoActionMessageVariable(String varName, Object varValue) { getReturnValue().getCanDoActionMessages().add(String.format("$%s %s", varName, varValue)); }
Source:
<code>public void testMassive() { FixedDoubleBreakdownHistogram histogram = new FixedDoubleBreakdownHistogram(100, 0.0, 1.0); ArrayList<Double> values = new ArrayList<>(); ArrayList<Double> weights = new ArrayList<>(); <START> IntStream.range(0, 1000000).forEach(i -> { <END> double value = Math.random(); double weight = ((int) (10 * Math.random())) / 10.0; values.add(value); weights.add(weight); histogram.add(value, weight, 1); }); Streams.stream(histogram.iterator()).forEach(b -> { long count = IntStream.range(0, values.size()) .filter(i -> b.getLeft() < values.get(i) && values.get(i) <= b.getRight() && b.getWeight() == weights.get(i)) .count(); assertEquals(b.getCount(), count); }); }</code><technical_language>nit: for-loop</technical_language>

Target:
public void testMassive() { FixedDoubleBreakdownHistogram histogram = new FixedDoubleBreakdownHistogram(100, 0.0, 1.0); ArrayList<Double> values = new ArrayList<>(); ArrayList<Double> weights = new ArrayList<>(); for (int i = 0; i < 1000000; ++i) { double value = Math.random(); double weight = ((int) (10 * Math.random())) / 10.0; values.add(value); weights.add(weight); histogram.add(value, weight, 1); } Streams.stream(histogram.iterator()).forEach(bucketWeight -> { long count = 0; for (int i = 0; i < values.size(); ++i) { if (bucketWeight.getLeft() < values.get(i) && values.get(i) <= bucketWeight.getRight() && bucketWeight.getWeight() == weights.get(i)) { ++count; } } assertEquals(bucketWeight.getCount(), count); }); }
Source:
<code>private boolean specialCaseMapEntries(String propName, FunctionType propertyType) { if (propertyType.getMaxArity() != 0 || !propName.equals("entries")) { return false; } ImmutableList<JSType> ttypes = null; JSType returnType = propertyType.getReturnType(); <START> if (returnType.isTemplatizedType()) <END> ttypes = ((TemplatizedType) returnType).getTemplateTypes(); if (returnType.isNoResolvedType()) ttypes = ((NoResolvedType) returnType).getTemplateTypes(); if (ttypes == null || !returnType.getDisplayName().equals("IteratorIterable") || ttypes.size() != 1 || !isTemplateOf(ttypes.get(0), "Array")) { return false; } JSType arrayMembers = ttypes.get(0).toMaybeTemplatizedType().getTemplateTypes().get(0); if (!arrayMembers.isUnionType() || arrayMembers.toMaybeUnionType().getAlternatesWithoutStructuralTyping().size() != 2) { return false; } emit("(): IterableIterator<["); Iterator<JSType> it = arrayMembers.toMaybeUnionType().getAlternatesWithoutStructuralTyping().iterator(); visitType(it.next()); emit(","); visitType(it.next()); emit("]>;"); emitBreak(); return true; }</code><technical_language>I rule is curlies if spans more line</technical_language>

Target:
private boolean specialCaseMapEntries(String propName, FunctionType propertyType) { if (propertyType.getMaxArity() != 0 || !propName.equals("entries")) { return false; } ImmutableList<JSType> ttypes = null; JSType returnType = propertyType.getReturnType(); if (returnType.isTemplatizedType()) { ttypes = ((TemplatizedType) returnType).getTemplateTypes(); } else if (returnType.isNoResolvedType()) { ttypes = ((NoResolvedType) returnType).getTemplateTypes(); } if (ttypes == null || !returnType.getDisplayName().equals("IteratorIterable") || ttypes.size() != 1 || !isTemplateOf(ttypes.get(0), "Array")) { return false; } JSType arrayMembers = ttypes.get(0).toMaybeTemplatizedType().getTemplateTypes().get(0); if (!arrayMembers.isUnionType() || arrayMembers.toMaybeUnionType().getAlternatesWithoutStructuralTyping().size() != 2) { return false; } emit("(): IterableIterator<["); Iterator<JSType> it = arrayMembers.toMaybeUnionType().getAlternatesWithoutStructuralTyping().iterator(); visitType(it.next()); emit(","); visitType(it.next()); emit("]>;"); emitBreak(); return true; }
Source:
<code>protected void validateParameters() { if (user == null && (users == null || users.isEmpty()) && email == null) { throw new IllegalParameterException("'users' or 'email' parameters must be set"); } else if (email != null && end == null) { throw new IllegalParameterException("'end' parameter must be set when adding a permission for an 'email'"); } ConfigurationService configService = Framework.getService(ConfigurationService.class); if (configService.isBooleanPropertyFalse(ALLOW_VIRTUAL_USER)) { UserManager userManager = Framework.getService(UserManager.class); if (user != null) { checkUserAndGroupExistence(user, userManager); } <START> if (users != null && !users.isEmpty()) { <END> for (String username : users) { checkUserAndGroupExistence(username, userManager); } } } }</code><technical_language>&& !users.isEmpty() is needed, cost a loop empty list</technical_language>

Target:
protected void validateParameters() { if (user == null && (users == null || users.isEmpty()) && email == null) { throw new IllegalParameterException("'users' or 'email' parameters must be set"); } else if (email != null && end == null) { throw new IllegalParameterException("'end' parameter must be set when adding a permission for an 'email'"); } ensureUserListIsUsed(); ConfigurationService configService = Framework.getService(ConfigurationService.class); if (configService.isBooleanPropertyFalse(ALLOW_VIRTUAL_USER)) { UserManager userManager = Framework.getService(UserManager.class); List<String> unknownNames = users.stream() .filter(userOrGroupName -> !isTransientUsername(userOrGroupName) && userManager.getUserModel(userOrGroupName) == null && userManager.getGroupModel(userOrGroupName) == null) .collect(toList()); if (!unknownNames.isEmpty()) { String errorMsg = String.format( "The following set of User or Group names do not exist: [%s]. Please provide valid ones.", String.join(",", unknownNames)); throw new IllegalParameterException(errorMsg); } } }
Source:
<code>public void copyFormatting(BaseComponent component) { <START> copyFormatting( component, FormatRetention.ALL, false ); <END> }</code><technical_language>I behaviour replace</technical_language>

Target:
public void copyFormatting(BaseComponent component) { copyFormatting( component, FormatRetention.ALL, true ); }
Source:
<code>private void removeDuplicateAttacks(int entityId) { int allowed = 1; Entity en = game.getEntity(entityId); if (null != en) { allowed = en.getAllowedPhysicalAttacks(); } Vector<EntityAction> toKeep = new Vector<>(); for (Enumeration<EntityAction> i = game.getActions(); i.hasMoreElements(); ) { EntityAction action = i.nextElement(); if (action.getEntityId() != entityId) { toKeep.addElement(action); } else if (allowed > 0) { toKeep.addElement(action); if (!(action instanceof SearchlightAttackAction)) { allowed--; } } else { <START> MegaMek.getLogger().error("removing duplicate phys attack for id#" + entityId <END> + "\n\t\taction was " + action.toString()); } } game.resetActions(); for (EntityAction entityAction : toKeep) { game.addAction(entityAction); } }</code><technical_language>suggestion MegaMek.getLogger().error("Removing duplicate phys attack for id#" + entityId</technical_language>

Target:
private void removeDuplicateAttacks(int entityId) { int allowed = 1; Entity en = game.getEntity(entityId); if (null != en) { allowed = en.getAllowedPhysicalAttacks(); } Vector<EntityAction> toKeep = new Vector<>(); for (Enumeration<EntityAction> i = game.getActions(); i.hasMoreElements(); ) { EntityAction action = i.nextElement(); if (action.getEntityId() != entityId) { toKeep.addElement(action); } else if (allowed > 0) { toKeep.addElement(action); if (!(action instanceof SearchlightAttackAction)) { allowed--; } } else { MegaMek.getLogger().error("Removing duplicate phys attack for id#" + entityId + "\n\t\taction was " + action.toString()); } } game.resetActions(); for (EntityAction entityAction : toKeep) { game.addAction(entityAction); } }
Source:
<code>private String acquireAccessToken() throws APIException { try { HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(new GenericUrl( String.format("%s/oauth/token?client_id=testdroid-cloud-api&client_secret=qwerty&grant_type=password&username=%s&password=%s", cloudURL, username, password))); request.setConnectTimeout(60000); <START> request.setReadTimeout(60000); END> HttpResponse response = request.execute(); if(response.getStatusCode() != 200) { throw new APIException(response.getStatusCode(), "Failed to acquire access token"); } String content = StringUtils.join(IOUtils.readLines(response.getContent()), "\n"); JSONObject json = JSONObject.fromObject(content); accessTokenExpireTime = System.currentTimeMillis()+(Long.parseLong(json.optString("expires_in"))*1000); return json.optString("access_token"); } catch(IOException ex) { throw new APIException("Failed to acquire access token", ex); } }</code><technical_language>constant private/public static final property in pom</technical_language>

Target:
private String acquireAccessToken() throws APIException { try { HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(new GenericUrl( String.format("%s/oauth/token?client_id=testdroid-cloud-api&client_secret=qwerty&grant_type=password&username=%s&password=%s", cloudURL, username, password))); request.setConnectTimeout(HTTP_CONNECT_TIMEOUT); request.setReadTimeout(HTTP_READ_TIMEOUT); HttpResponse response = request.execute(); if(response.getStatusCode() != 200) { throw new APIException(response.getStatusCode(), "Failed to acquire access token"); } String content = StringUtils.join(IOUtils.readLines(response.getContent()), "\n"); JSONObject json = JSONObject.fromObject(content); accessTokenExpireTime = System.currentTimeMillis()+(Long.parseLong(json.optString("expires_in"))*1000); return json.optString("access_token"); } catch(IOException ex) { throw new APIException("Failed to acquire access token", ex); } }
Source:
<code>public synchronized IPath[] getPaths() { List<IPath> result = new ArrayList<>(); for (Object element : objects.keySet()) { <START> IPath path = (IPath) element; <END> Node node = getNode(path); if (node.getPayload() != null) result.add(path); } return result.toArray(new IPath[result.size()]); }</code><technical_language>loop var; objects is typed</technical_language>

Target:
public synchronized IPath[] getPaths() { List<IPath> result = new ArrayList<>(); for (IPath path : objects.keySet()) { Node node = getNode(path); if (node.getPayload() != null) result.add(path); } return result.toArray(new IPath[result.size()]); }
Source:
<code>static void printTweetsOnce(JCommanderSetting jCommanderSettings, Location currentLocation, String queryString) { int numberOfTries = 0; do { try { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query(queryString).geoCode( new GeoLocation( currentLocation.getLatitude(), currentLocation.getLongitude()), RADIUS, RADIUS_UNIT); query.setCount(jCommanderSettings.getLimit()); QueryResult result = twitter.search(query); long currentTime = System.currentTimeMillis(); List<Status> tweets = result.getTweets(); Collections.reverse(tweets); <START> if (tweets.size() == 0) { <END> System.out.println("Не найдено ни одного твита"); printSeparator(); } for (Status status : tweets) { if (!status.isRetweet() || !jCommanderSettings.isHideRetweets()) { System.out.print("[" + TimeFormatter.formatTime(currentTime, status.getCreatedAt().getTime()) + "] "); printTweet(status); printSeparator(); } } numberOfTries = MAX_NUMBER_OF_TRIES; } catch (TwitterException te) { ++numberOfTries; if (numberOfTries == MAX_NUMBER_OF_TRIES) { System.out.println(te.getMessage()); System.err.println("Something went terribly wrong, " + "probably - connection + error"); System.exit(1); } } } while (numberOfTries < MAX_NUMBER_OF_TRIES); }</code><technical_language>List.isEmpty()</technical_language>

Target:
static void printTweetsOnce(JCommanderSetting jCommanderSettings, Location currentLocation, String queryString) { int numberOfTries = 0; do { try { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query(queryString).geoCode( new GeoLocation( currentLocation.getLatitude(), currentLocation.getLongitude()), RADIUS, RADIUS_UNIT); query.setCount(jCommanderSettings.getLimit()); QueryResult result = twitter.search(query); long currentTime = System.currentTimeMillis(); List<Status> tweets = result.getTweets(); Collections.reverse(tweets); if (tweets.isEmpty()) { System.out.println("Не найдено ни одного твита"); printSeparator(); } for (Status status : tweets) { if (!status.isRetweet() || !jCommanderSettings.isHideRetweets()) { System.out.print("[" + TimeFormatter.formatTime(currentTime, status.getCreatedAt().getTime()) + "] "); printTweet(status); printSeparator(); } } numberOfTries = MAX_NUMBER_OF_TRIES; } catch (TwitterException te) { ++numberOfTries; if (numberOfTries == MAX_NUMBER_OF_TRIES) { System.out.println(te.getMessage()); System.err.println("Something went terribly wrong, " + "probably - connection + error"); System.exit(1); } } } while (numberOfTries < MAX_NUMBER_OF_TRIES); }
Source:
<code>private void initKeyStore() throws Exception { LOG.debug("SamlCallbackHandler.initKeyStore() -- Begin"); InputStream is = null; final HashMap<String, String> keyStoreProperties = getKeyStoreSystemProperties(); String storeType = keyStoreProperties.get(KEY_STORE_TYPE_KEY); final String password = keyStoreProperties.get(KEY_STORE_PASSWORD_KEY); final String storeLoc = keyStoreProperties.get(KEY_STORE_KEY); if (storeType == null) { LOG.error("javax.net.ssl.keyStoreType is not defined"); LOG.warn("Default to JKS keyStoreType"); storeType = JKS_TYPE; } if (password == null || storeLoc == null) { LOG.error("Store password or store location not defined"); LOG.error("Please define javax.net.ssl.keyStorePassword and javax.net.ssl.keyStore"); } if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("javax.net.ssl.keyStore is not defined"); } else { try { keyStore = KeyStore.getInstance(storeType); if (!PKCS11_TYPE.equalsIgnoreCase(storeType)) { is = new FileInputStream(storeLoc); } keyStore.load(is, (password != null) ? password.toCharArray() : null); <START> } catch (final NoSuchAlgorithmException ex) { <END> LOG.error(KEY_STORE_ERROR_MSG, ex.getLocalizedMessage(), ex); throw new Exception(ex.getMessage()); } catch (final CertificateException ex) { LOG.error(KEY_STORE_ERROR_MSG, ex.getLocalizedMessage(), ex); throw new Exception(ex.getMessage()); } catch (final KeyStoreException ex) { LOG.error(KEY_STORE_ERROR_MSG, ex.getLocalizedMessage(), ex); throw new Exception(ex.getMessage()); } finally { try { if (is != null) { is.close(); } } catch (final IOException ex) { LOG.debug("KeyStoreCallbackHandler {}", ex); } } } LOG.debug("SamlCallbackHandler.initKeyStore() -- End"); }</code><technical_language>catch multiple exceptions types in single catch statement</technical_language>

Target:
private void initKeyStore() throws Exception { LOG.debug("SamlCallbackHandler.initKeyStore() -- Begin"); InputStream is = null; final HashMap<String, String> keyStoreProperties = getKeyStoreSystemProperties(); String storeType = keyStoreProperties.get(KEY_STORE_TYPE_KEY); final String password = keyStoreProperties.get(KEY_STORE_PASSWORD_KEY); final String storeLoc = keyStoreProperties.get(KEY_STORE_KEY); if (storeType == null) { LOG.error("javax.net.ssl.keyStoreType is not defined"); LOG.warn("Default to JKS keyStoreType"); storeType = JKS_TYPE; } if (password !=null){ if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("javax.net.ssl.keyStore is not defined"); } else { try { keyStore = KeyStore.getInstance(storeType); if (!PKCS11_TYPE.equalsIgnoreCase(storeType)) { is = new FileInputStream(storeLoc); } keyStore.load(is, password.toCharArray()); } catch (final NoSuchAlgorithmException|CertificateException|KeyStoreException ex) { LOG.error(KEYSTORE_ERROR_MSG, ex.getLocalizedMessage(), ex); throw new Exception(ex.getMessage()); } finally { try { if (is != null) { is.close(); } } catch (final IOException ex) { LOG.debug("KeyStoreCallbackHandler {}", ex); } } } }else{ LOG.error("Please define javax.net.ssl.keyStorePassword"); } LOG.debug("SamlCallbackHandler.initKeyStore() -- End"); }
Source:
<code>public void onBindViewHolder(final ItemHolder holder, int position) { <START> String item = mItems.get(holder.getAdapterPosition()); <END> holder.text.setText(item); holder.container.setBackgroundColor( isItemSelected(position) ? mSelectedColor : mUnselectedColor ); }</code><technical_language>getItem() method here, for consistency</technical_language>

Target:
public void onBindViewHolder(final ItemHolder holder, int position) { String item = getItem(holder.getAdapterPosition()); holder.text.setText(item); holder.container.setBackgroundColor( isItemSelected(position) ? mSelectedColor : mUnselectedColor ); }
Source:
<code>public void itReturnsAllValuesWrapped() { ArgumentCaptor<ReactiveNavigator.ActivityResult> argumentCaptor = ArgumentCaptor.forClass(ActivityResult.class); Observable<ActivityResult> observable = reactiveNavigator.toActivityForResult(mockIntent, 42); observable.subscribe(mockObserver); reactiveNavigator.onActivityResult(42, Activity.RESULT_OK, mockData); verify(mockObserver).onNext(argumentCaptor.capture()); ActivityResult value = argumentCaptor.getValue(); <START> Assert.assertEquals(Activity.RESULT_OK, value.getResultCode()); <END> assertEquals(mockData, value.getData()); }</code><technical_language>drop Assert</technical_language>

Target:
public void itReturnsAllValuesWrapped() { ArgumentCaptor<ReactiveNavigator.ActivityResult> argumentCaptor = ArgumentCaptor.forClass(ActivityResult.class); Observable<ActivityResult> observable = reactiveNavigator.activityResult(mockIntent, 42); observable.subscribe(mockObserver); reactiveNavigator.onActivityResult(42, Activity.RESULT_OK, mockData); verify(mockObserver).onNext(argumentCaptor.capture()); ActivityResult value = argumentCaptor.getValue(); assertEquals(Activity.RESULT_OK, value.resultCode()); assertEquals(mockData, value.data()); }
Source:
<code>public void loadOffices() { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getOffices() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Office>>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); <START> try { <END> if (e instanceof HttpException) { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(List<Office> offices) { getMvpView().showProgressbar(false); getMvpView().showOffices(offices); } })); }</code><technical_language>this utils method show error <LINK_0></technical_language>

Target:
public void loadOffices() { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getOffices() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Office>>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(List<Office> offices) { getMvpView().showProgressbar(false); getMvpView().showOffices(offices); } })); }
Source:
<code>public void initialize() { logger.debug("Initializing WemoLightHandler"); final String configLightId = (String) getConfig().get(DEVICE_ID); if (DEVICE_ID != null) { wemoLightID = configLightId; logger.debug("Initializing WemoLightHandler for LightID '{}'", wemoLightID); if (getWemoBridgeHandler() != null) { ThingStatusInfo statusInfo = getBridge().getStatusInfo(); <START> updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription()); <END> if (SUPPORTED_THING_TYPES.contains(this.getThing().getThingTypeUID())) { logger.debug("Initialize Thing {}", this.getThing().getThingTypeUID()); updateStatus(ThingStatus.ONLINE); onSubscription(); onUpdate(); } } } else { logger.debug("Cannot initalize WemoLightHandler. LightID not set."); } }</code><technical_language>copy status of bridge details (which sense for device). Note framework automatically sets status OFFLINE, if bridge is OFFLINE. is expected is if device is ready work set ONLINE if is a problem (while bridge ONLINE), set OFFLINE message (which here)</technical_language>

Target:
public void initialize() { logger.debug("Initializing WemoLightHandler"); final String configLightId = (String) getConfig().get(DEVICE_ID); if (DEVICE_ID != null) { wemoLightID = configLightId; logger.debug("Initializing WemoLightHandler for LightID '{}'", wemoLightID); } }
Source:
<code>public boolean canResolve(ScopeDescriptor scopeDescription) { return scopeDescription instanceof AggregateDescriptor <START> && ((AggregateDescriptor) scopeDescription).getType().equals(aggregateModel.type()); <END> }</code><technical_language>Objects.equals is safer (null-safety). Otherwise, aggregateModel.type() is non-null, turning equals improves null-safety</technical_language>

Target:
public boolean canResolve(ScopeDescriptor scopeDescription) { return scopeDescription instanceof AggregateScopeDescriptor && Objects.equals(aggregateModel.type(), ((AggregateScopeDescriptor) scopeDescription).getType()); }
Source:
<code>protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor) { IProgressMonitor mon = (monitor == null ? new NullProgressMonitor() : monitor); final ITmfStateProvider provider = createStateProvider(); String id = getId(); if (id == null) { <START> id = "unnamed"; END> } try { StateSystemBackendType backend = getBackendType(); String directory; File htFile; switch (backend) { case FULL: directory = TmfTraceManager.getSupplementaryFileDir(getTrace()); htFile = new File(directory + getSsFileName()); createFullHistory(id, provider, htFile); break; case PARTIAL: directory = TmfTraceManager.getSupplementaryFileDir(getTrace()); htFile = new File(directory + getSsFileName()); createPartialHistory(id, provider, htFile); break; case INMEM: createInMemoryHistory(id, provider); break; case NULL: createNullHistory(id, provider); break; default: break; } } catch (TmfTraceException e) { return false; } return !mon.isCanceled(); }</code><technical_language>put this in static field? id of null happen</technical_language>

Target:
protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor) { IProgressMonitor mon = (monitor == null ? new NullProgressMonitor() : monitor); final ITmfStateProvider provider = createStateProvider(); String id = getId(); if (id == null) { id = UNDEFINED_ID; } try { StateSystemBackendType backend = getBackendType(); String directory; File htFile; switch (backend) { case FULL: directory = TmfTraceManager.getSupplementaryFileDir(getTrace()); htFile = new File(directory + getSsFileName()); createFullHistory(id, provider, htFile); break; case PARTIAL: directory = TmfTraceManager.getSupplementaryFileDir(getTrace()); htFile = new File(directory + getSsFileName()); createPartialHistory(id, provider, htFile); break; case INMEM: createInMemoryHistory(id, provider); break; case NULL: createNullHistory(id, provider); break; default: break; } } catch (TmfTraceException e) { return false; } return !mon.isCanceled(); }
Source:
<code>public static void isRetryableExceptionWhereLeaderCannotBeFound(Throwable throwable) { assertThat(throwable) .hasMessageContaining("receiving QosException.RetryOther") <START> .isInstanceOf(RetryableException.class); <END> }</code><technical_language>do want map a QosException.RetryOther</technical_language>

Target:
public static void isRetryableExceptionWhereLeaderCannotBeFound(Throwable throwable) { assertThat(throwable) .hasMessageContaining("receiving QosException.RetryOther") .isInstanceOf(RetryableException.class) .hasRootCauseInstanceOf(QosException.RetryOther.class); }
Source:
<code>public void shouldTalkToPlugin_To_GetPipelineAnalytics() throws Exception { String responseBody = "{ \"view_path\": \"path/to/view\", \"data\": \"{}\" }"; when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody)); <START> AnalyticsPluginInfo pluginInfo = mock(AnalyticsPluginInfo.class); <END> PluginDescriptor desc = mock(PluginDescriptor.class); when(desc.id()).thenReturn(PLUGIN_ID); when(pluginInfo.getDescriptor()).thenReturn(desc); when(pluginInfo.getStaticAssetsPath()).thenReturn("/assets/root"); metadataStore.setPluginInfo(pluginInfo); AnalyticsData pipelineAnalytics = analyticsExtension.getPipelineAnalytics(PLUGIN_ID, "test_pipeline"); assertRequest(requestArgumentCaptor.getValue(), AnalyticsPluginConstants.EXTENSION_NAME, "1.0", REQUEST_GET_PIPELINE_ANALYTICS, "{\"pipeline_name\": \"test_pipeline\"}"); assertThat(pipelineAnalytics.getViewPath(), is("path/to/view")); Map<String, String> expected = new HashMap<>(); expected.put("data", "{}"); expected.put("view_path", "/assets/root/path/to/view"); assertEquals(expected, pipelineAnalytics.toMap()); }</code><technical_language>This unnecessary mock of a simple class. consider this: java AnalyticsPluginInfo pluginInfo = new AnalyticsPluginInfo( new GoPluginDescriptor(PLUGIN_ID, null, null, null, null, false), null, null, null); pluginInfo.setStaticAssetsPath("/assets/root"); metadataStore.setPluginInfo(pluginInfo); Ideally a PluginInfoMother</technical_language>

Target:
public void shouldTalkToPlugin_To_GetPipelineAnalytics() throws Exception { String responseBody = "{ \"view_path\": \"path/to/view\", \"data\": \"{}\" }"; when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody)); AnalyticsPluginInfo pluginInfo = new AnalyticsPluginInfo( new GoPluginDescriptor(PLUGIN_ID, null, null, null, null, false), null, null, null); pluginInfo.setStaticAssetsPath("/assets/root"); metadataStore.setPluginInfo(pluginInfo); AnalyticsData pipelineAnalytics = analyticsExtension.getPipelineAnalytics(PLUGIN_ID, "test_pipeline"); assertRequest(requestArgumentCaptor.getValue(), AnalyticsPluginConstants.EXTENSION_NAME, "1.0", REQUEST_GET_PIPELINE_ANALYTICS, "{\"pipeline_name\": \"test_pipeline\"}"); assertThat(pipelineAnalytics.getViewPath(), is("path/to/view")); Map<String, String> expected = new HashMap<>(); expected.put("data", "{}"); expected.put("view_path", "/assets/root/path/to/view"); assertEquals(expected, pipelineAnalytics.toMap()); }