auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void translate(final TableScan tableScan, final TranslatorContext context) { StreamGraph streamGraph = context.getStreamGraph(); List<String> tableNameParts = tableScan.getTable().getQualifiedName(); Validate.isTrue(tableNameParts.size() == 2, String.format("table name %s is not of the format <SystemName>.<StreamName>", Joiner.on(".").join(tableNameParts))); String streamName = tableNameParts.get(1); String systemName = tableNameParts.get(0); Validate.isTrue(relMsgConverters.containsKey(systemName), String.format("Unknown system %s", systemName)); SamzaRelConverter converter = relMsgConverters.get(systemName); MessageStream<SamzaSqlRelMessage> inputStream = streamGraph.getInputStream(streamName, (Object k, Object v) -> { RelDataType type = tableScan.getRowType(); return converter.convertToRelMessage(k, v, type); }); context.registerMessageStream(tableScan.getId(), inputStream); }

Target:
public void translate(final TableScan tableScan, final TranslatorContext context) { StreamGraph streamGraph = context.getStreamGraph(); List<String> tableNameParts = tableScan.getTable().getQualifiedName(); Validate.isTrue(tableNameParts.size() == 2, String.format("table name %s is not of the format <SystemName>.<StreamName>", Joiner.on(".").join(tableNameParts))); String streamName = tableNameParts.get(1); String systemName = tableNameParts.get(0); SystemStream systemStream = new SystemStream(systemName, streamName); Validate.isTrue(relMsgConverters.containsKey(systemStream), String.format("Unknown system %s", systemName)); SamzaRelConverter converter = relMsgConverters.get(systemStream); MessageStream<KV<Object, Object>> inputStream = streamGraph.getInputStream(streamName); MessageStream<SamzaSqlRelMessage> samzaSqlRelMessageStream = inputStream.map(converter::convertToRelMessage); context.registerMessageStream(tableScan.getId(), samzaSqlRelMessageStream); }
Source:
public Map<String, Object> getData() { return Collections.unmodifiableMap(this.data); }

Target:
public Map<String, Object> getData() { return this.data; }
Source:
private void reportMetered(String name, Metered meter, long timestamp) throws IOException { if (getDisabledMetricAttributes().contains(COUNT)) { reportCounter(name, meter.getCount(), timestamp); } sendIfEnabled(M1_RATE, name, convertRate(meter.getOneMinuteRate()), timestamp); sendIfEnabled(M5_RATE, name, convertRate(meter.getFiveMinuteRate()), timestamp); sendIfEnabled(M15_RATE, name, convertRate(meter.getFifteenMinuteRate()), timestamp); sendIfEnabled(MEAN_RATE, name, convertRate(meter.getMeanRate()), timestamp); }

Target:
private void reportMetered(String name, Metered meter, long timestamp) throws IOException { if (!getDisabledMetricAttributes().contains(COUNT)) { reportCounter(name, meter.getCount(), timestamp); } sendIfEnabled(M1_RATE, name, convertRate(meter.getOneMinuteRate()), timestamp); sendIfEnabled(M5_RATE, name, convertRate(meter.getFiveMinuteRate()), timestamp); sendIfEnabled(M15_RATE, name, convertRate(meter.getFifteenMinuteRate()), timestamp); sendIfEnabled(MEAN_RATE, name, convertRate(meter.getMeanRate()), timestamp); }
Source:
public FetchResult call() throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException { checkCallable(); try { try (Transport transport = Transport.open(repo, remote)) { transport.setCheckFetchedObjects(checkFetchedObjects); transport.setRemoveDeletedRefs(isRemoveDeletedRefs()); transport.setDryRun(dryRun); if (tagOption != null) transport.setTagOpt(tagOption); transport.setFetchThin(thin); configure(transport); FetchResult result = transport.fetch(monitor, refSpecs); return result; } } catch (NoRemoteRepositoryException e) { throw new InvalidRemoteException(MessageFormat.format( JGitText.get().invalidRemote, remote), e); } catch (TransportException e) { throw new org.eclipse.jgit.api.errors.TransportException( e.getMessage(), e); } catch (URISyntaxException e) { throw new InvalidRemoteException(MessageFormat.format( JGitText.get().invalidRemote, remote)); } catch (NotSupportedException e) { throw new JGitInternalException( JGitText.get().exceptionCaughtDuringExecutionOfFetchCommand, e); } }

Target:
public FetchResult call() throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException { checkCallable(); try (Transport transport = Transport.open(repo, remote)) { transport.setCheckFetchedObjects(checkFetchedObjects); transport.setRemoveDeletedRefs(isRemoveDeletedRefs()); transport.setDryRun(dryRun); if (tagOption != null) transport.setTagOpt(tagOption); transport.setFetchThin(thin); configure(transport); FetchResult result = transport.fetch(monitor, refSpecs); return result; } catch (NoRemoteRepositoryException e) { throw new InvalidRemoteException(MessageFormat.format( JGitText.get().invalidRemote, remote), e); } catch (TransportException e) { throw new org.eclipse.jgit.api.errors.TransportException( e.getMessage(), e); } catch (URISyntaxException e) { throw new InvalidRemoteException(MessageFormat.format( JGitText.get().invalidRemote, remote)); } catch (NotSupportedException e) { throw new JGitInternalException( JGitText.get().exceptionCaughtDuringExecutionOfFetchCommand, e); } }
Source:
public void testSubstituteSystemPropertyPlaceholders() throws Exception { Map<Object, Object> testMapSystemProperties = new HashMap<>(); testMapSystemProperties.put("Java Home", "${java.home}"); testMapSystemProperties.put("Java Version", "${java.version}"); when(propertiesMock.entrySet()).thenReturn(testMapSystemProperties.entrySet()); Properties testProperties = PropertiesLoader.substituteSystemPropertyPlaceholders(propertiesMock); testMapSystemProperties.replace("Java Home", System.getProperty("java.home")); testMapSystemProperties.replace("Java Version", System.getProperty("java.version")); Assert.assertEquals( "Replaces the System Properties in the string", testMapSystemProperties.entrySet(), testProperties.entrySet()); }

