auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public Result isUTF16(byte[] buffer, boolean failOnNull) { <END> if (buffer.length < 2) { return Result.newInvalid(); } int beAscii = 0; int beLines = 0; int leAscii = 0; int leLines = 0; for (int i = 0; i < buffer.length / 2; i++) { byte c1 = buffer[i * 2]; byte c2 = buffer[i * 2 + 1]; if (c1 == 0) { if (c2 != 0) { if (c2 == 0x0a || c2 == 0x0d) { beLines++; } beAscii++; } else if (failOnNull) { return Result.newInvalid(); } } else if (c2 == 0) { leAscii++; if (c1 == 0x0a || c1 == 0x0d) { leLines++; } } } float beAsciiPerc = beAscii * 2.0f / (float) buffer.length; float leAsciiPerc = leAscii * 2.0f / (float) buffer.length; if (leLines == 0) { if (beAsciiPerc >= UTF_16_NULL_PASS_THRESHOLD && leAsciiPerc < UTF_16_NULL_FAIL_THRESHOLD) { return Result.newValid(StandardCharsets.UTF_16BE); } if (beLines > 0) { return Result.newValid(StandardCharsets.UTF_16BE); } } else if (beLines > 0) { return Result.newInvalid(); } if (beLines == 0) { if (leAsciiPerc >= UTF_16_NULL_PASS_THRESHOLD && beAsciiPerc < UTF_16_NULL_FAIL_THRESHOLD) { return Result.newValid(StandardCharsets.UTF_16LE); } if (leLines > 0) { return Result.newValid(StandardCharsets.UTF_16LE); } } return new Result(Valid.MAYBE, null); }</code><technical_language>![CRITICAL](<LINK_0> 'Severity: CRITICAL') Refactor this method reduce Cognitive Complexity 31 15 allowed. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Result isUTF16(byte[] buffer, boolean failOnNull) { if (buffer.length < 2) { return Result.INVALID; } int beAscii = 0; int beLines = 0; int leAscii = 0; int leLines = 0; for (int i = 0; i < buffer.length / 2; i++) { byte c1 = buffer[i * 2]; byte c2 = buffer[i * 2 + 1]; if (c1 == 0) { if (c2 != 0) { if (c2 == 0x0a || c2 == 0x0d) { beLines++; } beAscii++; } else if (failOnNull) { return Result.INVALID; } } else if (c2 == 0) { leAscii++; if (c1 == 0x0a || c1 == 0x0d) { leLines++; } } } float beAsciiPerc = beAscii * 2.0f / (float) buffer.length; float leAsciiPerc = leAscii * 2.0f / (float) buffer.length; if (leLines == 0) { if (beAsciiPerc >= UTF_16_NULL_PASS_THRESHOLD && leAsciiPerc < UTF_16_NULL_FAIL_THRESHOLD) { return Result.newValid(StandardCharsets.UTF_16BE); } if (beLines > 0) { return Result.newValid(StandardCharsets.UTF_16BE); } } else if (beLines > 0) { return Result.INVALID; } if (beLines == 0) { if (leAsciiPerc >= UTF_16_NULL_PASS_THRESHOLD && beAsciiPerc < UTF_16_NULL_FAIL_THRESHOLD) { return Result.newValid(StandardCharsets.UTF_16LE); } if (leLines > 0) { return Result.newValid(StandardCharsets.UTF_16LE); } } return new Result(Validation.MAYBE, null); }
Source:
<code>public boolean engineIsKeyEntry(String alias) { Attributes attributes = obtainAliasOrCertificateAttributes(alias, null, new String[]{keyAttribute}); Attribute attribute = attributes == null ? null : LdapUtil.getBinaryAttribute(attributes, keyAttribute); if (attribute == null) { log.tracef("Alias [%s] is not key entry", alias); <START> return engineIsCertificateEntry(alias); END> } try { byte[] bytes = (byte[]) attribute.get(); return bytes != null; } catch (NamingException e) { throw log.ldapKeyStoreFailedToObtainKey(alias, e); } }</code><technical_language>This valid - if is impossible retrieve key, isKeyEntry() return true? Truststores JKS file contains certificates only, key. I dont TrustManager require claim certificates a key..</technical_language>

Target:
public boolean engineIsKeyEntry(String alias) { Attributes attributes = obtainAliasOrCertificateAttributes(alias, null, new String[]{keyAttribute}); Attribute attribute = attributes == null ? null : LdapUtil.getBinaryAttribute(attributes, keyAttribute); if (attribute == null) { log.tracef("Alias [%s] is not key entry", alias); return false; } try { byte[] bytes = (byte[]) attribute.get(); return bytes != null; } catch (NamingException e) { throw log.ldapKeyStoreFailedToObtainKey(alias, e); } }
Source:
<code>public Chain get(long key) { Lock lock = getLock(key).readLock(); try { <START> lock.lock(); <END> Chain chain = map.get(key); if (chain != null) { return chain; } else { return new HeapChainImpl(); } } finally { lock.unlock(); } }</code><technical_language>harmless j.u.c.l.ReentrantReadWriteLock pattern is wrong: lock out of try - catch block</technical_language>

Target:
public Chain get(long key) { Lock lock = getLock(key).readLock(); lock.lock(); try { Chain chain = map.get(key); if (chain != null) { return chain; } else { return new HeapChainImpl(); } } finally { lock.unlock(); } }
Source:
<code>public void onItemUse(PlayerInteractEvent.RightClickBlock event) { EntityPlayer player = event.getEntityPlayer(); World world = player.worldObj; if (Game.isClient(world)) return; ItemStack itemStack = event.getItemStack(); if (itemStack != null) { Item item = itemStack.getItem(); if (item != null && CartTools.vanillaCartItemMap.containsKey(item)) { event.setUseItem(Event.Result.DENY); EntityMinecart placedCart = CartTools.placeCart( CartTools.vanillaCartItemMap.get(item), player.getGameProfile(), itemStack, world, event.getPos()); if (placedCart != null && !player.capabilities.isCreativeMode) <START> dec(itemStack); <END> } } }</code><technical_language>is a null check start of this section</technical_language>

