auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void create(final String name) throws IOException { if (name.length() < DyAttachments.MIN || name.length() > DyAttachments.MAX) { throw new Attachments.InvalidNameException( String.format( "invalid attachment name length \"%s\". %s%s", name, "The length of the attachment name must be ", "between 3-100 characters" ) ); <START> } else if (!name.matches("[a-zA-Z\\.\\-0-9]{3,100}")) { <END> throw new Attachments.InvalidNameException( String.format( "invalid attachment name \"%s\". %s%s", name, "Attachment name can contains letters in upper ", "or lower case, numbers, dots, dashes." ) ); } this.region.table(DyAttachments.TBL).put( new Attributes() .with(DyAttachments.HASH, this.bout) .with(DyAttachments.RANGE, name) .with(DyAttachments.ATTR_ALIAS, this.self) .with(DyAttachments.ATTR_CTYPE, "text/plain") .with(DyAttachments.ATTR_DATA, " ") .with(DyAttachments.ATTR_ETAG, "empty") ); Logger.info(this, "attachment %s created in #%d", name, this.bout); }</code><technical_language>@kujtimiihoxha please read <LINK_0></technical_language>

Target:
public void create(final String name) throws IOException { if (!name.matches("[a-zA-Z\\.\\-0-9]{3,100}")) { if (name.length() < DyAttachments.MIN || name.length() > DyAttachments.MAX) { throw new Attachments.InvalidNameException( String.format( "invalid attachment name length \"%s\". %s%s", name, "The length of the attachment name must be ", "between 3-100 characters" ) ); } throw new Attachments.InvalidNameException( String.format( "invalid attachment name \"%s\". %s%s", name, "Attachment name can contains letters in upper ", "or lower case, numbers, dots, dashes." ) ); } this.region.table(DyAttachments.TBL).put( new Attributes() .with(DyAttachments.HASH, this.bout) .with(DyAttachments.RANGE, name) .with(DyAttachments.ATTR_ALIAS, this.self) .with(DyAttachments.ATTR_CTYPE, "text/plain") .with(DyAttachments.ATTR_DATA, " ") .with(DyAttachments.ATTR_ETAG, "empty") ); Logger.info(this, "attachment %s created in #%d", name, this.bout); }
Source:
<code>public void csarFilesHaveImmutableStorageAddresses() throws Exception { Map<String, Object> exportConfiguration = new HashMap<>(); <START> exportConfiguration.put(STORE_IMMUTABLY.name(), new HashMap<>()); <END> try (InputStream inputStream = this.createOutputAndInputStream( "origin/plain", new ServiceTemplateId("<LINK_0>", "ServiceTemplateWithAllReqCapVariants", false), exportConfiguration); ZipInputStream zis = new ZipInputStream(inputStream)) { ManifestContents manifestContents = parseManifest(zis); assertNotNull(manifestContents); for (String section : manifestContents.getSectionNames()) { assertNotNull(manifestContents.getAttributesForSection(section).get(TOSCAMetaFileAttributes.IMMUTABLE_ADDRESS)); } } }</code><technical_language>do store HashMap in configuration</technical_language>

Target:
public void csarFilesHaveImmutableStorageAddresses() throws Exception { Map<String, Object> exportConfiguration = new HashMap<>(); exportConfiguration.put(STORE_IMMUTABLY.name(), null); try (InputStream inputStream = this.createOutputAndInputStream( "origin/plain", new ServiceTemplateId("<LINK_0>", "ServiceTemplateWithAllReqCapVariants", false), exportConfiguration); ZipInputStream zis = new ZipInputStream(inputStream)) { ManifestContents manifestContents = parseManifest(zis); assertNotNull(manifestContents); for (String section : manifestContents.getSectionNames()) { assertNotNull(manifestContents.getAttributesForSection(section).get(TOSCAMetaFileAttributes.IMMUTABLE_ADDRESS)); } } }
Source:
<code>private String getSshServerAddress(Machine machine) { Map<String, ? extends Server> servers = machine.getRuntime().getServers(); <START> return servers.containsKey(SSH_PORT + "/tcp") ? servers.get(SSH_PORT + "/tcp").getAddress() : null; <END> }</code><technical_language>simplify this complex construction decomposing servers.get(SSH_PORT + "/tcp") variable if/else block java final Server sshServer = servers.get(SSH_PORT + "/tcp"); if (sshServer == null){ return null; } else { return sshServer.getAddress(); } similar. do think, fits in opinion</technical_language>

Target:
private String getSshServerAddress(Machine machine) { Map<String, ? extends Server> servers = machine.getRuntime().getServers(); final Server sshServer = servers.get(SSH_PORT + "/tcp"); return sshServer != null ? sshServer.getAddress() : null; }
Source:
<code>net.sf.launch4j.config.ClassPath toL4j(Set<Artifact> dependencies, List<Artifact> runtimeDependencies) { net.sf.launch4j.config.ClassPath ret = new net.sf.launch4j.config.ClassPath(); ret.setMainClass(mainClass); List<String> cp = new ArrayList<String>(); if (preCp != null) addToCp(cp, preCp); if (addDependencies) { if (jarLocation == null) jarLocation = ""; else if ( ! jarLocation.endsWith("/")) jarLocation += "/"; dependencies.addAll(runtimeDependencies); for (Artifact dependency : dependencies) { <START> Artifact dep = (Artifact) dependency; <END> if (Artifact.SCOPE_COMPILE.equals(dep.getScope()) || Artifact.SCOPE_RUNTIME.equals(dep.getScope())) { String depFilename; depFilename = dep.getFile().getName(); cp.add(jarLocation + depFilename); } } } if (postCp != null) addToCp(cp, postCp); ret.setPaths(cp); return ret; }</code><technical_language>This needed anymore</technical_language>