Target:
public void testSubstituteSystemPropertyPlaceholders() throws Exception { Map<Object, Object> testMapSystemProperties = new HashMap<>(); testMapSystemProperties.put("Java_Home", "${java.home}"); testMapSystemProperties.put("Java_Version", "${java.version}"); Map<Object, Object> testMapSystemPropertiesAfter = new HashMap<>(); testMapSystemPropertiesAfter.put("Java_Home", System.getProperty("java.home")); testMapSystemPropertiesAfter.put("Java_Version", System.getProperty("java.version")); when(propertiesMock.entrySet()).thenReturn(testMapSystemProperties.entrySet()); Properties testProperties = PropertiesLoader.substituteSystemPropertyPlaceholders(propertiesMock); assertThat(testProperties.entrySet(), equalTo(testMapSystemPropertiesAfter.entrySet())); }
Source:
public void testRelativeRefIncludingUrlRef(@Injectable final Schema mockedModel) { final RefFormat refFormat = RefFormat.RELATIVE; OpenAPI mockedOpenAPI = new OpenAPI(); mockedOpenAPI.setComponents(new Components()); mockedOpenAPI.getComponents().setSchemas(new HashMap<>()); ResolverCache mockedResolverCache = new ResolverCache(mockedOpenAPI, null, null); ExternalRefProcessor processor = new ExternalRefProcessor(mockedResolverCache, mockedOpenAPI); processor.processRefToExternalSchema("./relative-with-url/relative-with-url.yaml#/relative-with-url", refFormat); assertThat(((Schema) mockedOpenAPI.getComponents().getSchemas().get("relative-with-url").getProperties().get("Foo")).get$ref(), is("<LINK_2>swagger-api/swagger-parser/v2.0.2/modules/swagger-parser-v3/src/test/resources/relative/globals.yaml#/components/schemas/link-object") ); assertThat(mockedOpenAPI.getComponents().getSchemas().keySet().contains("link-object"), is(true)); assertThat(mockedOpenAPI.getComponents().getSchemas().keySet().contains("rel-data"), is(true)); }

Target:
public void testRelativeRefIncludingUrlRef(@Injectable final Schema mockedModel) throws Exception { final RefFormat refFormat = RefFormat.RELATIVE; final String url = "<LINK_1>"; final String expectedResult = "components:\n" + " schemas:\n" + " link-object:\n" + " type: object\n" + " additionalProperties:\n" + " \"$ref\": \"#/components/schemas/rel-data\"\n" + " rel-data:\n" + " type: object\n" + " required:\n" + " - href\n" + " properties:\n" + " href:\n" + " type: string\n" + " note:\n" + " type: string\n" + " result:\n" + " type: object\n" + " properties:\n" + " name:\n" + " type: string\n" + " _links:\n" + " \"$ref\": \"#/components/schemas/link-object\"\n" + ""; List<AuthorizationValue> auths = null; new Expectations() {{ RemoteUrl.urlToString(url, auths); times = 1; result = expectedResult; }}; OpenAPI mockedOpenAPI = new OpenAPI(); mockedOpenAPI.setComponents(new Components()); mockedOpenAPI.getComponents().setSchemas(new HashMap<>()); ResolverCache mockedResolverCache = new ResolverCache(mockedOpenAPI, null, null); ExternalRefProcessor processor = new ExternalRefProcessor(mockedResolverCache, mockedOpenAPI); processor.processRefToExternalSchema("./relative-with-url/relative-with-url.yaml#/relative-with-url", refFormat); assertThat(((Schema) mockedOpenAPI.getComponents().getSchemas().get("relative-with-url").getProperties().get("Foo")).get$ref(), is("<LINK_0>") ); assertThat(mockedOpenAPI.getComponents().getSchemas().keySet().contains("link-object"), is(true)); assertThat(mockedOpenAPI.getComponents().getSchemas().keySet().contains("rel-data"), is(true)); assertThat(((Schema) mockedOpenAPI.getComponents().getSchemas().get("relative-with-url").getProperties().get("Bar")).get$ref(), is("./relative-with-url/relative-with-local.yaml#/relative-same-file") ); }
Source:
public JmxReporter(String prefix) { Objects.requireNonNull(prefix); this.prefix = prefix; }

Target:
public JmxReporter(String prefix) { this.prefix = prefix != null ? prefix : ""; }
Source:
public void apply() { for (var entry : typesWithFields.entrySet()) { BibEntryType type = entry.getKey(); List<FieldViewModel> allFields = entry.getValue(); List<OrFields> requiredFields = allFields.stream().filter(field -> field.getFieldType() == FieldType.REQUIRED).map(FieldViewModel::getField).map(OrFields::new).collect(Collectors.toList()); List<BibField> otherFields = allFields.stream().filter(field -> field.getFieldType() == FieldType.OPTIONAL).map(bibField -> new BibField(bibField.getField(), bibField.getFieldPriority())).collect(Collectors.toList()); BibEntryType newType = new BibEntryType(type.getType(), otherFields, requiredFields); Globals.entryTypesManager.addCustomOrModifiedType(newType, mode); } for (var type : typesToRemove) { Globals.entryTypesManager.removeCustomEntryType(type, mode); } preferencesService.saveCustomEntryTypes(); }