Target:
public void onItemUse(PlayerInteractEvent.RightClickBlock event) { EntityPlayer player = event.getEntityPlayer(); World world = player.worldObj; if (Game.isClient(world)) return; ItemStack itemStack = event.getItemStack(); if (!isEmpty(itemStack)) { Item item = itemStack.getItem(); if (CartTools.vanillaCartItemMap.containsKey(item)) { event.setUseItem(Event.Result.DENY); EntityMinecart placedCart = CartTools.placeCart( CartTools.vanillaCartItemMap.get(item), player.getGameProfile(), itemStack, world, event.getPos()); if (placedCart != null && !player.capabilities.isCreativeMode) dec(itemStack); } } }
Source:
<code><START> void testResetReadBufferManager() { <END> synchronized (this) { ArrayList<ReadBuffer> completedBuffers = new ArrayList<>(); for (ReadBuffer buf : completedReadList) { if (buf != null) { completedBuffers.add(buf); } } for (ReadBuffer buf : completedBuffers) { evict(buf); } readAheadQueue.clear(); inProgressList.clear(); completedReadList.clear(); freeList.clear(); buffers = new byte[NUM_BUFFERS][]; for (int i = 0; i < NUM_BUFFERS; i++) { buffers[i] = null; } buffers = null; resetBufferManager(); } }</code><technical_language>please add some reasoning/docs changes. Thanks</technical_language>

Target:
void testResetReadBufferManager() { synchronized (this) { ArrayList<ReadBuffer> completedBuffers = new ArrayList<>(); for (ReadBuffer buf : completedReadList) { if (buf != null) { completedBuffers.add(buf); } } for (ReadBuffer buf : completedBuffers) { evict(buf); } readAheadQueue.clear(); inProgressList.clear(); completedReadList.clear(); freeList.clear(); for (int i = 0; i < NUM_BUFFERS; i++) { buffers[i] = null; } buffers = null; resetBufferManager(); } }
Source:
<code>public void registerMBean(Object mbean, ObjectName objectName) throws JMException { try { mbeanServer.registerMBean(mbean, objectName); } catch (final InstanceAlreadyExistsException ex) { if (registrationBehaviour == REGISTRATION_IGNORE_EXISTING) { <START> if (log.isDebugEnabled()) { <END> log.debug("Ignoring existing MBean at [{}]", objectName); } } else if (registrationBehaviour == REGISTRATION_REPLACE_EXISTING) { try { if (log.isDebugEnabled()) { log.debug("Replacing existing MBean at [{}]", objectName); } mbeanServer.unregisterMBean(objectName); mbeanServer.registerMBean(mbean, objectName); } catch (final InstanceNotFoundException ex2) { log.error("Unable to replace existing MBean at [" + objectName + "]", ex2); throw ex; } } else { throw ex; } } }</code><technical_language>This line longer necessary log.debug do check (<LINK_0></technical_language>

Target:
public void registerMBean(Object mbean, ObjectName objectName) throws JMException { try { mbeanServer.registerMBean(mbean, objectName); } catch (final InstanceAlreadyExistsException ex) { if (registrationBehaviour == REGISTRATION_IGNORE_EXISTING) { log.debug("Ignoring existing MBean at [{}]", objectName); } else if (registrationBehaviour == REGISTRATION_REPLACE_EXISTING) { try { log.debug("Replacing existing MBean at [{}]", objectName); mbeanServer.unregisterMBean(objectName); mbeanServer.registerMBean(mbean, objectName); } catch (final InstanceNotFoundException ex2) { log.error("Unable to replace existing MBean at [" + objectName + "]", ex2); throw ex; } } else { throw ex; } } }
Source:
<code>private static Options createCommandLineOptions() { Options options = new Options(); options.addOption( builder(HELP_OPTION) .longOpt("help") .desc("Print the usage of the script") .hasArg(false) .build() ); options.addOption( builder(SLEEP_OPTION) .longOpt("sleep") <START> .desc("Sleep a certain time between each solr request") <END> .hasArg(true) .build() ); options.addOption( builder(BATCH_SIZE_OPTION) .longOpt("batch") .desc("The amount of Solr records to be processed per batch (defaults to 100)") .hasArg(true) .build() ); options.addOption( builder(THREADS_OPTION) .longOpt("threads") .desc("The amount of threads used by the script (defaults to 2") .hasArg(true) .build() ); return options; }</code><technical_language>suggestion: rephrase "Sleep a time **given in milliseconds** solr request"</technical_language>

Target:
private static Options createCommandLineOptions() { Options options = new Options(); options.addOption( builder(HELP_OPTION) .longOpt("help") .desc("Print the usage of the script") .hasArg(false) .build() ); options.addOption( builder(SLEEP_OPTION) .longOpt("sleep") .desc("Sleep a certain time given in milliseconds between each solr request") .hasArg(true) .build() ); options.addOption( builder(BATCH_SIZE_OPTION) .longOpt("batch") .desc("The amount of Solr records to be processed per batch (defaults to 100)") .hasArg(true) .build() ); options.addOption( builder(THREADS_OPTION) .longOpt("threads") .desc("The amount of threads used by the script (defaults to 2") .hasArg(true) .build() ); return options; }
Source:
<code>public Builder snapshotFilter(Predicate<? super DomainEventData<?>> snapshotFilter) { <START> snapshotFilter(snapshotFilter::test); <END> return this; }</code><technical_language>assertNonNull before, it</technical_language>

Target:
public Builder snapshotFilter(Predicate<? super DomainEventData<?>> snapshotFilter) { return snapshotFilter(snapshotFilter::test); }
Source:
<code>public void init(FilterConfig filterConfig) throws ServletException { LOGGER.debug("Starting CSRF filter."); protectedContexts = new ArrayList<>(); protectedContexts.add(JOLOKIA_CONTEXT); protectedContexts.add(INTRIGUE_CONTEXT); protectedContexts.add(WEBSOCKET_CONTEXT); <START> String internalHostname = System.getProperty("org.codice.ddf.system.hostname"); <END> String internalHttpPort = System.getProperty("org.codice.ddf.system.httpPort"); String internalHttpsPort = System.getProperty("org.codice.ddf.system.httpsPort"); String externalHostname = System.getProperty("org.codice.ddf.external.hostname"); String externalHttpPort = System.getProperty("org.codice.ddf.external.httpPort"); String externalHttpsPort = System.getProperty("org.codice.ddf.external.httpsPort"); trustedAuthorities = new ArrayList<>(); trustedAuthorities.add(internalHostname + ":" + internalHttpPort); trustedAuthorities.add(internalHostname + ":" + internalHttpsPort); trustedAuthorities.add(externalHostname + ":" + externalHttpPort); trustedAuthorities.add(externalHostname + ":" + externalHttpsPort); if (internalHttpPort.equals("80") || internalHttpsPort.equals("443")) { trustedAuthorities.add(internalHostname); } if (externalHttpPort.equals("80") || externalHttpsPort.equals("443")) { trustedAuthorities.add(externalHostname); } }</code><technical_language>SystemBaseUrl getters instead of property literals? prevents typos if need refactor of is *much* easier catch</technical_language>

Target:
public void init(FilterConfig filterConfig) throws ServletException { LOGGER.debug("Starting CSRF filter."); protectedContexts = new ArrayList<>(); protectedContexts.add(JOLOKIA_CONTEXT); protectedContexts.add(INTRIGUE_CONTEXT); protectedContexts.add(WEBSOCKET_CONTEXT); String internalHostname = SystemBaseUrl.INTERNAL.getHost(); String internalHttpPort = SystemBaseUrl.INTERNAL.getHttpPort(); String internalHttpsPort = SystemBaseUrl.INTERNAL.getHttpsPort(); String externalHostname = SystemBaseUrl.EXTERNAL.getHost(); String externalHttpPort = SystemBaseUrl.EXTERNAL.getHttpPort(); String externalHttpsPort = SystemBaseUrl.EXTERNAL.getHttpsPort(); trustedAuthorities = new ArrayList<>(); trustedAuthorities.add(internalHostname + ":" + internalHttpPort); trustedAuthorities.add(internalHostname + ":" + internalHttpsPort); trustedAuthorities.add(externalHostname + ":" + externalHttpPort); trustedAuthorities.add(externalHostname + ":" + externalHttpsPort); }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitForStatement(@NotNull GoForStatement o) { super.visitForStatement(o); GoBlock forBlock = o.getBlock(); GoRangeClause forRangeClause = o.getRangeClause(); GoForClause forClause = o.getForClause(); <START> if (o.getExpression() != null || <END> forBlock == null || (forRangeClause != null && !forRangeClause.getExpressionList().isEmpty()) || (forClause != null && !forClause.getStatementList().isEmpty()) || !forBlock.getStatementList().isEmpty()) { return; } holder.registerProblem(o, "Infinite for loop", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new GoReplaceWithSelectStatementQuickFix(o)); } }; }</code><technical_language>please invert condition. this is strange consider loops infinite _except_ o.getExpression() != null block == nul ..</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitForStatement(@NotNull GoForStatement o) { super.visitForStatement(o); if (o.getExpression() == null && !hasBlock(o.getBlock()) && !hasRangeClause(o.getRangeClause()) && !hasClause(o.getForClause())) { holder.registerProblem(o, "Infinite for loop", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new GoReplaceWithSelectStatementQuickFix()); } } }; }
Source:
<code>public ViewExtensionDescription getDefaultRules(ResourceSet resourceSet) { <START> Resource resource = resourceSet.getResource(DEFAULT_RULES_RESOURCE_URI, true); if (resource == null) { <END> SiriusPropertiesCorePlugin.getPlugin().error(Messages.DefaultRulesProvider_DefaultPropertiesNotFound); } else { Optional<Group> optionalGroup = resource.getContents().stream().filter(Group.class::isInstance).map(Group.class::cast).findFirst(); Optional<ViewExtensionDescription> viewExtensionDescription = optionalGroup.flatMap(group -> { return group.getExtensions().stream().filter(ViewExtensionDescription.class::isInstance).map(ViewExtensionDescription.class::cast).findFirst(); }); return viewExtensionDescription.orElse(null); } return null; }</code><technical_language>java8-isation [optional]</technical_language>