Target:
net.sf.launch4j.config.ClassPath toL4j(Set<Artifact> dependencies, List<Artifact> runtimeDependencies) { net.sf.launch4j.config.ClassPath ret = new net.sf.launch4j.config.ClassPath(); ret.setMainClass(mainClass); List<String> cp = new ArrayList<String>(); if (preCp != null) addToCp(cp, preCp); if (addDependencies) { if (jarLocation == null) jarLocation = ""; else if ( ! jarLocation.endsWith("/")) jarLocation += "/"; dependencies.addAll(runtimeDependencies); for (Artifact dependency : dependencies) { if (Artifact.SCOPE_COMPILE.equals(dependency.getScope()) || Artifact.SCOPE_RUNTIME.equals(dependency.getScope())) { String depFilename; depFilename = dependency.getFile().getName(); cp.add(jarLocation + depFilename); } } } if (postCp != null) addToCp(cp, postCp); ret.setPaths(cp); return ret; }
Source:
<code>public void setChromeOptions(WebDriverConfiguration configuration, DesiredCapabilities capabilities) { ChromeOptions chromeOptions = new ChromeOptions(); String browser = configuration.getBrowser().toLowerCase(); if (browser.equals("chromeheadless")) { chromeOptions.addArguments("--headless"); <START> chromeOptions.addArguments("--window-size=1200,600"); <END> } CapabilitiesOptionsMapper.mapCapabilities(chromeOptions, capabilities, BROWSER_CAPABILITIES); String binary = (String) capabilities.getCapability("chrome.binary"); if (Validate.nonEmpty(binary)) { chromeOptions.setBinary(binary); } capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); String printChromeOptions = (String) capabilities.getCapability(CHROME_PRINT_OPTIONS); if (Validate.nonEmpty(printChromeOptions) && Boolean.valueOf(printChromeOptions.trim())) { try { StringBuffer chromeOptionsLog = new StringBuffer("\n"); chromeOptionsLog.append("======== Chrome options =========").append("\n"); chromeOptionsLog.append(chromeOptions.toJson().toString()).append("\n"); chromeOptionsLog.append("===== End of Chrome options ====="); log.info(chromeOptionsLog.toString()); } catch (IOException e) { log.warning("Something bad happened during printing chrome options: "); log.warning(e.getMessage()); } } }</code><technical_language>if setting specific sizes is approach - this size bigger smaller one...? if this (or other) sizes unexpected problems some platforms/PC configurations. I imagine size in dimensions property, otherwise, I set anything</technical_language>

Target:
public void setChromeOptions(WebDriverConfiguration configuration, DesiredCapabilities capabilities) { ChromeOptions chromeOptions = new ChromeOptions(); Dimensions dimensions = new Dimensions(configuration); String browser = configuration.getBrowser().toLowerCase(); if (browser.equals("chromeheadless")) { chromeOptions.addArguments("--headless"); if (dimensions.hasFullscreenEnabled()) { log.info( String.format("Chrome Headless does not support fullscreen. Setting default window-size to %dx%d", dimensions.getWidth(), dimensions.getHeight())); } chromeOptions.addArguments( String.format("--window-size=%d,%d", dimensions.getWidth(), dimensions.getHeight())); } CapabilitiesOptionsMapper.mapCapabilities(chromeOptions, capabilities, BROWSER_CAPABILITIES); String binary = (String) capabilities.getCapability("chrome.binary"); if (Validate.nonEmpty(binary)) { chromeOptions.setBinary(binary); } capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); String printChromeOptions = (String) capabilities.getCapability(CHROME_PRINT_OPTIONS); if (Validate.nonEmpty(printChromeOptions) && Boolean.valueOf(printChromeOptions.trim())) { try { StringBuffer chromeOptionsLog = new StringBuffer("\n"); chromeOptionsLog.append("======== Chrome options =========").append("\n"); chromeOptionsLog.append(chromeOptions.toJson().toString()).append("\n"); chromeOptionsLog.append("===== End of Chrome options ====="); log.info(chromeOptionsLog.toString()); } catch (IOException e) { log.warning("Something bad happened during printing chrome options: "); log.warning(e.getMessage()); } } }
Source:
<code>@Override public void run(JsonNode jsonNode) throws Exception { String cacheName = jsonNode.get("cacheName").asText(); int warmup = jsonNode.get("warmup").asInt(); String cell = jsonNode.get("cell").asText(); String attr = jsonNode.get("attr").asText(); markInitialized(); waitForActivation(); IgniteCache<Integer, Integer> cache = ignite.getOrCreateCache(cacheName); long[] max = new long[20]; Arrays.fill(max, -1); <START> int key = 10_000_000; <END> int cnt = 0; long initTime = 0; boolean record = false; Affinity<Integer> aff = ignite.affinity(cacheName); while (!terminated()) { key++; Collection<ClusterNode> nodes = aff.mapKeyToPrimaryAndBackups(key); Map<Object, Long> stat = nodes.stream().collect( Collectors.groupingBy(n -> n.attributes().get(attr), Collectors.counting())); if (!stat.containsKey(cell)) continue; cnt++; long start = System.currentTimeMillis(); cache.put(key, key); long finish = System.currentTimeMillis(); long time = finish - start; if (!record && cnt > warmup) { record = true; initTime = System.currentTimeMillis(); log.info("Warmup finished"); } if (record) { for (int i = 0; i < max.length; i++) { if (max[i] <= time) { System.arraycopy(max, i, max, i + 1, max.length - i - 1); max[i] = time; break; } } } if (cnt % 1000 == 0) log.info("Application streamed " + cnt + " transactions [worst_latency=" + Arrays.toString(max) + "]"); } recordResult("WORST_LATENCY", Arrays.toString(max)); recordResult("STREAMED", cnt - warmup); recordResult("MEASURE_DURATION", System.currentTimeMillis() - initTime); markFinished(); }</code><technical_language>10_000_000? this fact in code</technical_language>