Target:
public void apply() { for (var typeWithField : typesWithFields.entrySet()) { BibEntryType type = typeWithField.getKey(); List<FieldViewModel> allFields = typeWithField.getValue(); List<OrFields> requiredFields = allFields.stream().filter(field -> field.getFieldType() == FieldType.REQUIRED).map(FieldViewModel::getField).map(OrFields::new).collect(Collectors.toList()); List<BibField> otherFields = allFields.stream().filter(field -> field.getFieldType() == FieldType.OPTIONAL).map(bibField -> new BibField(bibField.getField(), bibField.getFieldPriority())).collect(Collectors.toList()); BibEntryType newType = new BibEntryType(type.getType(), otherFields, requiredFields); entryTypesManager.addCustomOrModifiedType(newType, mode); } for (var type : typesToRemove) { entryTypesManager.removeCustomOrModifiedEntryType(type, mode); } preferencesService.saveCustomEntryTypes(); entryTypesManager.addCustomOrModifiedTypes(preferencesService.loadBibEntryTypes(BibDatabaseMode.BIBTEX), preferencesService.loadBibEntryTypes(BibDatabaseMode.BIBLATEX)); }
Source:
public Metric(Class<?> tableClass, String fieldName, AggregationDictionary dictionary) { super(tableClass, fieldName, dictionary); if (dictionary.attributeOrRelationAnnotationExists(tableClass, fieldName, MetricAggregation.class)) { MetricAggregation metricAggregation = dictionary.getAttributeOrRelationAnnotation( tableClass, MetricAggregation.class, fieldName); Class<? extends Aggregation>[] aggregations = metricAggregation.aggregations(); this.supportedFunctions = Arrays.stream(aggregations) .map(MetricFunction::getAggregationFunction) .collect(Collectors.toSet()); } else if (dictionary.attributeOrRelationAnnotationExists(tableClass, fieldName, MetricComputation.class)) { MetricComputation metricComputation = dictionary.getAttributeOrRelationAnnotation( tableClass, MetricComputation.class, fieldName); this.supportedFunctions = new HashSet<>(); } else { throw new IllegalArgumentException(getId() + " is not a metric field"); } }

Target:
public Metric(Class<?> tableClass, String fieldName, AggregationDictionary dictionary) { super(tableClass, fieldName, dictionary); if (dictionary.attributeOrRelationAnnotationExists(tableClass, fieldName, MetricAggregation.class)) { MetricAggregation metricAggregation = dictionary.getAttributeOrRelationAnnotation( tableClass, MetricAggregation.class, fieldName); Aggregation[] aggregations = metricAggregation.aggregations(); this.supportedFunctions = Arrays.stream(aggregations) .map(MetricFunction::getAggregationFunction) .collect(Collectors.toList()); } else if (dictionary.attributeOrRelationAnnotationExists(tableClass, fieldName, MetricComputation.class)) { MetricComputation metricComputation = dictionary.getAttributeOrRelationAnnotation( tableClass, MetricComputation.class, fieldName); this.supportedFunctions = new ArrayList<>(); } else { throw new IllegalArgumentException(getId() + " is not a metric field"); } }
Source:
public List<File> findFilesFrom(File dir, FilenameFilter filter, boolean recurse) { this.filter = filter; List<File> files = new ArrayList<>(); scanDirectory(dir, files, recurse); Collections.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getPath().compareToIgnoreCase(o2.getPath()); } }); return files; }

Target:
public List<File> findFilesFrom(File dir, FilenameFilter filter, boolean recurse) { this.filter = filter; List<File> files = new ArrayList<>(); scanDirectory(dir, files, recurse); return files; }
Source:
public void setUp() { MockitoAnnotations.initMocks(this); result = new MockResult(); validator = new MockValidator(); controller = new MusicOwnerController(musicDao, userDao, userInfo, result, validator); music = createMusic(); user = createUser(); anotherUser = createAnotherUser(); }

Target:
public void setUp() { MockitoAnnotations.initMocks(this); result = new MockResult(); validator = new MockValidator(); controller = new MusicOwnerController(musicDao, userDao, userInfo, result, validator); music = new MusicBuilder().withId(1L).withType(MusicType.ROCK).withTitle("Some Music").withDescription("Some description").build(); user = new UserBuilder().withName("Renan").withLogin("renanigt").withPassword("1234").withMusicOwners(createMusicOwners()).build(); anotherUser = new UserBuilder().withName("Fulano").withLogin("fulano").withPassword("3456").build(); }
Source:
private ExecuteResult(InputStream stream, InputStream errorStream, int responseCode, String responseMessage, Throwable cause, JSONHelper jsonHelper) { this.responseCode = responseCode; boolean needsCouchException = false; switch(responseCode / 100) { case 1: case 2: this.fatal = false; this.exception = null; this.stream = stream; break; case 3: throw new CouchException("Unexpected redirection (3xx) code encountered", responseCode); case 4: case 5: this.fatal = responseCode / 100 != 5 ; if (responseCode == 404) { this.exception = new NoResourceException(responseMessage, cause); } else if (responseCode == 409) { this.exception = new DocumentConflictException(responseMessage); } else { needsCouchException = true; } break; default: this.fatal = false; needsCouchException = true; } if (needsCouchException) { try { Map<String, String> json = jsonHelper.fromJson(new InputStreamReader (errorStream, Charset.forName("UTF-8")), Map.class); CouchException ce = new CouchException(responseMessage, cause, responseCode); ce.setError(json.get("error")); ce.setReason(json.get("reason")); this.exception = ce; } catch (Exception e) { CouchException ce = new CouchException("Error deserializing server response", cause, responseCode); this.exception = ce; } } }

Target:
private ExecuteResult(InputStream stream, InputStream errorStream, int responseCode, String responseMessage, Throwable cause, JSONHelper jsonHelper) { this.responseCode = responseCode; boolean needsCouchException = false; switch(responseCode / 100) { case 1: case 2: this.fatal = false; this.exception = null; this.stream = stream; break; case 3: throw new CouchException("Unexpected redirection (3xx) code encountered", responseCode); case 4: this.fatal = true; if (responseCode == 404) { this.exception = new NoResourceException(responseMessage, cause); } else if (responseCode == 409) { this.exception = new DocumentConflictException(responseMessage); } else { needsCouchException = true; } break; case 5: this.fatal = false; needsCouchException = true; break; default: this.fatal = false; needsCouchException = true; } if (needsCouchException) { try { Map<String, String> json = jsonHelper.fromJson(new InputStreamReader (errorStream, Charset.forName("UTF-8")), Map.class); CouchException ce = new CouchException(responseMessage, cause, responseCode); ce.setError(json.get("error")); ce.setReason(json.get("reason")); this.exception = ce; } catch (Exception e) { CouchException ce = new CouchException("Error deserializing server response", cause, responseCode); this.exception = ce; } } }
Source:
private Set<ConstraintViolation> checkNullableExpressions(Entity entity, EntityType entityType) { List<String> nullableExpressions = new ArrayList<>(); List<Attribute> expressionAttributes = new ArrayList<>(); for (Attribute attribute : entityType.getAtomicAttributes()) { String nullableExpression = attribute.getNullableExpression(); if (nullableExpression != null) { expressionAttributes.add(attribute); nullableExpressions.add(nullableExpression); } } Set<ConstraintViolation> violations = new LinkedHashSet<>(); if (!nullableExpressions.isEmpty()) { List<Boolean> results = expressionValidator.resolveBooleanExpressions(nullableExpressions, entity); for (int i = 0; i < results.size(); i++) { if (!results.get(i) && EntityUtils.isNullValue(entity, expressionAttributes.get(i))) { violations.add(createConstraintViolation(entity, expressionAttributes.get(i), entityType, format("Offended expression: %s", nullableExpressions.get(i)))); } } } return violations; }