Target:
public ViewExtensionDescription getDefaultRules(ResourceSet resourceSet) { Optional<Resource> resource = Optional.ofNullable(resourceSet.getResource(DEFAULT_RULES_RESOURCE_URI, true)); if (!resource.isPresent()) { SiriusPropertiesCorePlugin.getPlugin().error(Messages.DefaultRulesProvider_DefaultPropertiesNotFound); } return resource.map(r -> r.getContents()).filter(Group.class::isInstance).map(Group.class::cast).map(group -> group.getExtensions()).filter(ViewExtensionDescription.class::isInstance) .map(ViewExtensionDescription.class::cast).orElse(null); }
Source:
<code>public void changed() { super.changed(); <START> if (!ConfServer.localPollingEnabled || !MassiveCoreMConf.get().warnOnLocalAlter) return; <END> this.lastStackTraceChanged = MUtil.getStackTrace(); }</code><technical_language>Duplicate source code? If check for this configuration multiple times, break out a common method for it</technical_language>

Target:
public void changed() { super.changed(); if (!MStore.isLocalPollingDebugEnabled() || !MassiveCoreMConf.get().advancedLocalPollingDebug) return; this.lastStackTraceChanged = MUtil.getStackTrace(); }
Source:
<code>public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Log.d(TAG, "got new message: " + remoteMessage.getData()); CountlyPush.Message message = CountlyPush.decodeMessage(remoteMessage.getData()); Intent notificationIntent = null; if (!message.has("c.l")) { notificationIntent = new Intent(this, MainActivity.class); notificationIntent.putExtra(MainActivity.NOTIFICATION_DIALOG, "yes"); notificationIntent.putExtra("title", "title"); <START> notificationIntent.putExtra("message", "message"); <END> } Boolean result = CountlyPush.displayMessage(getApplicationContext(), message, R.drawable.notification_icon, notificationIntent); if (result == null) { Log.d(TAG, "Message wasn't sent from Countly server, so it cannot be handled by Countly SDK"); } else if (result) { Log.d(TAG, "Message was handled by Countly SDK"); } else { Log.d(TAG, "Message wasn't handled by Countly SDK because API level is too low for Notification support or because currentActivity is null (not enough lifecycle method calls)"); } }</code><technical_language>Is is intended passing "message" a string a opposed message object</technical_language>