Target:
@Override public void run(JsonNode jsonNode) throws Exception { String cacheName = jsonNode.get("cacheName").asText(); int warmup = jsonNode.get("warmup").asInt(); String cell = jsonNode.get("cell").asText(); String attr = jsonNode.get("attr").asText(); markInitialized(); waitForActivation(); IgniteCache<Integer, Integer> cache = ignite.getOrCreateCache(cacheName); long[] max = new long[20]; Arrays.fill(max, -1); int key = 0; int cnt = 0; long initTime = 0; boolean record = false; Affinity<Integer> aff = ignite.affinity(cacheName); while (!terminated()) { key++; Collection<ClusterNode> nodes = aff.mapKeyToPrimaryAndBackups(key); Map<Object, Long> stat = nodes.stream().collect( Collectors.groupingBy(n -> n.attributes().get(attr), Collectors.counting())); if (!stat.containsKey(cell)) continue; cnt++; long start = System.currentTimeMillis(); cache.put(key, key); long finish = System.currentTimeMillis(); long time = finish - start; if (!record && cnt > warmup) { record = true; initTime = System.currentTimeMillis(); log.info("Warmup finished"); } if (record) { for (int i = 0; i < max.length; i++) { if (max[i] <= time) { System.arraycopy(max, i, max, i + 1, max.length - i - 1); max[i] = time; break; } } } if (cnt % 1000 == 0) log.info("Application streamed " + cnt + " transactions [worst_latency=" + Arrays.toString(max) + "]"); } recordResult("WORST_LATENCY", Arrays.toString(max)); recordResult("STREAMED", cnt - warmup); recordResult("MEASURE_DURATION", System.currentTimeMillis() - initTime); markFinished(); }
Source:
<code>private String extractPragmasFromFilename(String filename, Properties prop) { int parameterDelimiter = filename.indexOf('?'); if (parameterDelimiter == -1) { return filename; } StringBuilder sb = new StringBuilder(); sb.append(filename.substring(0, parameterDelimiter)); String parameters = filename.substring(parameterDelimiter + 1).split("&"); for (int i = 0 ; i < parameters.length; i++) { <START> final String parameter = parameters[i]; <END> final String kvp = parameter.toLowerCase().split("="); final String key = kvp[0].trim(); if (pragmaSet.contains(key)) { final String value = kvp[1].trim(); if (!value.isEmpty()) { prop.setProperty(key, value); } } else { if (i == 0) { sb.append('?'); } else { sb.append('&'); } sb.append(parameter); } } final String newFilename = sb.toString(); return newFilename; }</code><technical_language>Please remove final keyword. JVM eyes smart enough detect variables constant for this amount of code</technical_language>

Target:
private String extractPragmasFromFilename(String filename, Properties prop) throws SQLException { int parameterDelimiter = filename.indexOf('?'); if (parameterDelimiter == -1) { return filename; } StringBuilder sb = new StringBuilder(); sb.append(filename.substring(0, parameterDelimiter)); int nonPragmaCount = 0; String parameters = filename.substring(parameterDelimiter + 1).split("&"); for (int i = 0; i < parameters.length; i++) { String parameter = parameters[parameters.length - 1 - i].trim(); if (parameter.isEmpty()) { continue; } String kvp = parameter.toLowerCase().split("="); String key = kvp[0].trim(); if (pragmaSet.contains(key)) { if (kvp.length == 1) { throw new SQLException(String.format("Please specify a value for PRAGMA %s in URL %s", key, url)); } String value = kvp[1].trim(); if (!value.isEmpty()) { if (prop.containsKey(key)) { } else { prop.setProperty(key, value); } } } else { sb.append(nonPragmaCount == 0 ? '?' : '&'); sb.append(parameter); nonPragmaCount++; } } final String newFilename = sb.toString(); return newFilename; }
Source:
<code>public void setFirstPaymentDate() { nextPayment = nextPayment.plusDays(1); int temp; switch (schedule) { case Finances.SCHEDULE_BIWEEKLY: <START> temp = 8 - nextPayment.getDayOfWeek().getValue(); <END> if (temp != 7) { nextPayment = nextPayment.plusDays(temp); } nextPayment = nextPayment.plusWeeks(2); break; case Finances.SCHEDULE_MONTHLY: temp = nextPayment.getDayOfMonth(); if (temp != 1) { nextPayment = nextPayment.plusDays(nextPayment.lengthOfMonth() - temp); } nextPayment = nextPayment.plusMonths(1); break; case Finances.SCHEDULE_QUARTERLY: temp = nextPayment.getDayOfMonth(); if (temp != 1) { nextPayment = nextPayment.plusDays(nextPayment.lengthOfMonth() - temp); } nextPayment = nextPayment.plusMonths(3); break; case Finances.SCHEDULE_YEARLY: temp = nextPayment.getDayOfYear(); if (temp != 1) { nextPayment = nextPayment.plusDays(nextPayment.lengthOfYear() - temp); } nextPayment = nextPayment.plusYears(1); break; } }</code><technical_language>This logic needs explanation, if for next Monday/Sunday is a more obvious way: d.with(TemporalAdjusters.next(DayOfWeek.MONDAY));</technical_language>

Target:
public void setFirstPaymentDate() { nextPayment = nextPayment.plusDays(1); switch (schedule) { case Finances.SCHEDULE_BIWEEKLY: nextPayment = nextPayment.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY)).plusWeeks(2); break; case Finances.SCHEDULE_MONTHLY: if (nextPayment.getDayOfMonth() != 1) { nextPayment = nextPayment.with(TemporalAdjusters.firstDayOfNextMonth()); } nextPayment = nextPayment.plusMonths(1); break; case Finances.SCHEDULE_QUARTERLY: if (nextPayment.getDayOfMonth() != 1) { nextPayment = nextPayment.with(TemporalAdjusters.firstDayOfNextMonth()); } nextPayment = nextPayment.plusMonths(3); break; case Finances.SCHEDULE_YEARLY: if (nextPayment.getDayOfYear() != 1) { nextPayment = nextPayment.with(TemporalAdjusters.firstDayOfNextYear()); } nextPayment = nextPayment.plusYears(1); break; } }
Source:
<code>public <T> T getMandatoryParameter(String parameterName, Class<T> type) { <START> if ( !parameters.containsKey( parameterName ) ) { <END> throw LOG.getUnableToFindAnnotationParameterException( parameterName, null ); } Object parameter = parameters.get( parameterName ); if ( !type.isAssignableFrom( parameter.getClass() ) ) { throw LOG.getWrongParameterTypeException( type, parameter.getClass() ); } return (T) parameter; }</code><technical_language>avoid containsKey() + get() cascade checking result of null</technical_language>

Target:
public <T> T getMandatoryParameter(String parameterName, Class<T> type) { Object parameter = parameters.get( parameterName ); if ( parameter == null ) { throw LOG.getUnableToFindAnnotationParameterException( parameterName, null ); } if ( !type.isAssignableFrom( parameter.getClass() ) ) { throw LOG.getWrongParameterTypeException( type, parameter.getClass() ); } return (T) parameter; }
Source:
<code>public void setTransform( AffineTransform transform ) { AWTSWTImageUtils.checkAccess(); double[] matrix=new double[6]; transform.getMatrix(matrix); if( swtTransform==null ){ swtTransform=new Transform(display, (float)matrix[0], (float)matrix[2], (float)matrix[1], (float)matrix[3], <START> (float)matrix[4], (float)matrix[5] ); <END> }else{ swtTransform.setElements( (float)matrix[0], (float)matrix[2], (float)matrix[1], (float)matrix[3], (float)matrix[4], (float)matrix[5] ); } gc.setTransform(swtTransform); }</code><technical_language>@akater320, I understand changed ordering of elements put matrix[2] matrix[1] in code above. clarify</technical_language>