Target:
private Set<ConstraintViolation> checkNullableExpressions(Entity entity, EntityType entityType) { List<String> nullableExpressions = new ArrayList<>(); List<Attribute> expressionAttributes = new ArrayList<>(); for (Attribute attribute : entityType.getAtomicAttributes()) { String nullableExpression = attribute.getNullableExpression(); if (nullableExpression != null) { expressionAttributes.add(attribute); nullableExpressions.add(nullableExpression); } } Set<ConstraintViolation> violations = new LinkedHashSet<>(); if (!nullableExpressions.isEmpty()) { List<Boolean> results = expressionValidator.resolveBooleanExpressions(nullableExpressions, entity); for (int i = 0; i < results.size(); i++) { if (!results.get(i) && EntityUtils.isNullValue(entity, expressionAttributes.get(i))) { violations.add(createConstraintViolation(entity, expressionAttributes.get(i), entityType, format("Offended nullable expression: %s", nullableExpressions.get(i)))); } } } return violations; }
Source:
public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); String glob = Coder.bytesToString(commandElems.get(1)); Set<ByteArrayWrapper> allKeys = getDataRegion(context).keySet(); List<ByteArrayWrapper> matchingKeys = new ArrayList<>(); Pattern pattern; try { pattern = GlobPattern.compile(glob); } catch (PatternSyntaxException e) { logger.debug( "Could not compile the pattern: '{}' due to the following exception: Returning an empty list.", glob, e.getMessage()); return RedisResponse.emptyArray(); } for (ByteArrayWrapper bytesKey : allKeys) { String key = bytesKey.toString(); if (pattern.matcher(key).matches()) { matchingKeys.add(bytesKey); } } if (matchingKeys.isEmpty()) { return RedisResponse.emptyArray(); } return respondBulkStrings(matchingKeys); }

Target:
public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); String glob = Coder.bytesToString(commandElems.get(1)); Set<ByteArrayWrapper> allKeys = getDataRegion(context).keySet(); List<ByteArrayWrapper> matchingKeys = new ArrayList<>(); Pattern pattern; try { pattern = GlobPattern.compile(glob); } catch (PatternSyntaxException e) { logger.warn( "Could not compile the pattern: '{}' due to the following exception: '{}'. KEYS will return an empty list.", glob, e.getMessage()); return RedisResponse.emptyArray(); } for (ByteArrayWrapper bytesKey : allKeys) { String key = bytesKey.toString(); if (pattern.matcher(key).matches()) { matchingKeys.add(bytesKey); } } if (matchingKeys.isEmpty()) { return RedisResponse.emptyArray(); } return respondBulkStrings(matchingKeys); }
Source:
private boolean addOncogenicMutations(Alteration exactAlt, Set<Alteration> relevantAlts) { boolean add = false; if (!exactAlt.getAlteration().trim().equalsIgnoreCase("amplification")) { for (Alteration alt : relevantAlts) { Boolean isOncogenic = AlterationUtils.isOncogenicAlteration(alt); if (isOncogenic != null && isOncogenic && !isKitSpecialVariants(alt)) { add = true; break; } } } if (isKitSpecialVariants(exactAlt)) { add = false; } return add; }

Target:
private boolean addOncogenicMutations(Alteration exactAlt, Set<Alteration> relevantAlts) { boolean add = false; if (!isKitSpecialVariants(exactAlt)) { if (!exactAlt.getAlteration().trim().equalsIgnoreCase("amplification")) { for (Alteration alt : relevantAlts) { Boolean isOncogenic = AlterationUtils.isOncogenicAlteration(alt); if (isOncogenic != null && isOncogenic && !isKitSpecialVariants(alt)) { add = true; break; } } } } return add; }
Source:
public void setVisible(boolean visible) { if (bars != null) bars.clearGlobalActionHandlers(); ArrayList<Control> tabList = new ArrayList<>(); for (int i = 0; i < partRecs.size(); i++) { PartRec rec = partRecs.get(i); if (visible) { createRecPart(rec); hookGlobalAction(ActionFactory.PRINT.getId(), rec.part); hookGlobalAction(ActionFactory.COPY.getId(), rec.part); hookGlobalAction(ActionFactory.DELETE.getId(), rec.part); tabList.add(rec.part.getControl()); } rec.part.setVisible(visible); } Composite parent = mform.getForm().getBody(); parent.setTabList(tabList.toArray(new Control[tabList.size()])); if (actionBars != null) { actionBars.clearGlobalActionHandlers(); if (visible) { Map<String, IAction> handlers = bars.getGlobalActionHandlers(); if (handlers != null) { Set<String> keys = handlers.keySet(); for (Iterator<String> iter = keys.iterator(); iter.hasNext();) { String key = iter.next(); actionBars.setGlobalActionHandler(key, handlers.get(key)); } } } if (pageAction != null) pageAction.setChecked(visible); } if (bars != null) { if (visible) bars.activate(); else bars.deactivate(); if (this.__updateActionBars) bars.updateActionBars(); } else { ((SubToolBarManager) subToolBarManager).setVisible(visible); if (subMenuManager != null) { ((SubMenuManager)subMenuManager).setVisible(visible); } ReusableHelpPart.this.toolBarManager.update(true); getControl().getParent().layout(); } }