Target:
public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Log.d(TAG, "got new message: " + remoteMessage.getData()); CountlyPush.Message message = CountlyPush.decodeMessage(remoteMessage.getData()); Intent notificationIntent = null; if (!message.has("c.l")) { notificationIntent = new Intent(this, MainActivity.class); notificationIntent.putExtra(MainActivity.NOTIFICATION_DIALOG, "yes"); notificationIntent.putExtra("title", message.title()); notificationIntent.putExtra("message", message.message()); } Boolean result = CountlyPush.displayMessage(getApplicationContext(), message, R.drawable.notification_icon, notificationIntent); if (result == null) { Log.d(TAG, "Message wasn't sent from Countly server, so it cannot be handled by Countly SDK"); } else if (result) { Log.d(TAG, "Message was handled by Countly SDK"); } else { Log.d(TAG, "Message wasn't handled by Countly SDK because API level is too low for Notification support or because currentActivity is null (not enough lifecycle method calls)"); } }
Source:
<code>public List getRulesetFilenames() { try { <START> return Files.walk(Paths.get(ConfigCore.getParameter("RegelsaetzeVerzeichnis"))) <END> .filter(f -> f.toString().endsWith(".xml")) .map(Path::getFileName) .sorted() .collect(Collectors.toList()); } catch (IOException e) { Helper.setErrorMessage("errorLoadingMany", new Object[] {Helper.getTranslation("rulesets")}, logger, e); return new ArrayList(); } }</code><technical_language>Please adjust configuration parameter in #1623</technical_language>

Target:
public List getRulesetFilenames() { try { return Files.walk(Paths.get(ConfigCore.getParameter(Parameters.DIR_RULESETS))) .filter(f -> f.toString().endsWith(".xml")) .map(Path::getFileName) .sorted() .collect(Collectors.toList()); } catch (IOException e) { Helper.setErrorMessage("errorLoadingMany", new Object[] {Helper.getTranslation("rulesets")}, logger, e); return new ArrayList(); } }
Source:
<code>public void pushSubjectToConference(final Conversation conference, final String subject) { MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject); this.sendMessagePacket(conference.getAccount(), packet); final MucOptions mucOptions = conference.getMucOptions(); final MucOptions.User self = mucOptions.getSelf(); if (self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) { Bundle options = new Bundle(); <START> if (!mucOptions.persistent()) { <END> options.putString("muc#roomconfig_persistentroom", "1"); } options.putString("muc#roomconfig_roomname", subject); this.pushConferenceConfiguration(conference, options, null); } }</code><technical_language>remove condition instead set muc#roomconfig_persistentroom 1. room is persistent persistent is setting 1 a difference</technical_language>

Target:
public void pushSubjectToConference(final Conversation conference, final String subject) { MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject); this.sendMessagePacket(conference.getAccount(), packet); final MucOptions mucOptions = conference.getMucOptions(); final MucOptions.User self = mucOptions.getSelf(); if (self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) { Bundle options = new Bundle(); options.putString("muc#roomconfig_persistentroom", "1"); options.putString("muc#roomconfig_roomname", subject); this.pushConferenceConfiguration(conference, options, null); } }
Source:
<code>protected Channel setupChannel(Connection connection) throws Exception { Channel chan = connection.createChannel(); if (rmqConnectionConfig.getPrefetchCount().isPresent()) { <START> chan.basicQos(rmqConnectionConfig.getPrefetchCount().get()); <END> } return chan; }</code><technical_language>Hemm ... absolutely right i a basic setup independent brokers duplicate deduplicate clients. life interesting, global flag RabbitMQ older v3.3.0 bring connection. :rofl: experimenting is ! do need a helping hand ? i spare a couple of hours next weekend if need help</technical_language>

Target:
private Channel setupChannel(Connection connection) throws Exception { Channel chan = connection.createChannel(); if (rmqConnectionConfig.getPrefetchCount().isPresent()) { chan.basicQos(rmqConnectionConfig.getPrefetchCount().get(), true); } return chan; }
Source:
<code>public String getFullyQualifiedSignature() { if (!this.isConstructorCall() && !this.isMethodCall()) { return null; } Package classPackage = this.declaringType.getPackage(); String packageName = (classPackage == null) ? null : classPackage.getName(); String classname = this.getDeclaringType().getRawtype().getUnqualifiedName(); String name = this.getUnqualifiedName().equals("<init>") ? classname : this.getUnqualifiedName(); Iterator<Type> inputTypeIterator = inputTypes.iterator(); List<String> typeNames = new ArrayList<>(); for (int i = 0; inputTypeIterator.hasNext(); i++) { String typeName = inputTypeIterator.next().getName(); if (!isStatic() && i == 0) { <START> System.out.println("Skipped "); <END> continue; } typeNames.add(typeName); } return ((packageName == null) ? "" : packageName + ".") + (classname.equals(name) ? name : classname + "." + name) + "(" + UtilPlume.join(typeNames, ",") + ")"; }</code><technical_language>Is this diagnostic code accidentally left in</technical_language>

Target:
public String getFullyQualifiedSignature() { if (!this.isConstructorCall() && !this.isMethodCall()) { return null; } Package classPackage = this.declaringType.getPackage(); String packageName = (classPackage == null) ? null : classPackage.getName(); String classname = this.getDeclaringType().getRawtype().getUnqualifiedName(); String name = this.getUnqualifiedName().equals("<init>") ? classname : this.getUnqualifiedName(); Iterator<Type> inputTypeIterator = inputTypes.iterator(); List<String> typeNames = new ArrayList<>(); for (int i = 0; inputTypeIterator.hasNext(); i++) { String typeName = inputTypeIterator.next().getName(); if (!isStatic() && i == 0) { continue; } typeNames.add(typeName); } return ((packageName == null) ? "" : packageName + ".") + (classname.equals(name) ? name : classname + "." + name) + "(" + UtilPlume.join(typeNames, ",") + ")"; }
Source:
<code>public String getIconFileName() { <START> if (Jenkins.get().hasPermission(Jenkins.MANAGE) || Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) <END> return "gear2.png"; else return null; }</code><technical_language>instead add 2 new methods AccessControlled hasAnyPermission(Permission... permission) / checkAnyPermission(Permission ... permission)? <LINK_0> more elegant</technical_language>