Target:
public void setTransform( AffineTransform transform ) { AWTSWTImageUtils.checkAccess(); double[] matrix=new double[6]; transform.getMatrix(matrix); swtTransform.setElements( (float)matrix[0], (float)matrix[2], (float)matrix[1], (float)matrix[3], (float)matrix[4], (float)matrix[5] ); gc.setTransform(swtTransform); }
Source:
<code>public Set<Job> getAllActiveJobsOnHost(@NotBlank final String hostName) { log.debug("Called with hostname {}", hostName); final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<JobEntity> query = cb.createQuery(JobEntity.class); final Root<JobEntity> root = query.from(JobEntity.class); final Join<JobEntity, JobExecutionEntity> executions = root.join(JobEntity_.execution); final Set<Predicate> statusPredicates = JobStatus .getActiveStatuses() .stream() .map(status -> cb.equal(root.get(JobEntity_.status), status)) .collect(Collectors.toSet()); <START> final Predicate statusPredicate = cb.or(statusPredicates.toArray(new Predicate[statusPredicates.size()])); <END> final Predicate hostPredicate = cb.equal(executions.get(JobExecutionEntity_.hostName), hostName); query .distinct(true) .where(cb.and(statusPredicate, hostPredicate)); return this.entityManager .createQuery(query) .getResultList() .stream() .map(JobEntity::getDTO) .collect(Collectors.toSet()); }</code><technical_language>in clause</technical_language>

Target:
public Set<Job> getAllActiveJobsOnHost(@NotBlank final String hostName) { log.debug("Called with hostname {}", hostName); final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<JobEntity> query = cb.createQuery(JobEntity.class); final Root<JobEntity> root = query.from(JobEntity.class); final Join<JobEntity, JobExecutionEntity> executions = root.join(JobEntity_.execution); final Expression<Boolean> statusExpression = root.get(JobEntity_.status).in(JobStatus.getActiveStatuses()); final Predicate hostPredicate = cb.equal(executions.get(JobExecutionEntity_.hostName), hostName); query.where(cb.and(statusExpression, hostPredicate)); return this.entityManager .createQuery(query) .getResultList() .stream() .map(JobEntity::getDTO) .collect(Collectors.toSet()); }
Source:
<code>public Map<String, String> getClaimsMap() { if (claimsMap == null) { <START> return Collections.emptyMap(); <END> } return claimsMap; }</code><technical_language>This return immutable map. new HashMap<> instead</technical_language>

Target:
public Map<String, String> getClaimsMap() { return claimsMap; }
Source:
<code>public void infer_stream_types_on_chained_map() { Result result = Result.createFor("InferLambdaType"); JavaSymbol stringToBoolean = result.symbol("stringToBoolean"); assertThat(stringToBoolean.usages()).hasSize(2); assertThat(result.reference(63, 17)).isEqualTo(stringToBoolean); assertThat(result.reference(67, 17)).isEqualTo(stringToBoolean); IdentifierTree map = result.referenceTree(63, 8); MethodJavaType methodJavaType = (MethodJavaType) map.symbolType(); <START> assertThat(methodJavaType.resultType.isTagged(JavaType.DEFERRED)).isFalse(); <END> JavaSymbol booleanToInt = result.symbol("booleanToInt"); assertThat(booleanToInt.usages()).hasSize(1); assertThat(result.reference(68, 17)).isEqualTo(booleanToInt); JavaSymbol intToInt = result.symbol("intToInt"); assertThat(intToInt.usages()).hasSize(1); assertThat(result.reference(72, 20)).isEqualTo(intToInt); }</code><technical_language>a positive assertion ? testing is expected is expected</technical_language>

Target:
public void infer_stream_types_on_chained_map() { Result result = Result.createFor("InferLambdaType"); JavaSymbol stringToBoolean = result.symbol("stringToBoolean"); assertThat(stringToBoolean.usages()).hasSize(2); assertThat(result.reference(63, 17)).isEqualTo(stringToBoolean); assertThat(result.reference(67, 17)).isEqualTo(stringToBoolean); IdentifierTree map = result.referenceTree(63, 8); JavaType mapResultType = ((MethodJavaType) map.symbolType()).resultType; assertThat(mapResultType.isTagged(JavaType.DEFERRED)).isFalse(); assertThat(mapResultType.is("java.util.stream.Stream")).isTrue(); assertThat(mapResultType.isParameterized()).isTrue(); JavaType substitutionType = ((ParametrizedTypeJavaType) mapResultType).typeSubstitution.substitutedTypes().get(0); assertThat(substitutionType.is("java.lang.Boolean")).isTrue(); JavaSymbol booleanToInt = result.symbol("booleanToInt"); assertThat(booleanToInt.usages()).hasSize(1); assertThat(result.reference(68, 17)).isEqualTo(booleanToInt); JavaSymbol intToInt = result.symbol("intToInt"); assertThat(intToInt.usages()).hasSize(1); assertThat(result.reference(72, 20)).isEqualTo(intToInt); }
Source:
<code>public static void main(final String[] args) throws <START> IOException { <END> Banner.banner(); String namespace = null; int i = 0; while (i < args.length) { final String arg = args[i]; if (arg.startsWith("-")) { switch (arg) { case "-namespace": namespace = args[++i]; break; default: log.debug("Unknown argument: " + arg); usage(); break; } } else { break; } i++; } if (i >= args.length) { System.err.println("Not enough arguments."); usage(); } final String propertyFileName = args[i]; try { final Properties properties = processProperties(propertyFileName); File journal = new File(properties.getProperty(Options.FILE)); long startTime = System.currentTimeMillis(); if (journal.isFile()) { Journal jnl = new Journal(properties); AtomicLong duplicates = new AtomicLong(); try { log.info("Processing the journal: " + jnl.getFile()); if (namespace == null) { List<String> namespaces = jnl.getGlobalRowStore().getNamespaces(jnl.getLastCommitTime()); for (String nm : namespaces) { checkNamespace(jnl, nm, duplicates); } } else { checkNamespace(jnl, namespace, duplicates); } } finally { jnl.commit(); jnl.close(); log.info("Completed in " + (System.currentTimeMillis()-startTime) + ". Found " + duplicates.get() + " duplicates"); } } else { log.debug("Journal " + journal + " does not exist"); } } catch (Throwable e) { log.error("Error", e); } }</code><technical_language>IOException is thrown</technical_language>