Target:
public void setVisible(boolean visible) { if (bars != null) bars.clearGlobalActionHandlers(); ArrayList<Control> tabList = new ArrayList<>(); for (int i = 0; i < partRecs.size(); i++) { PartRec rec = partRecs.get(i); if (visible) { createRecPart(rec); hookGlobalAction(ActionFactory.PRINT.getId(), rec.part); hookGlobalAction(ActionFactory.COPY.getId(), rec.part); hookGlobalAction(ActionFactory.DELETE.getId(), rec.part); tabList.add(rec.part.getControl()); } rec.part.setVisible(visible); } Composite parent = mform.getForm().getBody(); parent.setTabList(tabList.toArray(new Control[tabList.size()])); if (actionBars != null) { actionBars.clearGlobalActionHandlers(); if (visible) { Map<String, IAction> handlers = bars.getGlobalActionHandlers(); if (handlers != null) { Set<String> keys = handlers.keySet(); for (Iterator<String> iter = keys.iterator(); iter.hasNext();) { String key = iter.next(); actionBars.setGlobalActionHandler(key, handlers.get(key)); } } } if (pageAction != null) pageAction.setChecked(visible); } if (bars != null) { if (visible) bars.activate(); else bars.deactivate(); if (this.updateActionBars) { bars.updateActionBars(); } } else { ((SubToolBarManager) subToolBarManager).setVisible(visible); if (subMenuManager != null) { ((SubMenuManager)subMenuManager).setVisible(visible); } ReusableHelpPart.this.toolBarManager.update(true); getControl().getParent().layout(); } }
Source:
static String unprotectPerforceFilename(String name) { String t = name.replace("%40", "@"); t = t.replace("%23", "#"); t = t.replace("%2A", "*"); t = t.replace("%25", "%"); if (!name.equals(t)) { LOGGER.log(Level.FINEST, "unprotectPerforceFilename: replaced ''{0}'' with ''{1}''", new Object[]{name, t}); } return t; }

Target:
static String unprotectPerforceFilename(String name) { String t = name.replace("%40", "@"); t = t.replace("%23", "#"); t = t.replace("%2A", "*"); t = t.replace("%25", "%"); if (LOGGER.isLoggable(Level.FINEST) && !name.equals(t)) { LOGGER.log(Level.FINEST, "unprotectPerforceFilename: replaced ''{0}'' with ''{1}''", new Object[]{name, t}); } return t; }
Source:
public void closeCurrentColumn() { if (currentlySelectedColumn.isPresent()) { int columnIndex = currentlySelectedColumn.get(); System.out.println("Going to close column " + columnIndex); closeColumn(columnIndex); if (getChildren() == null || getChildren().size() == 0) { currentlySelectedColumn = Optional.empty(); } else { int newColumnIndex = (columnIndex > getChildren().size() - 1) ? columnIndex - 1 : columnIndex; System.out.println("jumping to column " + newColumnIndex); currentlySelectedColumn = Optional.of(newColumnIndex); getColumn(currentlySelectedColumn.get()).requestFocus(); } } }

Target:
public void closeCurrentColumn() { if (currentlySelectedColumn.isPresent()) { int columnIndex = currentlySelectedColumn.get(); closeColumn(columnIndex); if (getChildren().size() == 0) { currentlySelectedColumn = Optional.empty(); } else { int newColumnIndex = (columnIndex > getChildren().size() - 1) ? columnIndex - 1 : columnIndex; currentlySelectedColumn = Optional.of(newColumnIndex); getColumn(currentlySelectedColumn.get()).requestFocus(); } } }
Source:
public void buildAndInstallExistentProject() throws Exception{ DefaultLocalExecutor executor = new DefaultLocalExecutor(executorService); CompletableFuture<KieCompilationResponse> futureRes = executor.buildAndInstall(Paths.get(tmpRoot.toAbsolutePath()+"/dummy"), mavenRepo.toString()); KieCompilationResponse res = futureRes.get(); assertThat(res.isSuccessful()).isTrue(); assertThat(res.getDependencies()).isEmpty(); assertThat(res.getDependencies().size()).isGreaterThan(0); }

Target:
public void buildAndInstallExistentProject() throws Exception{ DefaultLocalExecutor executor = new DefaultLocalExecutor(executorService); CompletableFuture<KieCompilationResponse> futureRes = executor.buildAndInstall(Paths.get(tmpRoot.toAbsolutePath()+"/dummy"), mavenRepo.toString()); KieCompilationResponse res = futureRes.get(); assertThat(res.isSuccessful()).isTrue(); assertThat(res.getDependencies()).isNotEmpty(); assertThat(res.getDependencies().size()).isGreaterThan(0); }
Source:
public double distance(OGCGeometry another) { double minD = 0; for (int i = 0, n = numGeometries(); i < n; ++i) { double d = geometryN(i).distance(another); if (d < minD) { minD = d; if (minD == 0) { break; } } } return minD; }

Target:
public double distance(OGCGeometry another) { if (this == another) return isEmpty() ? Double.NaN : 0; double minD = Double.NaN; for (int i = 0, n = numGeometries(); i < n; ++i) { double d = geometryN(i).distance(another); if (d < minD || Double.isNaN(minD)) { minD = d; if (minD == 0) { break; } } } return minD; }
Source:
public View getViewById(View rowView, int viewId) { View view = getCacheViewId(viewId); if (view == null) { Log.w(TAG, "Row Item View with Id " + viewId + " not found in Cache. " + "Consideing caching elememts that you access in the renderer since it can improve " + "efficiency by 15%"); return rowView.findViewById(viewId); } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Found Row Item View with Id " + viewId + " in Cache."); } return view; } }

Target:
public View getViewById(View rowView, int viewId) { View view = viewCache.get(viewId); if (view == null) { Log.w(TAG, "Row Item View with Id " + viewId + " not found in Cache. " + "Consideing caching elememts that you access in the renderer since it can improve " + "efficiency by 15%"); return rowView.findViewById(viewId); } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Found Row Item View with Id " + viewId + " in Cache."); } return view; } }
Source:
public String formatForBigtable(String hbaseColumnFamily) { return tableMetadataSetter.getFormattedV1TableName() + "/columnFamilies/" + hbaseColumnFamily; }

Target:
public String formatForBigtable(String hbaseColumnFamily) { return String.format("%s/%s/%s", tableMetadataSetter.getFormattedV1TableName(), COLUMN_FAMILIES_SEPARARATOR, hbaseColumnFamily); }
Source:
public void withReticulate(final String progressCaption, final String userPrompt, final Command command) { withDependencies( progressCaption, userPrompt, new Dependency[] { Dependency.cranPackage("jsonlite", "0.9.19"), Dependency.cranPackage("png", "0.1-7"), Dependency.cranPackage("reticulate", "1.6"), }, true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } }); }