Target:
public String getIconFileName() { if (Jenkins.get().hasAnyPermission(Jenkins.MANAGE, Jenkins.SYSTEM_READ)) return "gear2.png"; else return null; }
Source:
<code>private static void assertGetResult(VmTemplate result) { assertNotNull(result); assertEquals(EXISTING_TEMPLATE_ID, result.getId()); <START> assertTrue("Template generation wasn't loaded as expected", result.getDbGeneration() == 1); <END> }</code><technical_language>Wait, this is worse previous version. happened assertEquals()? [it supports primitives, name suggest]</technical_language>

Target:
private static void assertGetResult(VmTemplate result) { assertNotNull(result); assertEquals(EXISTING_TEMPLATE_ID, result.getId()); assertEquals("Template generation wasn't loaded as expected", 1, result.getDbGeneration()); }
Source:
<code>public static Map<String, Object> getVideoDeviceSpecParams(VmBase vmBase) { Map<String, Object> specParams = new HashMap<>(); getVideoDeviceParams(vmBase).forEach((k, v) -> specParams.put(k, String.valueOf(v))); return specParams; <START> } <END></code><technical_language>streams: return getVideoDeviceParams(vmBase).entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> String.valueof(e.getValue()))</technical_language>

Target:
public static Map<String, Object> getVideoDeviceSpecParams(VmBase vmBase) { return getVideoDeviceRAMSettings(vmBase).entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))); }
Source:
<code>public void use(SquareContainer square) { if (direction == null) throw new IllegalStateException( "The disk cannot be used when there is no direction set!"); <START> currentSquare = (SquareContainer) square; END> if (!canMoveDisk(direction)) currentSquare.addItem(this); else while (canMoveDisk(direction)) { moveDisk(direction); if (currentSquare.hasPlayer()) { currentSquare.getPlayer().asExplodable().skipNumberOfActions(3); break; } } direction = null; currentSquare = null; }</code><technical_language>wrong? cast is unnecessary. Also, created a setSquare(), ;)</technical_language>

Target:
public void use(SquareContainer square) { if (direction == null) throw new IllegalStateException( "The disk cannot be used when there is no direction set!"); setSquare(square); if (!canMoveDisk(direction)) currentSquare.addItem(this); else while (canMoveDisk(direction)) { moveDisk(direction); if (currentSquare.hasPlayer()) { currentSquare.getPlayer().asExplodable().skipNumberOfActions(3); break; } } direction = null; currentSquare = null; }
Source:
<code>public static String[] basePackages(SimpleModuleDefinition moduleDefinition, ClassLoader moduleClassLoader) { Resource propertiesFile = ModuleUtils.locateModuleResource(moduleDefinition, moduleClassLoader, ".properties"); if (propertiesFile == null) { <START> return new String[0]; <END> } Properties properties = new Properties(); try { properties.load(propertiesFile.getInputStream()); } catch (IOException e) { throw new RuntimeException(String.format("Unable to read module properties for %s:%s", moduleDefinition.getName(), moduleDefinition.getType()), e); } String basePackageNames = properties.getProperty(BASE_PACKAGES); return StringUtils.commaDelimitedListToStringArray(basePackageNames); }</code><technical_language>implementation of scan() downstream, fail fast: java /** * Perform a scan base packages. * <p>Note {@link #refresh()} called in order for context * fully process new classes. * @param basePackages packages check for annotated classes * @see #register(Class...) * @see #refresh() */ public void scan(String... basePackages) { Assert.notEmpty(basePackages, "At base package specified"); this.scanner.scan(basePackages); }</technical_language>

Target:
public static String[] basePackages(SimpleModuleDefinition moduleDefinition, ClassLoader moduleClassLoader) { Resource propertiesFile = ModuleUtils.modulePropertiesFile(moduleDefinition, moduleClassLoader); if (propertiesFile == null) { return new String[0]; } Properties properties = new Properties(); try { properties.load(propertiesFile.getInputStream()); } catch (IOException e) { throw new RuntimeException(String.format("Unable to read module properties for %s:%s", moduleDefinition.getName(), moduleDefinition.getType()), e); } String basePackageNames = properties.getProperty(BASE_PACKAGES); return StringUtils.commaDelimitedListToStringArray(basePackageNames); }
Source:
<code>public List<CloudBlobMetadata> findEntriesSince(String partitionPath, CloudFindToken findToken, long maxTotalSizeOfEntries) { List<CloudBlobMetadata> entries = new LinkedList<>(); for (BlobId blobId : map.keySet()) { if (map.get(blobId).getFirst().getLastUpdateTime() >= findToken.getLastUpdateTime()) { if (findToken.getLastUpdateTimeReadBlobIds().contains(map.get(blobId).getFirst().getId())) { continue; } entries.add(map.get(blobId).getFirst()); } } Collections.sort(entries, (CloudBlobMetadata o1, CloudBlobMetadata o2) -> { if (o1.getLastUpdateTime() == o2.getLastUpdateTime()) { return 0; } <START> return o1.getLastUpdateTime() > o2.getLastUpdateTime() ? 1 : -1; <END> }); long totalSize = 0; List<CloudBlobMetadata> results = new ArrayList<>(); for (CloudBlobMetadata metadata : entries) { if (totalSize + metadata.getSize() > maxTotalSizeOfEntries) { if (results.size() == 0) { results.add(metadata); } break; } results.add(metadata); totalSize += metadata.getSize(); } return results; }</code><technical_language>a comparator lambda do this in line</technical_language>