Target:
public static void main(final String[] args) { Banner.banner(); String namespace = null; int i = 0; while (i < args.length) { final String arg = args[i]; if (arg.startsWith("-")) { switch (arg) { case "-namespace": namespace = args[++i]; break; default: log.debug("Unknown argument: " + arg); usage(); break; } } else { break; } i++; } if (i >= args.length) { System.err.println("Not enough arguments."); usage(); } final String propertyFileName = args[i]; try { final Properties properties = processProperties(propertyFileName); File journal = new File(properties.getProperty(Options.FILE)); long startTime = System.currentTimeMillis(); if (journal.isFile()) { Journal jnl = new Journal(properties); AtomicLong duplicates = new AtomicLong(); try { log.info("Processing the journal: " + jnl.getFile()); if (namespace == null) { List<String> namespaces = jnl.getGlobalRowStore().getNamespaces(jnl.getLastCommitTime()); for (String nm : namespaces) { checkNamespace(jnl, nm, duplicates); } } else { checkNamespace(jnl, namespace, duplicates); } } finally { jnl.commit(); jnl.close(); log.info("Completed in " + (System.currentTimeMillis()-startTime) + ". Found " + duplicates.get() + " duplicates"); } } else { log.debug("Journal " + journal + " does not exist"); } } catch (Throwable e) { log.error("Error", e); } }
Source:
<code>private Collection<EventClass> getEventClasses(Collection<Event> events) { <START> return transform(events, new Function<Event, EventClass>() { <END> @Override public @Nullable EventClass apply(@Nullable Event record) { if (record == null) { return null; } Message eventMessage = unpack(record.getMessage()); return EventClass.of(eventMessage); } }); }</code><technical_language>Please Stream API for transformations</technical_language>

Target:
private Collection<EventClass> getEventClasses(Collection<Event> events) { List<EventClass> result = events.stream() .map(EventClass::of) .collect(toList()); return result; }
Source:
<code>public InputRow nextRow() throws IOException { if (!hasMore()) { throw new NoSuchElementException(); } if (!parsedInputRows.isEmpty()) { <START> return parsedInputRows.remove(0); <END> } return getNextRow(); }</code><technical_language>ArrayList.remove() internally moves positions of remaining elements this happen for row in this case expensive. parsedInputRows large in general, I suggest iterator list instead of modifying list. java public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear GC do work return oldValue; }</technical_language>

Target:
public InputRow nextRow() throws IOException { if (!hasMore()) { throw new NoSuchElementException(); } if (parsedInputRows.hasNext()) { return parsedInputRows.next(); } return getNextRow(); }
Source:
<code>public void initialContentShouldEndUpInThirdBackupFileAfterThreeBackupRuns() throws IOException { <START> final int kNumberOfBackups = 3; <END> String contentOne = "Test One."; Process process = new Process(); process.setId(2); process.setProcessBaseUri(URI.create("2")); URI correctURI = URI .create(processService.getProcessDataDirectory(process).toString() + "/" + BACKUP_FILE_NAME); writeFile(correctURI, contentOne); runBackup(kNumberOfBackups, process); fileService.createResource(processService.getProcessDataDirectory(process), BACKUP_FILE_NAME); runBackup(kNumberOfBackups, process); fileService.createResource(processService.getProcessDataDirectory(process), BACKUP_FILE_NAME); runBackup(kNumberOfBackups, process); assertFileHasContent(processService.getProcessDataDirectory(process) + "/" + BACKUP_FILE_NAME + ".3", contentOne); }</code><technical_language>mentioned above: do introduce unreadable variable names</technical_language>

Target:
public void initialContentShouldEndUpInThirdBackupFileAfterThreeBackupRuns() throws IOException { final int numberOfBackups = 3; String contentOne = "Test One."; Process process = new Process(); process.setId(2); process.setProcessBaseUri(URI.create("2")); URI correctURI = URI .create(processService.getProcessDataDirectory(process).toString() + "/" + BACKUP_FILE_NAME); writeFile(correctURI, contentOne); runBackup(numberOfBackups, process); fileService.createResource(processService.getProcessDataDirectory(process), BACKUP_FILE_NAME); runBackup(numberOfBackups, process); fileService.createResource(processService.getProcessDataDirectory(process), BACKUP_FILE_NAME); runBackup(numberOfBackups, process); assertFileHasContent(processService.getProcessDataDirectory(process) + "/" + BACKUP_FILE_NAME + ".3", contentOne); }
Source:
<code>private void stopBeingLeader() { synchronized (lock) { try { leaderCounter++; log.info("I am no longer the leader..."); for (String server : loadManagementPeons.keySet()) { LoadQueuePeon peon = loadManagementPeons.remove(server); peon.stop(); } loadManagementPeons.clear(); serviceAnnouncer.unannounce(self); metadataRuleManager.stop(); metadataSegmentManager.stop(); lookupCoordinatorManager.stop(); } catch (Exception e) { log.makeAlert(e, "Unable to stopBeingLeader").emit(); } finally { <START> leader = false; <END> } } }</code><technical_language>this change is out of scope here. is a significant change in behavior if error is encountered stop calls</technical_language>

Target:
private void stopBeingLeader() { synchronized (lock) { try { leaderCounter++; log.info("I am no longer the leader..."); for (String server : loadManagementPeons.keySet()) { LoadQueuePeon peon = loadManagementPeons.remove(server); peon.stop(); } loadManagementPeons.clear(); serviceAnnouncer.unannounce(self); metadataRuleManager.stop(); metadataSegmentManager.stop(); lookupCoordinatorManager.stop(); leader = false; } catch (Exception e) { log.makeAlert(e, "Unable to stopBeingLeader").emit(); } } }
Source:
<code>protected EventsValue(final Builder builder) { this.eventId = builder.eventId; this.timestamp = new SecondTimeStamp(builder.timestamp); this.endTimestamp = new SecondTimeStamp(builder.endTimestamp); this.source = builder.source; this.title = builder.title; this.message = builder.message; this.priority = builder.priority; this.userId = builder.userId; this.ongoing = builder.ongoing; <START> this.parentId = builder.parentIds; <END> this.childId = builder.childIds; this.additionalProps = builder.additionalProps; this.namespace = builder.namespace; }</code><technical_language>Do want rename fields, too</technical_language>