Target:
public void withReticulate(final String progressCaption, final String userPrompt, final Command command) { withDependencies( progressCaption, userPrompt, new Dependency[] { Dependency.cranPackage("jsonlite", "0.9.19"), Dependency.cranPackage("png", "0.1-7"), Dependency.cranPackage("reticulate", "1.10"), }, true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } }); }
Source:
protected int doHash(TopicRef topicRef) { return Objects.hash(topicRef.getTopic()); }

Target:
protected int doHash(TopicRef topicRef) { return topicRef.hashCode(); }
Source:
public BungeeBossBar(BaseComponent[] title, BarColor color, BarStyle style, float progress) { this.title = Preconditions.checkNotNull( title, "title" ); this.color = Preconditions.checkNotNull( color, "color" ); this.style = Preconditions.checkNotNull( style, "style" ); Preconditions.checkArgument( 0 <= progress && progress <= 1, "Progress may not be lower than 0 or greater than 1" ); this.progress = progress; this.visible = true; this.players = new HashSet<>(); this.flags = EnumSet.noneOf( BarFlag.class ); this.uuid = UUID.randomUUID(); }

Target:
public BungeeBossBar(BaseComponent[] title, BarColor color, BarStyle style, float progress) { this.title = Preconditions.checkNotNull( title, "title" ); this.color = Preconditions.checkNotNull( color, "color" ); this.style = Preconditions.checkNotNull( style, "style" ); Preconditions.checkArgument( 0 <= progress && progress <= 1, "Progress may not be lower than 0 or greater than 1" ); this.progress = progress; this.visible = true; this.players = new HashSet<>(); this.flags = EnumSet.noneOf( BarFlag.class ); this.removePacket = new BossBar( uuid, 1 ); }
Source:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (courseData == null || !IS_COURSEWARE_ACCESSIBLE) return; final String headerImageUrl = courseData.getCourse().getCourse_image(environment.getConfig()); Glide.with(CourseDashboardFragment.this) .load(headerImageUrl) .placeholder(R.drawable.edx_map_login) .transform(new TopAnchorFillWidthTransformation(getActivity())) .into(headerImageView); courseTextName.setText(courseData.getCourse().getName()); CourseEntry course = courseData.getCourse(); courseTextDetails.setText(course.getDescription(getActivity())); }

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (courseData == null || !isCoursewareAccessible) return; final String headerImageUrl = courseData.getCourse().getCourse_image(environment.getConfig()); Glide.with(CourseDashboardFragment.this) .load(headerImageUrl) .placeholder(R.drawable.edx_map_login) .transform(new TopAnchorFillWidthTransformation(getActivity())) .into(headerImageView); courseTextName.setText(courseData.getCourse().getName()); CourseEntry course = courseData.getCourse(); courseTextDetails.setText(course.getDescription(getActivity())); }
Source:
public List<PatchSetApproval> copyApprovalsToLatestPatchSet( @GerritServerConfig Config cfg, ReviewDb db, Change change) throws OrmException { PatchSet.Id source; if (change.getNumberOfPatchSets() > 1) { source = new PatchSet.Id(change.getId(), change.getNumberOfPatchSets() - 1); } else { throw new OrmException("Previous patch set could not be found"); } PatchSet.Id dest = change.currPatchSetId(); List<PatchSetApproval> patchSetApprovals = db.patchSetApprovals().byChange(change.getId()).toList(); for (PatchSetApproval a : patchSetApprovals) { if (!ApprovalCategory.SUBMIT.equals(a.getCategoryId())) { final ApprovalType type = approvalTypes.byId(a.getCategoryId()); if ((a.getPatchSetId().equals(source) && type.getCategory().isCopyMinScore() && type.isMaxNegative(a)) || cfg.getBoolean("approvals", a.getCategoryId().get(), "stickThroughRebase", false)) { db.patchSetApprovals().insert( Collections.singleton(new PatchSetApproval(dest, a))); } } } return patchSetApprovals; }

Target:
public List<PatchSetApproval> copyApprovalsToLatestPatchSet( @GerritServerConfig Config cfg, ReviewDb db, Change change) throws OrmException { PatchSet.Id source; if (change.getNumberOfPatchSets() > 1) { source = new PatchSet.Id(change.getId(), change.getNumberOfPatchSets() - 1); } else { throw new OrmException("Previous patch set could not be found"); } PatchSet.Id dest = change.currPatchSetId(); List<PatchSetApproval> patchSetApprovals = db.patchSetApprovals().byChange(change.getId()).toList(); final List<PatchSetApproval> toInsert = new ArrayList<PatchSetApproval>(); boolean globalStickThroughRebase = cfg.getBoolean( "approval", null, "stickThroughRebase", false); for (PatchSetApproval a : patchSetApprovals) { if (!ApprovalCategory.SUBMIT.equals(a.getCategoryId())) { final ApprovalType type = approvalTypes.byId(a.getCategoryId()); boolean typeSpecificStickThroughRebase = cfg.getBoolean( "approval", a.getCategoryId().get(), "stickThroughRebase", false); if ((a.getPatchSetId().equals(source) && type.getCategory().isCopyMinScore() && type.isMaxNegative(a)) || globalStickThroughRebase || typeSpecificStickThroughRebase) { toInsert.add(new PatchSetApproval(dest, a)); } } } db.patchSetApprovals().insert(toInsert); return patchSetApprovals; }
Source:
public String getNamespace() { return AbstractNodesProvider.getNodesNamespace(); }

Target:
public String getNamespace() { return OnmsTopology.TOPOLOGY_NAMESPACE_LINKD; }
Source:
public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeLimitPercentageParam = (String) serverContext.getServerConfig().get("--log-size-quota-percentage"); final double logSizeLimitPercentage = Double.parseDouble(logSizeLimitPercentageParam); if (logSizeLimitPercentage < 0.0 || 100.0 < logSizeLimitPercentage) { String msg = String.format("Invalid quota: quota(%f)%% must be between 0-100%%", logSizeLimitPercentage); throw new LogUnitException(msg); } String codec = (String) serverContext.getServerConfig().get("--compression-codec"); compressionCodec = Codec.Type.valueOf(codec); long fileSystemCapacity = initStreamLogDirectory(); logSizeLimit = (long) (fileSystemCapacity * logSizeLimitPercentage / 100.0); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }

Target:
public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeLimitPercentageParam = (String) serverContext.getServerConfig().get("--log-size-quota-percentage"); final double logSizeLimitPercentage = Double.parseDouble(logSizeLimitPercentageParam); if (logSizeLimitPercentage < 0.0 || 100.0 < logSizeLimitPercentage) { String msg = String.format("Invalid quota: quota(%f)%% must be between 0-100%%", logSizeLimitPercentage); throw new LogUnitException(msg); } String codec = (String) serverContext.getServerConfig().get("--compression-codec"); codecType = Codec.Type.valueOf(codec); long fileSystemCapacity = initStreamLogDirectory(); logSizeLimit = (long) (fileSystemCapacity * logSizeLimitPercentage / 100.0); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }
Source:
private List<FeedItem> getFavorites() { int page = 0; List<FeedItem> favoritesPage = DBReader.getFavoriteItemsList(page, PAGE_LIMIT); List<FeedItem> favoritesList = new ArrayList<>(); while (!favoritesPage.isEmpty()) { favoritesList.addAll(favoritesPage); if (favoritesPage.size() < PAGE_LIMIT) { break; } ++page; favoritesPage = DBReader.getFavoriteItemsList(page * PAGE_LIMIT, PAGE_LIMIT); } Collections.sort(favoritesList, (lhs, rhs) -> rhs.getPubDate().compareTo(lhs.getPubDate())); return favoritesList; }

Target:
private List<FeedItem> getFavorites() { int page = 0; List<FeedItem> favoritesList = new ArrayList<>(); List<FeedItem> favoritesPage; do { favoritesPage = DBReader.getFavoriteItemsList(page * PAGE_LIMIT, PAGE_LIMIT); favoritesList.addAll(favoritesPage); ++page; } while (!favoritesPage.isEmpty() && favoritesPage.size() == PAGE_LIMIT); Collections.sort(favoritesList, (lhs, rhs) -> rhs.getPubDate().compareTo(lhs.getPubDate())); return favoritesList; }
Source:
private List<TeamInviteResponse> teamInviteTokensToReponses(Collection<TeamInviteToken> inviteTokens) { if (!inviteTokens.isEmpty()) { return inviteTokens.stream().filter(Token::isValid) .map(t -> new TeamInviteResponse(t.getTeam().getId(), t.getTeam().getTeamName(), t.getToken(), t.getUser().getUsername())).collect(Collectors.toList()); } else { return Collections.emptyList(); } }

Target:
private List<TeamInviteResponse> teamInviteTokensToReponses(Collection<TeamInviteToken> inviteTokens) { return inviteTokens.stream(). filter(Token::isValid). map(t -> new TeamInviteResponse(t.getTeam().getId(), t.getTeam().getTeamName(), t.getToken(), t.getUser().getUsername())). collect(Collectors.toList()); }
Source:
private String[] getExecutorCommand(int container) { List<Integer> freePorts = new ArrayList<>(SchedulerUtils.PORTS_REQUIRED_FOR_EXECUTOR); for (int i = 0; i < SchedulerUtils.PORTS_REQUIRED_FOR_EXECUTOR; i++) { freePorts.add(5000 + (i + (container * 10))); } String[] executorCmd = SchedulerUtils.executorCommand(config, runtime, container, freePorts); String finalExecCommand = setClusterValues(formHeronExecCommand(executorCmd)); String ecsTaskProject = EcsContext.topologyName(config) + "_" + String.valueOf(container); FileOutputStream dockerFilestream = null; String content = null; try { tempDockerFile = File.createTempFile("docker", ".yml"); content = getDockerFileContent(finalExecCommand, container); tempDockerFile.setWritable(true); dockerFilestream = new FileOutputStream(tempDockerFile); IOUtils.write(content, dockerFilestream); IOUtils.closeQuietly(dockerFilestream); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(dockerFilestream); } String dockerComposeFileName = " --file " + tempDockerFile; String finalCommand = EcsContext.COMPOSE_CMD + ecsTaskProject + dockerComposeFileName; finalCommand = finalCommand + EcsContext.UP; System.out.println("final Ecs Task command " + finalCommand); tempDockerFile.deleteOnExit(); return new String[] {finalCommand}; }

Target:
protected String[] getExecutorCommand(int container) { List<Integer> freePorts = new ArrayList<>(SchedulerUtils.PORTS_REQUIRED_FOR_EXECUTOR); Integer localFreePort = null; nfreePorts = new StringBuilder(); for (int i = 0; i < SchedulerUtils.PORTS_REQUIRED_FOR_EXECUTOR; i++) { localFreePort = SysUtils.getFreePort(); freePorts.add(localFreePort); nfreePorts.append("\n - \""); nfreePorts.append(localFreePort); nfreePorts.append(":"); nfreePorts.append(localFreePort); nfreePorts.append("\""); } String[] executorCmd = SchedulerUtils.executorCommand(config, runtime, container, freePorts); String finalExecCommand = setClusterValues(formHeronExecCommand(executorCmd)); String ecsTaskProject = EcsContext.topologyName(config) + "_" + container; FileOutputStream dockerFilestream = null; String content = null; try { tempDockerFile = File.createTempFile("docker", ".yml"); content = getDockerFileContent(finalExecCommand, container); tempDockerFile.setWritable(true); dockerFilestream = new FileOutputStream(tempDockerFile); IOUtils.write(content, dockerFilestream); IOUtils.closeQuietly(dockerFilestream); } catch (IOException e) { LOG.severe("Unable to create ecs task for container: " + container); } finally { IOUtils.closeQuietly(dockerFilestream); } String finalCommand = String.format("%s %s --file %s up", EcsContext.composeupCmd(config), ecsTaskProject, tempDockerFile); LOG.info("final Ecs Task command " + finalCommand); return new String[] {finalCommand}; }
Source:
private void parseSubApp(Node node) throws TypeImportException { SubApp subApp = LibraryElementFactory.eINSTANCE.createSubApp(); NamedNodeMap map = node.getAttributes(); Node name = map.getNamedItem(LibraryElementTags.NAME_ATTRIBUTE); if (name != null) { subApp.setName(name.getNodeValue()); } else { throw new TypeImportException(Messages.SubAppTImporter_ERROR_SubAppName); } Node type = map.getNamedItem(LibraryElementTags.TYPE_ATTRIBUTE); if (type != null) { configureSubAppInterface(subApp, node, type.getNodeValue()); } else { parseUntypedSubapp(subApp, node.getChildNodes()); } Node comment = map.getNamedItem(LibraryElementTags.COMMENT_ATTRIBUTE); if (comment != null) { subApp.setComment(comment.getNodeValue()); } CommonElementImporter.getXandY(map, subApp); configureParameters(subApp.getInterface(), node.getChildNodes()); getFbNetwork().getNetworkElements().add(subApp); fbNetworkElementMap.put(subApp.getName(), subApp); }