Target:
public List<CloudBlobMetadata> findEntriesSince(String partitionPath, CloudFindToken findToken, long maxTotalSizeOfEntries) { List<CloudBlobMetadata> entries = new LinkedList<>(); for (BlobId blobId : map.keySet()) { if (map.get(blobId).getFirst().getLastUpdateTime() >= findToken.getLastUpdateTime()) { if (findToken.getLastUpdateTimeReadBlobIds().contains(map.get(blobId).getFirst().getId())) { continue; } entries.add(map.get(blobId).getFirst()); } } Collections.sort(entries, Comparator.comparingLong(CloudBlobMetadata::getLastUpdateTime)); return CloudBlobMetadata.capMetadataListBySize(entries, maxTotalSizeOfEntries); }
Source:
<code>@Test public void dataset_09() { Dataset ds = createDataset(); <START> assertTrue("Named default graph not found", ds.containsNamedModel(Quad.defaultGraphIRI.getURI())); <END> }</code><technical_language>This message a confusing (Named default graph), maybe: Default graph URI ( "+Quad.defaultGraphIRI.getURI()+" )" is verbose, clear</technical_language>

Target:
@Test public void dataset_09() { Dataset ds = createDataset(); assertTrue("Default graph not found using '<"+Quad.defaultGraphIRI.getURI()+">'", ds.containsNamedModel(Quad.defaultGraphIRI.getURI())); }
Source:
<code>public Object setRuntimePropertyValue(String propertyName, Object newValue) { if ("comPort".equalsIgnoreCase(propertyName)) { final Object oldValue = propComPort; propComPort = newValue.toString(); return oldValue; } if ("baudRate".equalsIgnoreCase(propertyName)) { final Object oldValue = propBaudRate; propBaudRate = Integer.parseInt(newValue.toString()); return oldValue; } if ("sendStringTerminator".equalsIgnoreCase(propertyName)) { final Object oldValue = propSendStringTerminator; propSendStringTerminator = Integer.parseInt(newValue.toString()); return oldValue; } if ("receiveStringTerminator".equalsIgnoreCase(propertyName)) { final Object oldValue = propReceiveStringTerminator; propReceiveStringTerminator = Integer.parseInt(newValue.toString()); return oldValue; } if ("sendBytesBufferSize".equalsIgnoreCase(propertyName)) { final Object oldValue = propSendBytesBufferSize; propSendBytesBufferSize = Integer.parseInt(newValue.toString()); sendBytesBuffer=ByteBuffer.allocate(propSendBytesBufferSize); return oldValue; } if ("cimId".equalsIgnoreCase(propertyName)) { final Object oldValue = propCimId; if(newValue != null) { <START> String s = newValue.toString().trim(); <END> if (s.startsWith("0x")) { s = s.substring(2); try { propCimId = (short) Integer.parseInt(s, 16); } catch (NumberFormatException e) { logger.warning("could not format cimId, value is: " + s); } } } return oldValue; } return null; }</code><technical_language>I forgot: trimming, converted uppercase, support mixed versions of lowercase uppercase hex strings</technical_language>

Target:
public Object setRuntimePropertyValue(String propertyName, Object newValue) { if ("comPort".equalsIgnoreCase(propertyName)) { final Object oldValue = propComPort; propComPort = newValue.toString(); return oldValue; } if ("baudRate".equalsIgnoreCase(propertyName)) { final Object oldValue = propBaudRate; propBaudRate = Integer.parseInt(newValue.toString()); return oldValue; } if ("sendStringTerminator".equalsIgnoreCase(propertyName)) { final Object oldValue = propSendStringTerminator; propSendStringTerminator = Integer.parseInt(newValue.toString()); return oldValue; } if ("receiveStringTerminator".equalsIgnoreCase(propertyName)) { final Object oldValue = propReceiveStringTerminator; propReceiveStringTerminator = Integer.parseInt(newValue.toString()); return oldValue; } if ("sendBytesBufferSize".equalsIgnoreCase(propertyName)) { final Object oldValue = propSendBytesBufferSize; propSendBytesBufferSize = Integer.parseInt(newValue.toString()); sendBytesBuffer=ByteBuffer.allocate(propSendBytesBufferSize); return oldValue; } if ("cimId".equalsIgnoreCase(propertyName)) { final Object oldValue = propCimId; if(newValue != null) { String s = newValue.toString().trim().toLowerCase(); if (s.startsWith("0x")) { s = s.substring(2); try { propCimId = (short) Integer.parseInt(s, 16); } catch (NumberFormatException e) { logger.warning("could not format cimId, value is: " + s); } } } return oldValue; } return null; }
Source:
<code><START> DataOperation(final Optional<String> origEvalId, final String operationId, final DataOpType operationType, <END> final String dataType, final List<LongRange> dataKeyRanges, final Optional<SortedMap<Long, T>> dataKeyValueMap) { this.origEvalId = origEvalId; this.operationId = operationId; this.operationType = operationType; this.dataType = dataType; this.dataKeyRanges = Collections.unmodifiableList(dataKeyRanges); if (dataKeyValueMap.isPresent()) { this.dataKeyValueMap = Optional.of(Collections.unmodifiableSortedMap(dataKeyValueMap.get())); } else { this.dataKeyValueMap = dataKeyValueMap; } }</code><technical_language>I this constructor is general one; others call this constructor instead of setting members in individual constructors</technical_language>

Target:
DataOperation(final Optional<String> origEvalId, final String operationId, final DataOpType operationType, final String dataType, final List<LongRange> dataKeyRanges, final Optional<SortedMap<Long, T>> dataKeyValueMap) { this.origEvalId = origEvalId; this.operationId = operationId; this.operationType = operationType; this.dataType = dataType; this.dataKeyRanges = dataKeyRanges; this.dataKeyValueMap = dataKeyValueMap; }
Source:
<code>abstract protected IDynamicDistributionTemplate initTemplate(DynamicPluginAdapter pluginAdapter, IDynamicMonitor monitor) throws Exception; @Override <START> public void unregist(IDynamicPlugin dynamicPlugin, IDynamicMonitor monitor) throws Exception { <END> IDynamicPluginConfiguration pluginConfiguration = dynamicPlugin.getPluginConfiguration(); String id = pluginConfiguration.getId(); DynamicPluginAdapter registedPluginAdapter = registedPluginMap.get(id); if (registedPluginAdapter != null) { DynamicServiceUtil.removeContribution(registedPluginAdapter.getPlugin()); registedPluginMap.remove(id); } ServiceRegistration registedOsgiService = registedOsgiServiceMap.get(id); if (registedOsgiService != null) { DynamicServiceUtil.unregistOSGiService(registedOsgiService); registedOsgiServiceMap.remove(id); } }</code><technical_language>is this supposed register</technical_language>