Target:
protected EventsValue(final Builder builder) { this.eventId = builder.eventId; this.timestamp = new SecondTimeStamp(builder.timestamp); this.endTimestamp = new SecondTimeStamp(builder.endTimestamp); this.source = builder.source; this.title = builder.title; this.message = builder.message; this.priority = builder.priority; this.userId = builder.userId; this.ongoing = builder.ongoing; this.parentIds = builder.parentIds; this.childIds = builder.childIds; this.additionalProps = builder.additionalProps; this.namespace = builder.namespace; }
Source:
<code>protected void notifySelect() { notify(SWT.MouseEnter); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseMove); notify(SWT.MouseDown); notify(SWT.Selection); <START> notify(SWT.MouseUp); <END> notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); }</code><technical_language>I remove events</technical_language>

Target:
protected void notifySelect() { notifySelect(true); }
Source:
<code>public ModuleDefinitionResource save(@RequestParam("name") String name, @RequestParam("definition") String definition) { <START> List<ModuleDeploymentRequest> modules = this.parser.parse(name, definition); <END> ModuleType type = this.determineType(modules); ModuleDefinition moduleDefinition = new ModuleDefinition(name, type); moduleDefinition.setDefinition(definition); ModuleDefinitionResource resource = new ModuleDefinitionResourceAssembler().toResource(moduleDefinition); this.repository.save(moduleDefinition); return resource; }</code><technical_language>logic needs a deeper layer</technical_language>

Target:
public ModuleDefinitionResource save(@RequestParam("name") String name, @RequestParam("definition") String definition) { List<ModuleDeploymentRequest> modules = this.parser.parse(name, definition); ModuleType type = this.determineType(modules); ModuleDefinition moduleDefinition = new ModuleDefinition(name, type); moduleDefinition.setDefinition(definition); ModuleDefinitionResource resource = moduleDefinitionResourceAssembler.toResource(moduleDefinition); this.repository.save(moduleDefinition); return resource; }
Source:
<code>public int addFileAttachment(String path) { if (immutable) { <START> throw new UnsupportedOperationException("Attachments can't be muted"); <END> } paths.add(path); return paths.size() - 1; }</code><technical_language>s/muted/mutated</technical_language>

Target:
public int addFileAttachment(String path) { if (immutable) { throw new UnsupportedOperationException("Attachments can't be mutated"); } paths.add(path); return paths.size() - 1; }
Source:
<code>public static String metadataFieldNameToDisplayName(String metadataFieldName) { if (metadataFieldName.startsWith("characteristic")) { return characteristicFieldNameToDisplayName(metadataFieldName); } else { <START> return factorFieldNameToDisplayName(metadataFieldName); <END> } }</code><technical_language>factorFieldNameToDisplayName characteristicFieldNameToDisplayName refactored metadataFieldToDisplayName(String fieldName, String prefix) (where prefix factor_, characteristic_ empty string</technical_language>

Target:
public static String metadataFieldNameToDisplayName(String metadataFieldName) { if (metadataFieldName.startsWith("characteristic")) { return metadataFieldNameToDisplayName(metadataFieldName, "characteristic_"); } else { return metadataFieldNameToDisplayName(metadataFieldName, "factor_"); } }
Source:
<code>public void auditLoggingOnForInboundX12BatchResponseTest() { AdapterCORE_X12DSGenericBatchResponseProxyObjectFactory mockFactory = mock(AdapterCORE_X12DSGenericBatchResponseProxyObjectFactory.class); PassthroughInboundCORE_X12DSGenericBatchResponse inboundResp = new PassthroughInboundCORE_X12DSGenericBatchResponse(mockFactory, getAuditLogger(true)); AdapterCORE_X12DGenericBatchResponseProxy mockResponseProxy = mock(AdapterCORE_X12DGenericBatchResponseProxy.class); COREEnvelopeBatchSubmission request = new COREEnvelopeBatchSubmission(); COREEnvelopeBatchSubmissionResponse expectedResponse = new COREEnvelopeBatchSubmissionResponse(); AssertionType assertion = new AssertionType(); Properties webContextProperties = new Properties(); <START> when(mockFactory.getAdapterCORE_X12DocSubmissionProxy()).thenReturn(mockResponseProxy); <END> when(mockResponseProxy.batchSubmitTransaction(eq(request), eq(assertion))).thenReturn(expectedResponse); COREEnvelopeBatchSubmissionResponse actualResponse = inboundResp.batchSubmitTransaction(request, assertion, webContextProperties); assertEquals("Actual and Expected response differ", actualResponse, expectedResponse); verify(mockEJBLogger).auditResponseMessage(eq(request), eq(actualResponse), eq(assertion), isNull(NhinTargetSystemType.class), eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_NHIN_INTERFACE), eq(Boolean.FALSE), eq(webContextProperties), eq(NhincConstants.CORE_X12DS_GENERICBATCH_RESPONSE_SERVICE_NAME), any(COREX12BatchSubmissionAuditTransforms.class)); }</code><technical_language>variables final for methods</technical_language>