Target:
private void parseSubApp(Node node) throws TypeImportException { SubApp subApp = LibraryElementFactory.eINSTANCE.createSubApp(); NamedNodeMap map = node.getAttributes(); Node name = map.getNamedItem(LibraryElementTags.NAME_ATTRIBUTE); if (null != name) { subApp.setName(name.getNodeValue()); } else { throw new TypeImportException(Messages.SubAppTImporter_ERROR_SubAppName); } Node type = map.getNamedItem(LibraryElementTags.TYPE_ATTRIBUTE); if (null != type) { configureSubAppInterface(subApp, node, type.getNodeValue()); } else { parseUntypedSubapp(subApp, node.getChildNodes()); } Node comment = map.getNamedItem(LibraryElementTags.COMMENT_ATTRIBUTE); if (null != comment) { subApp.setComment(comment.getNodeValue()); } CommonElementImporter.getXandY(map, subApp); configureParameters(subApp.getInterface(), node.getChildNodes()); getFbNetwork().getNetworkElements().add(subApp); fbNetworkElementMap.put(subApp.getName(), subApp); }
Source:
public boolean isKey(RelOptTable table, List<Integer> columns) { return columns.size() == 1 && keyMap.get(table.getQualifiedName().toString()) .equals( ImmutableList.of(table.getRowType().getFieldList() .get(columns.get(0)).getName())); }

Target:
public boolean isKey(RelOptTable table, List<Integer> columns) { return columns.stream().allMatch(columnOrdinal -> (columnOrdinal >= 0) && (columnOrdinal < table.getRowType().getFieldCount())) && keyMap.get(table.getQualifiedName().toString()) .contains(columnNames(table, columns)); }
Source:
BlobChangefeedPagedResponse(List<BlobChangefeedEvent> events, BlobChangefeedCursor cursor) { this.events = events; this.cursor = cursor; System.out.println(events.get(0).getId()); System.out.println(getContinuationToken()); System.out.println(events.get(events.size() - 1).getId()); }

Target:
BlobChangefeedPagedResponse(List<BlobChangefeedEvent> events, BlobChangefeedCursor cursor) { this.events = events; this.cursor = cursor; }
Source:
public Map<KeyT, ValueT> decode( @Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { if (bytes == null || bytes.remaining() == 0) { return new LinkedHashMap<>(0); } else { ByteBuffer input = bytes.duplicate(); int size = input.getInt(); Map<KeyT, ValueT> result = Maps.newLinkedHashMapWithExpectedSize(size); for (int i = 0; i < size; i++) { KeyT key; int keySize = input.getInt(); if (keySize < 0) { key = null; } else { ByteBuffer encodedKey = input.slice(); encodedKey.limit(keySize); input.position(input.position() + keySize); key = keyCodec.decode(encodedKey, protocolVersion); } ValueT value; int valueSize = input.getInt(); if (valueSize < 0) { value = null; } else { ByteBuffer encodedValue = input.slice(); encodedValue.limit(valueSize); input.position(input.position() + valueSize); value = valueCodec.decode(encodedValue, protocolVersion); } result.put(key, value); } return result; } }

Target:
public Map<KeyT, ValueT> decode( @Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { if (bytes == null || bytes.remaining() == 0) { return new LinkedHashMap<>(0); } else { ByteBuffer input = bytes.duplicate(); int size = input.getInt(); Map<KeyT, ValueT> result = Maps.newLinkedHashMapWithExpectedSize(size); for (int i = 0; i < size; i++) { KeyT key; int keySize = input.getInt(); if (keySize < 0) { key = null; } else { ByteBuffer encodedKey = input.slice(); encodedKey.limit(keySize); key = keyCodec.decode(encodedKey, protocolVersion); input.position(input.position() + keySize); } ValueT value; int valueSize = input.getInt(); if (valueSize < 0) { value = null; } else { ByteBuffer encodedValue = input.slice(); encodedValue.limit(valueSize); value = valueCodec.decode(encodedValue, protocolVersion); input.position(input.position() + valueSize); } result.put(key, value); } return result; } }
Source:
private void addContact(@NotNull JID jid, @NotNull String nickname) { BiPredicate<String, String> dialog = (title, message) -> { boolean choseYes; try { choseYes = SafeDialogUtils.showYesNoDialog(project, message, title); } catch (IllegalAWTContextException e) { log.error("Tried to run dialog in an illegal context", e); showAccountCreationFailedErrorNotification(e); return false; } return choseYes; }; try { xmppContactsService.addContact(jid, nickname, dialog); } catch (OperationCanceledException e) { log.debug("Adding contact canceled by user during XMPP request", e); } }

Target:
private void addContact(@NotNull JID jid, @NotNull String nickname) { BiPredicate<String, String> dialog = (title, message) -> { try { return SafeDialogUtils.showYesNoDialog(project, message, title); } catch (IllegalAWTContextException e) { log.error("Tried to run dialog in an illegal context", e); showAccountCreationFailedErrorNotification(e); return false; } }; try { xmppContactsService.addContact(jid, nickname, dialog); } catch (OperationCanceledException e) { log.debug("Adding contact canceled by user during XMPP request", e); } }