Target:
abstract protected IDynamicDistributionTemplate initTemplate(DynamicPluginAdapter pluginAdapter, IDynamicMonitor monitor) throws Exception; @Override public void unregister(IDynamicPlugin dynamicPlugin, IDynamicMonitor monitor) throws Exception { IDynamicPluginConfiguration pluginConfiguration = dynamicPlugin.getPluginConfiguration(); String id = pluginConfiguration.getId(); DynamicPluginAdapter registedPluginAdapter = registedPluginMap.get(id); if (registedPluginAdapter != null) { DynamicServiceUtil.removeContribution(registedPluginAdapter.getPlugin()); registedPluginMap.remove(id); } ServiceRegistration registedOsgiService = registedOsgiServiceMap.get(id); if (registedOsgiService != null) { DynamicServiceUtil.unregistOSGiService(registedOsgiService); registedOsgiServiceMap.remove(id); } }
Source:
<code>public static Set set(String field, Date date){ <START> return set(field, ClientConstants.getDateFormat().format(date)); <END> }</code><technical_language>Insted, set(field,Literal.value(date))</technical_language>

Target:
public static Set set(String field, Date date){ return new Set().more(field, Literal.value(date)); }
Source:
<code>public void testDifferentThresholdsForMinLogSizeToCompact() throws StoreException { int[] minLogSizeToTriggerCompactionInPercentages = new int[]{60, 61, 65, 70, 80, 95}; for (int minLogSize : minLogSizeToTriggerCompactionInPercentages) { properties.setProperty("store.min.log.size.to.trigger.compaction.in.percent", String.valueOf(minLogSize)); StoreConfig config = new StoreConfig(new VerifiableProperties(properties)); MetricRegistry metricRegistry = new MetricRegistry(); StorageManagerMetrics metrics = new StorageManagerMetrics(metricRegistry); blobStore = new MockBlobStore("", config, null, null, metrics, null, 0, null, null, null, time); blobStore.capacityInBytes = CAPACITY_IN_BYTES; <START> blobStore.start(); <END> compactionManager = new CompactionManager(config); blobStore.usedCapacity = CAPACITY_IN_BYTES * 6 / 10; blobStore.validLogSegments = generateRandomString(2); verifyCompactionDetails(null); } minLogSizeToTriggerCompactionInPercentages = new int[]{10, 20, 35, 40, 50, 59}; for (int minLogSize : minLogSizeToTriggerCompactionInPercentages) { properties.setProperty("store.min.log.size.to.trigger.compaction.in.percent", String.valueOf(minLogSize)); StoreConfig config = new StoreConfig(new VerifiableProperties(properties)); MetricRegistry metricRegistry = new MetricRegistry(); StorageManagerMetrics metrics = new StorageManagerMetrics(metricRegistry); blobStore = new MockBlobStore("", config, null, null, metrics, null, 0, null, null, null, time); blobStore.capacityInBytes = CAPACITY_IN_BYTES; blobStore.start(); compactionManager = new CompactionManager(config); blobStore.usedCapacity = CAPACITY_IN_BYTES * 6 / 10; blobStore.validLogSegments = generateRandomString(2); verifyCompactionDetails(new CompactionDetails(blobStore.getTime().milliseconds() - messageRetentionTimeInMs, blobStore.validLogSegments)); } }</code><technical_language>start calls required mocking BlobStore, right</technical_language>

Target:
public void testDifferentThresholdsForMinLogSizeToCompact() throws StoreException { int[] minLogSizeToTriggerCompactionInPercentages = new int[]{10, 20, 35, 40, 50, 59, 60, 61, 65, 70, 80, 95}; for (int minLogSize : minLogSizeToTriggerCompactionInPercentages) { properties.setProperty("store.min.log.size.to.trigger.compaction.in.percent", String.valueOf(minLogSize)); config = new StoreConfig(new VerifiableProperties(properties)); MetricRegistry metricRegistry = new MetricRegistry(); StorageManagerMetrics metrics = new StorageManagerMetrics(metricRegistry); blobStore = new MockBlobStore(config, metrics, time, CAPACITY_IN_BYTES, DEFAULT_USED_CAPACITY_IN_BYTES); compactionManager = new CompactionManager(config, time); blobStore.validLogSegments = generateRandomStrings(2); if (blobStore.usedCapacity < (config.storeMinUsedCapacityToTriggerCompactionInPercentage / 100.0 * blobStore.capacityInBytes)) { verifyCompactionDetails(null); } else { verifyCompactionDetails( new CompactionDetails(time.milliseconds() - messageRetentionTimeInMs, blobStore.validLogSegments)); } } }
Source:
<code>public void anonCanLogInViaUserLoginPage() { WikiBasePageObject base = new WikiBasePageObject(); base.openSpecialUpload(wikiURL); base.verifyLoginRequiredMessage(); <START> base.clickLoginOnSpecialPage(); <END> new AttachedSignInPage().login(credentials.userName10, credentials.password10); base.verifyUserLoggedIn(credentials.userName10); Assertion.assertTrue(base.isStringInURL(URLsContent.SPECIAL_UPLOAD)); }</code><technical_language>Create a ticket refactor this? WikiBasePageObject base = new WikiBasePageObject(); base.openSpecialUpload(wikiURL); base.verifyLoginRequiredMessage(); base.clickLoginOnSpecialPage();</technical_language>