Target:
public void auditLoggingOnForInboundX12BatchResponseTest() { PassthroughInboundCORE_X12DSGenericBatchResponse inboundResp = new PassthroughInboundCORE_X12DSGenericBatchResponse(mockFactory, getAuditLogger(true)); COREEnvelopeBatchSubmissionResponse expectedResponse = new COREEnvelopeBatchSubmissionResponse(); when(mockFactory.getAdapterCORE_X12DocSubmissionProxy()).thenReturn(mockResponseProxy); when(mockResponseProxy.batchSubmitTransaction(eq(request), eq(assertion))).thenReturn(expectedResponse); COREEnvelopeBatchSubmissionResponse actualResponse = inboundResp.batchSubmitTransaction(request, assertion, webContextProperties); assertEquals("Actual and Expected response differ", actualResponse, expectedResponse); verify(mockEJBLogger).auditResponseMessage(eq(request), eq(actualResponse), eq(assertion), isNull(NhinTargetSystemType.class), eq(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION), eq(NhincConstants.AUDIT_LOG_NHIN_INTERFACE), eq(Boolean.FALSE), eq(webContextProperties), eq(NhincConstants.CORE_X12DS_GENERICBATCH_RESPONSE_SERVICE_NAME), any(COREX12BatchSubmissionAuditTransforms.class)); }
Source:
<code>protected DistStageAck run() { if (queries.isEmpty()) { log.info("No queries have been specified"); return successfulResponse(); } MulticastSocket socket = null; try { socket = new MulticastSocket(); socket.setSoTimeout((int) timeout); InetAddress targetAddress = InetAddress.getByName(address); byte[] payload = getQuery().getBytes(); DatagramPacket packet = new DatagramPacket(payload, 0, payload.length, targetAddress, port); socket.send(packet); if (expectedResponseCount == -1) { return successfulResponse(); } <START> long start = System.currentTimeMillis(); <END> int received = 0; while (received < expectedResponseCount) { if (start + timeout < System.currentTimeMillis()) { String errorMessage = "Timed out waiting for query responses"; log.error(errorMessage); return errorResponse(errorMessage); } byte[] buffer = new byte[1024 * 64]; DatagramPacket result = new DatagramPacket(buffer, buffer.length); socket.receive(result); received++; if (printResultsAsInfo) { log.infof("Received response %s from %s:%d", new String(result.getData(), 0, result.getLength()), result.getAddress(), result.getPort()); } else { log.tracef("Received response %s from %s:%d", new String(result.getData(), 0, result.getLength()), result.getAddress(), result.getPort()); } } } catch (IOException e) { String errorMessage = "Exception while performing multicast socket operation. Make sure 'enable_diagnostics' property of TP is enabled " + "and correct diagnostics port is specified"; log.error(errorMessage, e); return errorResponse(errorMessage, e); } finally { if (socket != null) { socket.close(); } } return successfulResponse(); }</code><technical_language>TimeService</technical_language>

Target:
protected String[] run() throws IOException { String[] datagramPacketsResponse = null; if (!queries.isEmpty() && expectedResponseCount > 0) { datagramPacketsResponse = new String[expectedResponseCount]; MulticastSocket socket = null; try { socket = new MulticastSocket(); socket.setSoTimeout((int) timeout); InetAddress targetAddress = InetAddress.getByName(address); byte[] payload = getQuery().getBytes(); DatagramPacket packet = new DatagramPacket(payload, 0, payload.length, targetAddress, port); socket.send(packet); long start = TimeService.currentTimeMillis(); int received = 0; while (received < expectedResponseCount) { if (start + timeout < TimeService.currentTimeMillis()) { String errorMessage = "Timed out waiting for query responses"; throw new IOException(errorMessage); } byte[] buffer = new byte[1024 * 64]; DatagramPacket result = new DatagramPacket(buffer, buffer.length); socket.receive(result); datagramPacketsResponse[received++] = String.format("Received response %s from %s:%d", new String(result.getData(), 0, result.getLength()), result.getAddress(), result.getPort()); } } catch (IOException e) { String errorMessage = "Exception while performing multicast socket operation. Make sure 'enable_diagnostics' property of TP is enabled " + "and correct diagnostics port is specified"; throw new IOException(errorMessage, e); } finally { if (socket != null) { socket.close(); } } } return datagramPacketsResponse != null ? datagramPacketsResponse : EMPTY_RESPONSE; }
Source:
<code>public void testGetNotificationTypesForAdminUser() { <START> final int expectedCount = 8; <END> SecurityContextHolder.getContext().setAuthentication(adminUser); Set<NotificationType> results = searchMenuManager.getNotificationTypes(); assertNotNull(results); assertEquals(expectedCount, results.size()); for (NotificationType nt : results) { assertNotNull(nt.getId()); assertNotNull(nt.getName()); assertNotNull(nt.getDescription()); assertNotNull(nt.getRequiresAcb()); } }</code><technical_language>I this 1. notification types questionable activity right</technical_language>

Target:
public void testGetNotificationTypesForAdminUser() { final int expectedCount = 1; SecurityContextHolder.getContext().setAuthentication(adminUser); Set<NotificationType> results = searchMenuManager.getNotificationTypes(); assertNotNull(results); assertEquals(expectedCount, results.size()); for (NotificationType nt : results) { assertNotNull(nt.getId()); assertNotNull(nt.getName()); assertNotNull(nt.getDescription()); assertNotNull(nt.getRequiresAcb()); } }
Source:
<code>private static XmlElement findFpmlRoot(XmlElement root) { <START> XmlElement fpmlRoot = isFpmlRoot(root); <END> if (fpmlRoot != null) { return fpmlRoot; } for (XmlElement el : root.getChildren()) { fpmlRoot = isFpmlRoot(el); if (fpmlRoot != null) { return fpmlRoot; } } for (XmlElement el1 : root.getChildren()) { for (XmlElement el2 : el1.getChildren()) { fpmlRoot = isFpmlRoot(el2); if (fpmlRoot != null) { return fpmlRoot; } } } throw new FpmlParseException("Unable to find FpML root element"); }</code><technical_language>isFpmlRoot() return a boolean anymore, is worth renaming more appropriate, getFpmlRoot()</technical_language>

Target:
private static XmlElement findFpmlRoot(XmlElement root) { XmlElement fpmlRoot = getFpmlRoot(root); if (fpmlRoot != null) { return fpmlRoot; } for (XmlElement el : root.getChildren()) { fpmlRoot = getFpmlRoot(el); if (fpmlRoot != null) { return fpmlRoot; } } for (XmlElement el1 : root.getChildren()) { for (XmlElement el2 : el1.getChildren()) { fpmlRoot = getFpmlRoot(el2); if (fpmlRoot != null) { return fpmlRoot; } } } throw new FpmlParseException("Unable to find FpML root element"); }
Source:
<code>public String getPartitionField() { <START> return partitionField; <END> }</code><technical_language>Do need separate getter for partitionField? partitionField a public access modifier</technical_language>

Target:
public String getPartitionField() { return Strings.isNullOrEmpty(partitionField) ? null : partitionField; }
Source:
<code>public void testMassIndexing() throws Exception { <START> boolean indexEnabled = getConfigBuilder().build().indexing().isEnabled(); <END> RestServerHelper helper = restServers.get(0); int port = helper.getPort(); String clearIndexURL = String.format("http://localhost:%d/rest/v2/caches/%s/search/indexes?action=clear", port, CACHE_NAME); String massIndexURL = String.format("http://localhost:%d/rest/v2/caches/%s/search/indexes?action=mass-index", port, CACHE_NAME); Request massIndexRequest = client.newRequest(massIndexURL); Request clearIndexRequest = client.newRequest(clearIndexURL); ContentResponse clearResponse = clearIndexRequest.send(); assertEquals(clearResponse.getStatus(), indexEnabled ? OK_200 : BAD_REQUEST_400); if (indexEnabled) eventually(() -> getCount() == 0); ContentResponse massIndexResponse = massIndexRequest.send(); assertEquals(massIndexResponse.getStatus(), indexEnabled ? OK_200 : BAD_REQUEST_400); eventually(() -> getCount() == ENTRIES); }</code><technical_language>This other occurrences of this happen enabled getter in IndexingConfigurationBuilder is package local. public void build()</technical_language>

Target:
public void testMassIndexing() throws Exception { boolean indexEnabled = getConfigBuilder().indexing().enabled(); RestServerHelper helper = restServers.get(0); int port = helper.getPort(); String clearIndexURL = String.format("http://localhost:%d/rest/v2/caches/%s/search/indexes?action=clear", port, CACHE_NAME); String massIndexURL = String.format("http://localhost:%d/rest/v2/caches/%s/search/indexes?action=mass-index", port, CACHE_NAME); Request massIndexRequest = client.newRequest(massIndexURL); Request clearIndexRequest = client.newRequest(clearIndexURL); ContentResponse clearResponse = clearIndexRequest.send(); assertEquals(clearResponse.getStatus(), indexEnabled ? OK_200 : BAD_REQUEST_400); if (indexEnabled) eventually(() -> getCount() == 0); ContentResponse massIndexResponse = massIndexRequest.send(); assertEquals(massIndexResponse.getStatus(), indexEnabled ? OK_200 : BAD_REQUEST_400); eventually(() -> getCount() == ENTRIES); }
Source:
<code>protected void execute(Context context) throws SQLException { MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("SELECT id FROM quality_gates WHERE name = ?") .setString(1, SONARQUBE_WAY_QUALITY_GATE); <START> massUpdate.rowPluralName("quality_gates"); <END> massUpdate.update("UPDATE quality_gates SET name=?, is_built_in=?, updated_at=? WHERE id=?"); massUpdate.execute((row, update) -> { update.setString(1, findNewQualityGateName(context)); update.setBoolean(2, false); update.setDate(3, new Date(system2.now())); update.setLong(4, row.getLong(1)); return true; }); }</code><technical_language>"quality_gates" => "quality gates" is displayed in log for user</technical_language>

Target:
protected void execute(Context context) throws SQLException { MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("SELECT id FROM quality_gates WHERE name = ?") .setString(1, SONARQUBE_WAY_QUALITY_GATE); massUpdate.rowPluralName("quality gates"); massUpdate.update("UPDATE quality_gates SET name=?, is_built_in=?, updated_at=? WHERE id=?"); massUpdate.execute((row, update) -> { update.setString(1, findNewQualityGateName(context)); update.setBoolean(2, false); update.setDate(3, new Date(system2.now())); update.setLong(4, row.getLong(1)); return true; }); }
Source:
<code>public void addPlayer(EntityPlayerMP player) { if (player.world != this.getWorldServer()) { CubicChunks.bigWarning("Player world not the same ad PlayerCubeMap world! Adding anyway. This is very likely to cause issues! Player " + "world dimension ID: %d, PlayerCubeMap dimension ID: %d", player.world.provider.getDimension(), getWorldServer().provider.getDimension()); } else if (!player.world.playerEntities.contains(player)) { CubicChunks.LOGGER.debug("PlayerCubeMap (dimension {}): Adding player to pending to add list", getWorldServer().provider.getDimension()); pendingPlayerAdd.add(player); return; } PlayerWrapper playerWrapper = new PlayerWrapper(player); playerWrapper.updateManagedPos(); if (!vanillaNetworkHandler.hasCubicChunks(player)) { vanillaNetworkHandler.updatePlayerPosition(this, player, playerWrapper.getManagedCubePos(), -1); } <START> <END> CubePos playerCubePos = CubePos.fromEntity(player); this.cubeSelector.forAllVisibleFrom(playerCubePos, horizontalViewDistance, verticalViewDistance, (currentPos) -> { ColumnWatcher chunkWatcher = getOrCreateColumnWatcher(currentPos.chunkPos()); if (!chunkWatcher.containsPlayer(player)) { chunkWatcher.addPlayer(player); } CubeWatcher cubeWatcher = getOrCreateCubeWatcher(currentPos); cubeWatcher.addPlayer(player); }); this.players.put(player.getEntityId(), playerWrapper); this.setNeedSort(); }</code><technical_language>move this code below</technical_language>

Target:
public void addPlayer(EntityPlayerMP player) { if (player.world != this.getWorldServer()) { CubicChunks.bigWarning("Player world not the same ad PlayerCubeMap world! Adding anyway. This is very likely to cause issues! Player " + "world dimension ID: %d, PlayerCubeMap dimension ID: %d", player.world.provider.getDimension(), getWorldServer().provider.getDimension()); } else if (!player.world.playerEntities.contains(player)) { CubicChunks.LOGGER.debug("PlayerCubeMap (dimension {}): Adding player to pending to add list", getWorldServer().provider.getDimension()); pendingPlayerAdd.add(player); return; } PlayerWrapper playerWrapper = new PlayerWrapper(player); playerWrapper.updateManagedPos(); if (!vanillaNetworkHandler.hasCubicChunks(player)) { vanillaNetworkHandler.updatePlayerPosition(this, player, playerWrapper.getManagedCubePos()); } CubePos playerCubePos = CubePos.fromEntity(player); this.cubeSelector.forAllVisibleFrom(playerCubePos, horizontalViewDistance, verticalViewDistance, (currentPos) -> { ColumnWatcher chunkWatcher = getOrCreateColumnWatcher(currentPos.chunkPos()); if (!chunkWatcher.containsPlayer(player)) { chunkWatcher.addPlayer(player); } CubeWatcher cubeWatcher = getOrCreateCubeWatcher(currentPos); cubeWatcher.addPlayer(player); }); this.players.put(player.getEntityId(), playerWrapper); this.setNeedSort(); }