Target:
public void anonCanLogInViaUserLoginPage() { WikiBasePageObject base = new WikiBasePageObject(); base.openSpecialUpload(wikiURL); base.verifyLoginRequiredMessage(); base.clickLoginOnSpecialPage(); new AttachedSignInPage().login(credentials.userName10, credentials.password10); base.verifyUserLoggedIn(credentials.userName10); assertTrue(base.isStringInURL(URLsContent.SPECIAL_UPLOAD)); }
Source:
<code>private String getCachedImgTag(int id){ if(!GUIPreferences.getInstance().getBoolean(GUIPreferences.ADVANCED_ROUND_REPORT_SPRITES) <START> || imgCache == null || !imgCache.containsKey(id)) { <END> return null; } return imgCache.get(id); }</code><technical_language>suggestion || (imgCache == null) || !imgCache.containsKey(id)) {</technical_language>

Target:
private String getCachedImgTag(int id){ if (!GUIPreferences.getInstance().getBoolean(GUIPreferences.ADVANCED_ROUND_REPORT_SPRITES) || (imgCache == null) || !imgCache.containsKey(id)) { return null; } return imgCache.get(id); }
Source:
<code>private void forcedLoadAlbums(){ Account account = userManager.getActiveAccount().getValue(); if (albumsSubscription != null) { albumsSubscription.unsubscribe(); albumsSubscription = null; } if (photosSubscription != null) { photosSubscription.unsubscribe(); photosSubscription = null; } if (account != null) { <START> albumsSubscription = categoriesRepository.getCategories(account, category, preferencesRepository.getStringPreference(PreferencesRepository.KEY_PREF_THUMBNAIL_SIZE, "medium")) <END> .subscribe(new CategoriesSubscriber()); photosSubscription = imageRepository.getImages(account, category) .subscribe(new ImagesSubscriber()); } }</code><technical_language>refactor getStringPreference getString, query a preference is obvious preferenceRepository... preferenceRepository preferences (which a type PreferenceRepository)</technical_language>

Target:
private void forcedLoadAlbums(){ Account account = userManager.getActiveAccount().getValue(); if (albumsSubscription != null) { albumsSubscription.unsubscribe(); albumsSubscription = null; } if (photosSubscription != null) { photosSubscription.unsubscribe(); photosSubscription = null; } if (account != null) { albumsSubscription = categoriesRepository.getCategories(account, category, preferences.getString(PreferencesRepository.KEY_PREF_DOWNLOAD_SIZE)) .subscribe(new CategoriesSubscriber()); photosSubscription = imageRepository.getImages(account, category) .subscribe(new ImagesSubscriber()); } }
Source:
<code>public Client(InetSocketAddress address){ nwc.startListeningOnAnyAvailablePort(); nwc.addPeer(address); send(new ConnectEvent(isSpectator())); playerId = -1; <START> timer = new SimulationTimer(); <END> timer.addListener(this); timer.start(); }</code><technical_language>Move SimulationTimer GameController, add a protected final method add a listener</technical_language>

Target:
public Client(InetSocketAddress address){ nwc.startListeningOnAnyAvailablePort(); nwc.addPeer(address); send(new ConnectEvent(isSpectator())); playerId = -1; }
Source:
<code>public void editDefaultAuthenticationContext() throws Exception { final Address authenticationContextAddress = createAuthenticationContext(); final SnapshotBackup snapshotBackup = new SnapshotBackup(); <START> client.apply(snapshotBackup.backup()); <END> try { page.navigate(); new ConfigChecker.Builder(client, ElytronOperations.getElytronSubsystemAddress()) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.TEXT, DEFAULT_AUTHENTICATION_CONTEXT, authenticationContextAddress.getLastPairValue()) .verifyFormSaved() .verifyAttribute(DEFAULT_AUTHENTICATION_CONTEXT, authenticationContextAddress.getLastPairValue()); } finally { client.apply(snapshotBackup.restore()); } }</code><technical_language>moving snapshot backup/restore logic Before/After methods? developing integration tests I want run tests in parallel IMHO some state (model snapshot) of test methods. @rhatlapa WDYT</technical_language>

Target:
public void editDefaultAuthenticationContext() throws Exception { final Address authenticationContextAddress = createAuthenticationContext(); try { elytronAuthenticationOperations.performActionOnAttributeAndRevertItsValueToOriginal( ElytronOperations.getElytronSubsystemAddress(), DEFAULT_AUTHENTICATION_CONTEXT, () -> { page.navigate(); new ConfigChecker.Builder(client, ElytronOperations.getElytronSubsystemAddress()) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.TEXT, DEFAULT_AUTHENTICATION_CONTEXT, authenticationContextAddress.getLastPairValue()) .verifyFormSaved() .verifyAttribute(DEFAULT_AUTHENTICATION_CONTEXT, authenticationContextAddress.getLastPairValue()); } ); } finally { ops.removeIfExists(authenticationContextAddress); } }
Source:
<code>public ImmutableSet<ColumnName> columnNames() { <START> return ImmutableSet.copyOf(storageFields.keySet()); <END> }</code><technical_language>Assuming, storageFields immutable, keys immutable too</technical_language>

Target:
public final ImmutableSet<ColumnName> columnNames() { return ImmutableSet.copyOf(storageFields.keySet()); }
Source:
<code>private CRPluggableScmMaterial pluggableScmMaterialConfigToCRPluggableScmMaterial(PluggableSCMMaterialConfig pluggableScmMaterialConfig) { SCMs scms = getSCMs(); String id = pluggableScmMaterialConfig.getScmId(); SCM scmConfig = scms.find(id); if (scmConfig == null) throw new ConfigConvertionException( String.format("Failed to find referenced scm '%s'", id)); return new CRPluggableScmMaterial(pluggableScmMaterialConfig.getName().toString(), id, pluggableScmMaterialConfig.getFolder(), <START> pluggableScmMaterialConfig.getFilterAsString()); <END> }</code><technical_language>getFilterAsString problem mentioned elsewhere</technical_language>

Target:
private CRPluggableScmMaterial pluggableScmMaterialConfigToCRPluggableScmMaterial(PluggableSCMMaterialConfig pluggableScmMaterialConfig) { SCMs scms = getSCMs(); String id = pluggableScmMaterialConfig.getScmId(); SCM scmConfig = scms.find(id); if (scmConfig == null) throw new ConfigConvertionException( String.format("Failed to find referenced scm '%s'", id)); return new CRPluggableScmMaterial(pluggableScmMaterialConfig.getName().toString(), id, pluggableScmMaterialConfig.getFolder(), pluggableScmMaterialConfig.filter().ignoredFileNames()); }