auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void execute(List<String> args, PrintStream out) { ISarosSession session = sessionManager.getSession(); if (session == null) { log.error("No Session running, cannot add any resources"); return; } try { <START> args.stream() <END> .map(path -> new ServerProjectImpl(this.workspace, path)) .forEach(project -> session.addSharedResources(project, project.getName(), null)); for (User user : session.getRemoteUsers()) { sessionManager.startSharingProjects(user.getJID()); } } catch (Exception e) { log.error("Error sharing resources", e); } }</code><technical_language>This is a good case ask question if lambdas all. 1. line 47 normal iterator for:each, lambda ? 2. Is intention do for (arg : args) pl.add(new XYZ(arg)) for (p : pl) someFunction(pl) for (arg : args) someFunction(new XYZ(arg)) I asking lets assume want issue argument affect other arguments write: for (arg : args) try {someFunction(new XYZ(arg))}catch(...){} I right write 2 catch blocks lambdas ? arg.stream().map(x -> try{...}catch(...){}).forEach(x -> try{...}catch(...){}))</technical_language>

Target:
public void execute(List<String> args, PrintStream out) { ISarosSession session = sessionManager.getSession(); if (session == null) { log.error("No Session running, cannot add any resources"); return; } try { Map<IProject, List<IResource>> projects = new HashMap<>(); for (String path : args) { try { IProject project = new ServerProjectImpl(this.workspace, path); projects.put(project, null); } catch (Exception e) { log.error(path + " could not be added to the session", e); } } sessionManager.addResourcesToSession(projects); } catch (Exception e) { log.error("Error sharing resources", e); } }
Source:
<code>public static List<FormOption> getLanguages() { final List<FormOption> languages = new ArrayList<>(); for (String languageCode : Locale.getISOLanguages()) { try { final String languageName = getLanguageNameFromCode(languageCode); <START> if (Character.isUpperCase(languageName.charAt(0)) && languageName.length() > 3) { <END> languages.add(new FormOption(languageName, languageCode)); } } catch (InvalidLocaleException e) { e.printStackTrace(); } } return languages; }</code><technical_language>need mention some ref need skip some of languages</technical_language>

Target:
public static List<FormOption> getLanguages() { final List<FormOption> languages = new ArrayList<>(); for (String languageCode : Locale.getISOLanguages()) { try { final String languageName = getLanguageNameFromCode(languageCode); if (!languageCode.equals(languageName) && !languageCode.equals("zxx")) { languages.add(new FormOption(languageName, languageCode)); } } catch (InvalidLocaleException e) { e.printStackTrace(); } } sortBasedOnLocale(languages); return languages; }
Source:
<code>public <T> DefaultSerializationProviderConfiguration addSerializerFor(Class<T> serializableClass, Class<? extends Serializer<T>> serializerClass) { if (serializableClass == null) { throw new NullPointerException("Serializable class cannot be null"); } if (serializerClass == null) { throw new NullPointerException("Serializer class cannot be null"); <START> } <END> String alias = serializableClass.getName(); Constructor<? extends Serializer<T>> transientConstructor = null; Constructor<? extends Serializer<T>> persistentConstructor = null; try { transientConstructor = serializerClass.getConstructor(ClassLoader.class); if (transientSerializers.containsKey(alias)) { throw new IllegalArgumentException("Duplicate transient serializer for class : " + alias); } else { transientSerializers.put(alias, serializerClass); } } catch (NoSuchMethodException e) { } try { persistentConstructor = serializerClass.getConstructor(ClassLoader.class, FileBasedPersistenceContext.class); if (persistentSerializers.containsKey(alias)) { throw new IllegalArgumentException("Duplicate persistent serializer for class : " + alias); } else { persistentSerializers.put(alias, serializerClass); } } catch (NoSuchMethodException e) { } if(transientConstructor == null && persistentConstructor == null) { throw new IllegalArgumentException("The serializer: " + serializerClass.getName() + " does not meet the constructor requirements for either transient or persistent caches."); } return this; }</code><technical_language>This set of changes simpler if extracted isConstructorPresent(...) method do exception handling</technical_language>

Target:
public <T> DefaultSerializationProviderConfiguration addSerializerFor(Class<T> serializableClass, Class<? extends Serializer<T>> serializerClass) { if (serializableClass == null) { throw new NullPointerException("Serializable class cannot be null"); } if (serializerClass == null) { throw new NullPointerException("Serializer class cannot be null"); } String alias = serializableClass.getName(); boolean transientConstructorPresent = false; boolean persistentConstructorPresent = false; if(transientConstructorPresent = isConstructorPresent(serializerClass, ClassLoader.class)) { if (transientSerializers.containsKey(alias)) { throw new IllegalArgumentException("Duplicate transient serializer for class : " + alias); } else { transientSerializers.put(alias, serializerClass); } } if(persistentConstructorPresent = isConstructorPresent(serializerClass, ClassLoader.class, FileBasedPersistenceContext.class)) { if (persistentSerializers.containsKey(alias)) { throw new IllegalArgumentException("Duplicate persistent serializer for class : " + alias); } else { persistentSerializers.put(alias, serializerClass); } } if(!transientConstructorPresent && !persistentConstructorPresent) { throw new IllegalArgumentException("The serializer: " + serializerClass.getName() + " does not meet the constructor requirements for either transient or persistent caches."); } return this; }
Source:
<code>private Builder(Cursor cursor) throws Exception { mId = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_ID)); mJobClass = (Class<? extends Job>) Class.forName(cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_JOB_CLASS))); mStartMs = cursor.getLong(cursor.getColumnIndex(JobStorage.COLUMN_START_MS)); mEndMs = cursor.getLong(cursor.getColumnIndex(JobStorage.COLUMN_END_MS)); mBackoffMs = cursor.getLong(cursor.getColumnIndex(JobStorage.COLUMN_BACKOFF_MS)); mBackoffPolicy = BackoffPolicy.valueOf(cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_BACKOFF_POLICY))); mIntervalMs = cursor.getLong(cursor.getColumnIndex(JobStorage.COLUMN_INTERVAL_MS)); mRequirementsEnforced = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_REQUIREMENTS_ENFORCED)) > 0; mRequiresCharging = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_REQUIRES_CHARGING)) > 0; mRequiresDeviceIdle = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_REQUIRES_DEVICE_IDLE)) > 0; mExact = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_EXACT)) > 0; mNetworkType = NetworkType.valueOf(cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_NETWORK_TYPE))); String xml = cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_EXTRAS)); if (!TextUtils.isEmpty(xml)) { <START> mExtras = PersistableBundleCompat.fromXml(xml); <END> } mPersisted = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_PERSISTED)) > 0; mTag = cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_TAG)); }</code><technical_language>lazy initialize this if need parsing xml</technical_language>

Target:
private Builder(Cursor cursor) throws Exception { mId = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_ID)); mJobClass = (Class<? extends Job>) Class.forName(cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_JOB_CLASS))); mStartMs = cursor.getLong(cursor.getColumnIndex(JobStorage.COLUMN_START_MS)); mEndMs = cursor.getLong(cursor.getColumnIndex(JobStorage.COLUMN_END_MS)); mBackoffMs = cursor.getLong(cursor.getColumnIndex(JobStorage.COLUMN_BACKOFF_MS)); mBackoffPolicy = BackoffPolicy.valueOf(cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_BACKOFF_POLICY))); mIntervalMs = cursor.getLong(cursor.getColumnIndex(JobStorage.COLUMN_INTERVAL_MS)); mRequirementsEnforced = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_REQUIREMENTS_ENFORCED)) > 0; mRequiresCharging = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_REQUIRES_CHARGING)) > 0; mRequiresDeviceIdle = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_REQUIRES_DEVICE_IDLE)) > 0; mExact = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_EXACT)) > 0; mNetworkType = NetworkType.valueOf(cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_NETWORK_TYPE))); mExtrasXml = cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_EXTRAS)); mPersisted = cursor.getInt(cursor.getColumnIndex(JobStorage.COLUMN_PERSISTED)) > 0; mTag = cursor.getString(cursor.getColumnIndex(JobStorage.COLUMN_TAG)); }
Source:
<code>private <R> GridClientFutureAdapter<R> makeAuthRequest() throws GridClientConnectionResetException { TcpClientFuture<R> fut = new TcpClientFuture<>(); fut.retryState(TcpClientFuture.STATE_REQUEST_RETRY); <START> GridClientAuthenticationRequest req = buildAuthRequest(); pendingReqs.putIfAbsent(req.requestId(), fut); GridNioFuture<?> sndFut = ses.send(req); try { sndFut.get(); } catch (Exception e) { throw new GridClientConnectionResetException("Failed to send message over connection " + "(will try to reconnect): " + serverAddress(), e); } return fut; <END> }</code><technical_language>Duplication of makeRequest, please reuse makeRequest instead</technical_language>

Target:
private <R> GridClientFutureAdapter<R> makeAuthRequest() throws GridClientConnectionResetException, GridClientClosedException { TcpClientFuture<R> fut = new TcpClientFuture<>(); fut.retryState(TcpClientFuture.STATE_REQUEST_RETRY); GridClientAuthenticationRequest req = buildAuthRequest(); return makeRequest(req, fut, false); }
Source:
<code>protected void finalize() throws Throwable { if( isOpen ) { System.err.println( "WARNING: Neo4j Session object leaked, please ensure that your application calls the `close` method on Sessions before disposing of the objects." ); if( currentTransaction != null ) { connection.forceClose(); } else { connection.close(); } } <START> } <END></code><technical_language>Finalizers run concurrently other methods object, in a thread. want isOpen field volatile ensure write in close is visible finalizer thread</technical_language>

Target:
protected void finalize() throws Throwable { if( isOpen ) { logger.error( "Neo4j Session object leaked, please ensure that your application calls the `close` " + "method on Sessions before disposing of the objects.", null ); connection.close(); } }
Source:
<code>protected boolean matchesSafely(Column item) { <START> if (!qualifier.matches(item.getQualifier())) <END> return false; if (item.getCellsCount() != cells.size()) return false; for (int i = 0; i < cells.size(); ++i) { if (!cells.get(i).matches(item.getCells(i))) { return false; } } return true; }</code><technical_language>Please add curly braces if statement bodies</technical_language>

Target:
protected boolean matchesSafely(Column item) { if (!qualifier.matches(item.getQualifier())) { return false; } if (item.getCellsCount() != cells.size()) { return false; } for (int i = 0; i < cells.size(); ++i) { if (!cells.get(i).matches(item.getCells(i))) { return false; } } return true; }
Source:
<code>protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) { List<EurekaEndpoint> candidateHosts = null; int endpointIdx = 0; for (int retry = 0; retry < numberOfRetries; retry++) { EurekaHttpClient currentHttpClient = delegate.get(); EurekaEndpoint currentEndpoint = null; if (currentHttpClient == null) { if (candidateHosts == null) { candidateHosts = getHostCandidates(); if (candidateHosts.isEmpty()) { throw new TransportException("There is no known eureka server; cluster server list is empty"); } } if (endpointIdx >= candidateHosts.size()) { throw new TransportException("Cannot execute request on any known server"); } currentEndpoint = candidateHosts.get(endpointIdx++); currentHttpClient = clientFactory.newClient(currentEndpoint); } try { EurekaHttpResponse<R> response = requestExecutor.execute(currentHttpClient); if (serverStatusEvaluator.accept(response.getStatusCode(), requestExecutor.getRequestType())) { delegate.set(currentHttpClient); if (retry > 0) { logger.info("Request execution succeeded on retry #{}", retry); } return response; } logger.warn("Request execution failure with status code {}; retrying on another server if available", response.getStatusCode()); } catch (Exception e) { <START> logger.warn("Request execution failured with message: {}", e.getMessage()); END> } delegate.compareAndSet(currentHttpClient, null); if (currentEndpoint != null) { quarantineSet.add(currentEndpoint); } } throw new TransportException("Retry limit reached; giving up on completing the request"); }</code><technical_language>failed</technical_language>

Target:
protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) { List<EurekaEndpoint> candidateHosts = null; int endpointIdx = 0; for (int retry = 0; retry < numberOfRetries; retry++) { EurekaHttpClient currentHttpClient = delegate.get(); EurekaEndpoint currentEndpoint = null; if (currentHttpClient == null) { if (candidateHosts == null) { candidateHosts = getHostCandidates(); if (candidateHosts.isEmpty()) { throw new TransportException("There is no known eureka server; cluster server list is empty"); } } if (endpointIdx >= candidateHosts.size()) { throw new TransportException("Cannot execute request on any known server"); } currentEndpoint = candidateHosts.get(endpointIdx++); currentHttpClient = clientFactory.newClient(currentEndpoint); } try { EurekaHttpResponse<R> response = requestExecutor.execute(currentHttpClient); if (serverStatusEvaluator.accept(response.getStatusCode(), requestExecutor.getRequestType())) { delegate.set(currentHttpClient); if (retry > 0) { logger.info("Request execution succeeded on retry #{}", retry); } return response; } logger.warn("Request execution failure with status code {}; retrying on another server if available", response.getStatusCode()); } catch (Exception e) { logger.warn("Request execution failed with message: {}", e.getMessage()); } delegate.compareAndSet(currentHttpClient, null); if (currentEndpoint != null) { quarantineSet.add(currentEndpoint); } } throw new TransportException("Retry limit reached; giving up on completing the request"); }
Source:
<code>public void shouldNotParseUUID() throws Exception { SurefireMasterProcessChannelProcessorFactory factory = new SurefireMasterProcessChannelProcessorFactory(); UUID uuid = UUID.randomUUID(); <START> URI uri = new URI( "tcp://127.0.0.1:12345?xxx=" + uuid ); <END> UUID parsed = invokeMethod( factory, "parseAuth", uri ); assertThat( parsed ) .isNull(); }</code><technical_language>IP address here</technical_language>

Target:
public void shouldNotParseUUID() throws Exception { UUID uuid = UUID.randomUUID(); URI uri = new URI( "tcp://localhost:12345?xxx=" + uuid ); String parsed = invokeMethod( SurefireMasterProcessChannelProcessorFactory.class, "extractSessionId", uri ); assertThat( parsed ) .isNull(); }
Source:
<code>public void connect() throws Exception { super.connect(); if (vdsClient != null) { String hostfp = getHostFingerprint(); if (!vdsClient.getSSHKeyFingerprint().equals(hostfp)) { <START> throw new GeneralSecurityException("Invalid fingerprint got " + <END> vdsClient.getSSHKeyFingerprint() + " exected " + hostfp); } } }</code><technical_language>please indent, indent block. please string.format. String actual = this.getHostFingerprint(); String expected = _vds.getSSHFingerprint(); if (isEmpty(expected)) { _vds.setSSHFingerprint(actual); // persist } else if (!actual.equals(expected)) { throw new GeneralSecurityException( String.format( "Invalid fin... '%s' expected '%s'", actual, expected ) ); }</technical_language>

Target:
public void connect() throws Exception { super.connect(); if (_vds != null) { String actual = getHostFingerprint(); String expected = _vds.getSSHKeyFingerprint(); if (!actual.equals(expected)) { throw new GeneralSecurityException( String.format( "Invalid fingerprint %s, expected %s", actual, expected ) ); } } }
Source:
<code><START> public boolean checkMessages(String deletingMessageID, String queueName) { <END> boolean isSuccessful = true; if (isElementPresent(UIElementMapper.getInstance() .getElement("mb.dlc.browse.content.table"))) { WebElement queueTable = driver.findElement(By.xpath(UIElementMapper.getInstance(). getElement("mb.dlc.browse.content.table"))); List<WebElement> rowElementList = queueTable.findElements(By.tagName("tr")); for (WebElement row : rowElementList) { List<WebElement> columnList = row.findElements(By.tagName("td")); if ((columnList.size() == COLUMN_LIST_SIZE) && columnList.get(MESSAGE_ID_COLUMN) .getText().equals(deletingMessageID)) { isSuccessful = false; break; } } } else { Assert.fail("No messages in Queue" + queueName + "after deleting"); } return isSuccessful; }</code><technical_language>sense this a private method ? i.e if this function is in this class only</technical_language>

Target:
private boolean checkMessages(String deletingMessageID, String queueName) { boolean isSuccessful = true; if (isElementPresent(UIElementMapper.getInstance() .getElement("mb.dlc.browse.content.table"))) { WebElement queueTable = driver.findElement(By.xpath(UIElementMapper.getInstance(). getElement("mb.dlc.browse.content.table"))); List<WebElement> rowElementList = queueTable.findElements(By.tagName("tr")); for (WebElement row : rowElementList) { List<WebElement> columnList = row.findElements(By.tagName("td")); if ((COLUMN_LIST_SIZE == columnList.size()) && columnList.get(MESSAGE_ID_COLUMN) .getText().equals(deletingMessageID)) { isSuccessful = false; break; } } } else { Assert.fail("No messages in Queue" + queueName + "after deleting"); } return isSuccessful; }
Source:
<code>public AsyncRabbitTemplate(ConnectionFactory connectionFactory, String exchange, String routingKey, String replyQueue, String replyAddress) { Assert.notNull(connectionFactory, "'connectionFactory' cannot be null"); Assert.notNull(routingKey, "'routingKey' cannot be null"); Assert.notNull(replyQueue, "'replyQueue' cannot be null"); this.template = new RabbitTemplate(connectionFactory); this.template.setExchange(exchange == null ? "" : exchange); this.template.setRoutingKey(routingKey); this.container = new SimpleMessageListenerContainer(connectionFactory); Collection<MessagePostProcessor> afterReceivePostProcessors = this.template.getAfterReceivePostProcessors(); if (afterReceivePostProcessors != null) { <START> this.container.setAfterReceivePostProcessors( <END> afterReceivePostProcessors.toArray(new MessagePostProcessor[0])); } this.container.setQueueNames(replyQueue); this.container.setMessageListener(this); this.container.afterPropertiesSet(); this.directReplyToContainer = null; if (replyAddress == null) { this.replyAddress = replyQueue; } else { this.replyAddress = replyAddress; } }</code><technical_language>If null? JavaUtils</technical_language>

Target:
public AsyncRabbitTemplate(ConnectionFactory connectionFactory, String exchange, String routingKey, String replyQueue, String replyAddress) { Assert.notNull(connectionFactory, "'connectionFactory' cannot be null"); Assert.notNull(routingKey, "'routingKey' cannot be null"); Assert.notNull(replyQueue, "'replyQueue' cannot be null"); this.template = new RabbitTemplate(connectionFactory); this.template.setExchange(exchange == null ? "" : exchange); this.template.setRoutingKey(routingKey); this.container = new SimpleMessageListenerContainer(connectionFactory); JavaUtils.INSTANCE .acceptIfNotNull(this.template.getAfterReceivePostProcessors(), (value) -> this.container.setAfterReceivePostProcessors( value.toArray(new MessagePostProcessor[0]))); this.container.setQueueNames(replyQueue); this.container.setMessageListener(this); this.container.afterPropertiesSet(); this.directReplyToContainer = null; if (replyAddress == null) { this.replyAddress = replyQueue; } else { this.replyAddress = replyAddress; } }
Source:
<code>public static Charset parseEncoding(final byte[] b) { final int enc = encoding(b, 0); if (enc < 0) return Constants.CHARSET; final int lf = nextLF(b, enc); String decoded = decode(Constants.CHARSET, b, enc, lf - 1); try { return Charset.forName(decoded); } catch (IllegalCharsetNameException badName) { <START> Charset aliased = encodingAliases.get(StringUtils <END> .toLowerCase(decoded)); if (aliased != null) return aliased; throw badName; } catch (UnsupportedCharsetException badName) { Charset aliased = encodingAliases.get(StringUtils .toLowerCase(decoded)); if (aliased != null) return aliased; throw badName; } }</code><technical_language>this is line wrapping, lets pull lookup a private method: private static Charset charsetForAlias(String name) { return encodingAliases.get(StringUtils.toLowerCase(name)); } declare helper method right this parseEncoding method</technical_language>

Target:
public static Charset parseEncoding(final byte[] b) { final int enc = encoding(b, 0); if (enc < 0) return Constants.CHARSET; final int lf = nextLF(b, enc); String decoded = decode(Constants.CHARSET, b, enc, lf - 1); try { return Charset.forName(decoded); } catch (IllegalCharsetNameException badName) { Charset aliased = charsetForAlias(decoded); if (aliased != null) return aliased; throw badName; } catch (UnsupportedCharsetException badName) { Charset aliased = charsetForAlias(decoded); if (aliased != null) return aliased; throw badName; } }
Source:
<code>public MultiSourceTrackingToken createHeadToken() { Map<String, TrackingToken> tokenMap = new HashMap<>(); <START> eventStreams.forEach((k, v) -> tokenMap.put(k, v.createHeadToken())); <END> return new MultiSourceTrackingToken(tokenMap); }</code><technical_language>Suggestion: do, is this: Map<String, TrackingToken> tokenMap = eventStreams.entrySet().stream().collect(Collectors.toMap( Map.Entry::getKey, entry -> entry.getValue().createHeadToken() ));</technical_language>

Target:
public MultiSourceTrackingToken createHeadToken() { Map<String, TrackingToken> tokenMap = new HashMap<>(); eventStreams.forEach(streamableMessageSource -> tokenMap.put(streamableMessageSource.sourceId(), streamableMessageSource.createHeadToken())); return new MultiSourceTrackingToken(tokenMap); }
Source:
<code>public static ReplicationFactor fromString(String s) { if (s.contains("/")) { List<String> parts = Splitter.on('/').splitToList(s); Preconditions.checkArgument( parts.size() == 2, "Replication factor format is <replicas> or <replicas>/<transient>"); <START> return new ReplicationFactor(Integer.valueOf(parts.get(0)), Integer.valueOf(parts.get(1))); <END> } else { return new ReplicationFactor(Integer.valueOf(s), 0); } }</code><technical_language>Nit: Integer.parseInt avoid IDEA warnings (redundant boxing)</technical_language>

Target:
public static ReplicationFactor fromString(String s) { if (s.contains("/")) { int slash = s.indexOf('/'); String allPart = s.substring(0, slash); String transientPart = s.substring(slash + 1); Preconditions.checkArgument( allPart != null && transientPart != null, "Replication factor format is <replicas> or <replicas>/<transient>"); return new ReplicationFactor(Integer.parseInt(allPart), Integer.parseInt(transientPart)); } else { return new ReplicationFactor(Integer.parseInt(s), 0); } }
Source:
<code>public void testGetPath() throws Exception { String aut = "p b r;\n" + "q a r;\n" + "r b p;\n" + "r a q;\n" + "q a t;\n" + "p;\n" + "t;\n"; PAutomaton auto = PAutomaton.of(aut); PAutomatonState p = PAutomatonState.ofString("p"); PAutomatonState t = PAutomatonState.ofString("t"); Collection<Transition> path = auto.getPath(p, t); System.err.println("One shortest path from p to t is: " + path); <START> org.junit.Assert.assertEquals("Path from p to t should have size 3", 3, path.size()); <END> }</code><technical_language>assert path is</technical_language>

Target:
public void testGetPath() throws Exception { String aut = "p b r;\n" + "q a r;\n" + "r b p;\n" + "r a q;\n" + "q a t;\n" + "p;\n" + "t;\n"; PAutomaton<PAutomatonState<String, String>, String> auto = PAutomaton.of(aut); PAutomatonState<String, String> p = PAutomatonState.ofString("p"); PAutomatonState<String, String> t = PAutomatonState.ofString("t"); Collection<Transition<PAutomatonState<String, String>, String>> path = auto.getPath(p, t); org.junit.Assert.assertEquals("Path from p to t should have size 3", 3, path.size()); org.junit.Assert.assertEquals("Shortest path","[p b r, r a q, q a t]",path.toString()); }
Source:
<code>public void testQueryTaskByVariablesWithOwners() { Map<String, Object> variables = emptyMap(); Map<String, Object> attributes = emptyMap(); List<String> potOwners = Collections.singletonList("katy"); <START> List<UserTaskInstanceWithPotOwnerDesc> data = advanceVariableDataService.queryUserTasksByVariables(attributes, variables, emptyMap(), potOwners, new QueryContext(0, 2)); <END> Assert.assertEquals(2, data.size()); for (UserTaskInstanceWithPotOwnerDesc p : data) { Assert.assertTrue(p.getPotentialOwners().contains("katy")); } }</code><technical_language>get next batch for pagination</technical_language>

Target:
public void testQueryTaskByVariablesWithOwners() { List<String> potOwners = Collections.singletonList("katy"); List<UserTaskInstanceWithPotOwnerDesc> data = advanceVariableDataService.queryUserTasksByVariables(emptyList(), emptyList(), emptyList(), potOwners, queryContext); if (queryContext.getCount() > 0) { Assert.assertThat(data.size(), is(queryContext.getCount())); } for (UserTaskInstanceWithPotOwnerDesc p : data) { Assert.assertTrue(p.getPotentialOwners().contains("katy")); } }
Source:
<code>public void initialize(FrameAnimation schemaObject) { function = gameLoop.getFactory().getEngineObject( schemaObject.getNextframe() != null ? schemaObject .getNextframe() : new Linear()); frames = new ArrayList<TimedRenderer>(); <START> if (schemaObject.getFrames() != null) { <END> for (Timed f : schemaObject.getFrames()) { if (f != null) frames.add((TimedRenderer) gameLoop.getFactory() .getEngineObject(f)); else frames.add(null); } } setCurrentFrame(function.getInitialFrameIndex(frames.size())); }</code><technical_language>Lists in schema objects initialized empty lists, null. If are, schema is corrupted (someone intentionally change list null), throwing a exception (NullPointerException in this case) is a valid reaction. exception caught in game loop, decided do</technical_language>

Target:
public void initialize(FrameAnimation schemaObject) { function = gameLoop.getFactory().getEngineObject( schemaObject.getNextframe() != null ? schemaObject .getNextframe() : new Linear()); frames = new ArrayList<TimedRenderer>(); for (Timed f : schemaObject.getFrames()) { frames.add((TimedRenderer) gameLoop.getFactory().getEngineObject(f)); } setCurrentFrame(function.getInitialFrameIndex(frames.size())); }
Source:
<code><START> public String toString() { <END> return "App{" + "Description='" + Description + '\'' + ", Name='" + Name + '\'' + ", Downloads=" + Downloads + ", RedirectUris=" + Arrays.toString(RedirectUris) + ", Image=" + Image + '}'; }</code><technical_language>generating toString() "String concat (+) super.toString() template in AndroidStudio - get Id field logged pretty important for debugging</technical_language>

Target:
public String toString() { return "App{" + "Description='" + Description + '\'' + ", Name='" + Name + '\'' + ", Downloads=" + Downloads + ", RedirectUris=" + Arrays.toString(RedirectUris) + ", Image=" + Image + ", Tags=" + Arrays.toString(Tags) + "} " + super.toString(); }
Source:
<code>public PipelineEventReader<CharacterEventReader, CharacterEvent> getEventReader( HttpServletRequest request, HttpServletResponse response) { if (this.wrappedComponent != null) { final PipelineEventReader<CharacterEventReader, CharacterEvent> pipelineEventReader = this.wrappedComponent.getEventReader(request, response); final CharacterEventReader eventReader = pipelineEventReader.getEventReader(); final JsonWrapperFilteringCharacterEventReader jsonWrapperFilteringCharacterEventReader = new JsonWrapperFilteringCharacterEventReader(eventReader); final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties(); return new PipelineEventReaderImpl<CharacterEventReader, CharacterEvent>( jsonWrapperFilteringCharacterEventReader, outputProperties); <START> } else return null; <END> }</code><technical_language>art: else is needed if ends a return</technical_language>

Target:
public PipelineEventReader<CharacterEventReader, CharacterEvent> getEventReader( HttpServletRequest request, HttpServletResponse response) throws IllegalStateException { if (this.wrappedComponent != null) { final PipelineEventReader<CharacterEventReader, CharacterEvent> pipelineEventReader = this.wrappedComponent.getEventReader(request, response); final CharacterEventReader eventReader = pipelineEventReader.getEventReader(); final JsonWrapperFilteringCharacterEventReader jsonWrapperFilteringCharacterEventReader = new JsonWrapperFilteringCharacterEventReader(eventReader); final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties(); return new PipelineEventReaderImpl<CharacterEventReader, CharacterEvent>( jsonWrapperFilteringCharacterEventReader, outputProperties); } else { logger.warn("PipelineComponentWrapper.wrapperComponent is null"); throw new IllegalStateException("PipelineComponentWrapper.wrapperComponent is null"); } }
Source:
<code>public DataTransactionResult clearPassengers() { this.removePassengers(); <START> final ImmutableList.Builder<EntitySnapshot> passengerSnapshotsBuilder = ImmutableList.builder(); END> final DataTransactionResult.Builder builder = DataTransactionResult.builder(); return builder.result(DataTransactionResult.Type.SUCCESS).success(new ImmutableSpongeListValue<>(Keys.PASSENGERS, passengerSnapshotsBuilder .build())).build(); }</code><technical_language>Intended empty, a list of _removed_ passengers</technical_language>

Target:
public void clearPassengers() { this.removePassengers(); }
Source:
<code>public ChatComponent setStrikethrough(boolean strikethrough) { <START> $lock.writeLock().lock(); <END> if (this.strikethrough == null) this.strikethrough = new AtomicBoolean(strikethrough); else this.strikethrough.set(strikethrough); $lock.writeLock().unlock(); return this; }</code><technical_language>THREAD-SAFETY This is a poor construct for a thread-safe class. save (that much) memory, solved a volatile boolean set false a default instead</technical_language>

Target:
public ChatComponent setStrikethrough(boolean strikethrough) { if (this.strikethrough == null) this.strikethrough = new AtomicBoolean(strikethrough); else this.strikethrough.set(strikethrough); return this; }
Source:
<code>protected void configure() { bind(AmazonAutoScaling.class).toProvider(AmazonAutoScalingProvider.class); bind(AmazonS3Client.class).toProvider(AmazonS3ClientProvider.class); bind(InstanceStatusOverridesView.class).to(AsgStatusOverridesView.class); <START> bind(InstanceStatusOverridesView.class).to(S3StatusOverridesRegistry.class); <END> bind(InstanceStatusOverridesSource.class).to(S3StatusOverridesRegistry.class); MapBinder<Integer, OverridesService> mapbinder = MapBinder.newMapBinder(binder(), Integer.class, OverridesService.class); mapbinder.addBinding(0).to(AsgStatusOverridesService.class); mapbinder.addBinding(1).to(S3StatusOverridesService.class); }</code><technical_language>Binding InstanceStatusOverridesView class</technical_language>

Target:
protected void configure() { bind(AmazonAutoScaling.class).toProvider(AmazonAutoScalingProvider.class); bind(AmazonS3Client.class).toProvider(AmazonS3ClientProvider.class); bind(AsgStatusOverridesView.class).in(Scopes.SINGLETON); bind(S3StatusOverridesRegistry.class).in(Scopes.SINGLETON); bind(OverridesService.class).to(CompositeOverridesService.class).in(Scopes.SINGLETON); Multibinder<OverridesService> multibinder = Multibinder.newSetBinder(binder(), OverridesService.class); multibinder.addBinding().to(AsgStatusOverridesService.class); multibinder.addBinding().to(S3StatusOverridesService.class); }
Source:
<code>public boolean contains(@Nullable ServiceId serviceId) { return serviceId != null && serviceId.equals(serviceIdMap.get(serviceId.getId())); <START> } <END></code><technical_language>ServiceId objects serviceId field? e.g. aliases</technical_language>

Target:
public boolean contains(@Nullable ServiceId serviceId) { return serviceId != null && serviceIdMap.get(serviceId.getId()).contains(serviceId); }
Source:
<code><START> public PsFacebook(final com.jcabi.http.Request frequest, <END> final WebRequestor frequestor, final String fapp, final String fkey) { this.request = frequest; this.requestor = frequestor; this.app = fapp; this.key = fkey; }</code><technical_language>this constructor package protected if supposed for test</technical_language>

Target:
PsFacebook(final com.jcabi.http.Request frequest, final WebRequestor frequestor, final String fapp, final String fkey) { this.request = frequest; this.requestor = frequestor; this.app = fapp; this.key = fkey; }
Source:
<code>public String addHiddenContent(String spaceId, String contentId, String contentMimeType, InputStream content) { <START> log.debug("addContent(" + spaceId + ", " + contentId + ", " + <END> contentMimeType + ")"); String bucketName = getBucketName(spaceId); if (contentMimeType == null || contentMimeType.equals("")) { contentMimeType = DEFAULT_MIMETYPE; } ObjectMetadata objMetadata = new ObjectMetadata(); objMetadata.setContentType(contentMimeType); PutObjectRequest putRequest = new PutObjectRequest(bucketName, contentId, content, objMetadata); putRequest.setStorageClass(DEFAULT_STORAGE_CLASS); putRequest.setCannedAcl(CannedAccessControlList.Private); try { PutObjectResult putResult = s3Client.putObject(putRequest); return putResult.getETag(); } catch (AmazonClientException e) { String err = "Could not add content " + contentId + " with type " + contentMimeType + " to S3 bucket " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, NO_RETRY); } }</code><technical_language>this "addHiddenContent(" "addContent("</technical_language>

Target:
public String addHiddenContent(String spaceId, String contentId, String contentMimeType, InputStream content) { log.debug("addHiddenContent(" + spaceId + ", " + contentId + ", " + contentMimeType + ")"); String bucketName = getBucketName(spaceId); if (contentMimeType == null || contentMimeType.equals("")) { contentMimeType = DEFAULT_MIMETYPE; } ObjectMetadata objMetadata = new ObjectMetadata(); objMetadata.setContentType(contentMimeType); PutObjectRequest putRequest = new PutObjectRequest(bucketName, contentId, content, objMetadata); putRequest.setStorageClass(DEFAULT_STORAGE_CLASS); putRequest.setCannedAcl(CannedAccessControlList.Private); try { PutObjectResult putResult = s3Client.putObject(putRequest); return putResult.getETag(); } catch (AmazonClientException e) { String err = "Could not add content " + contentId + " with type " + contentMimeType + " to S3 bucket " + bucketName + " due to error: " + e.getMessage(); throw new StorageException(err, e, NO_RETRY); } }
Source:
<code>public static String extractValue(String input, String xpath) { if (input == null || xpath == null) { return null; } try { XPathExpression xpathExpression = XPATH_FACTORY.newXPath().compile(xpath); try { NodeList nodes = (NodeList) xpathExpression .evaluate(new InputSource(new StringReader(input)), XPathConstants.NODESET); List<String> result = new ArrayList<>(); for (int i = 0; i < nodes.getLength(); i++) { result.add(nodes.item(i).getFirstChild().getTextContent()); } return StringUtils.join(result, " "); } catch (Exception e) { return xpathExpression.evaluate(new InputSource(new StringReader(input))); } <START> } catch (Exception ex) { <END> throw RESOURCE.illegalBehaviorInExtractValueFunc(ex.toString(), input, xpath).ex(); } }</code><technical_language>Catch clause is general</technical_language>

Target:
public static String extractValue(String input, String xpath) { if (input == null || xpath == null) { return null; } try { XPathExpression xpathExpression = XPATH_FACTORY.get().newXPath().compile(xpath); try { NodeList nodes = (NodeList) xpathExpression .evaluate(new InputSource(new StringReader(input)), XPathConstants.NODESET); List<String> result = new ArrayList<>(); for (int i = 0; i < nodes.getLength(); i++) { result.add(nodes.item(i).getFirstChild().getTextContent()); } return StringUtils.join(result, " "); } catch (XPathExpressionException e) { return xpathExpression.evaluate(new InputSource(new StringReader(input))); } } catch (XPathExpressionException ex) { throw RESOURCE.illegalBehaviorInExtractValueFunc(ex.toString(), input, xpath).ex(); } }
Source:
<code>protected Object handleRequestMessage(Message<?> requestMessage) { Assert.notNull(this.connectionFactory, this.getClass().getName() + " requires a client connection factory"); boolean haveSemaphore = false; TcpConnection connection = null; String connectionId = null; try { haveSemaphore = acquireSemaphoreIfNeeded(requestMessage); connection = this.connectionFactory.getConnection(); Long remoteTimeout = getRemoteTimeout(requestMessage); AsyncReply reply = new AsyncReply(remoteTimeout, connection, haveSemaphore, requestMessage); connectionId = connection.getConnectionId(); this.pendingReplies.put(connectionId, reply); if (logger.isDebugEnabled()) { logger.debug("Added pending reply " + connectionId); } connection.send(requestMessage); if (this.closeStreamAfterSend) { connection.shutdownOutput(); } if (isAsync()) { return reply.getFuture(); } else { return getReply(requestMessage, connection, connectionId, reply); } } catch (RuntimeException | IOException e) { logger.error("Tcp Gateway exception", e); if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessagingException("Failed to send or receive", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new MessageHandlingException(requestMessage, "Interrupted in the [" + this + ']', e); } finally { <START> if (!isAsync()) { <END> cleanUp(haveSemaphore, connection, connectionId); } } }</code><technical_language>obtain isAsync() local variable in begging of method? Kinda avoid a race condition changed in runtime..</technical_language>

Target:
protected Object handleRequestMessage(Message<?> requestMessage) { Assert.notNull(this.connectionFactory, this.getClass().getName() + " requires a client connection factory"); boolean haveSemaphore = false; TcpConnection connection = null; String connectionId = null; boolean async = isAsync(); try { haveSemaphore = acquireSemaphoreIfNeeded(requestMessage); connection = this.connectionFactory.getConnection(); Long remoteTimeout = getRemoteTimeout(requestMessage); AsyncReply reply = new AsyncReply(remoteTimeout, connection, haveSemaphore, requestMessage, async); connectionId = connection.getConnectionId(); this.pendingReplies.put(connectionId, reply); if (logger.isDebugEnabled()) { logger.debug("Added pending reply " + connectionId); } connection.send(requestMessage); if (this.closeStreamAfterSend) { connection.shutdownOutput(); } if (async) { return reply.getFuture(); } else { return getReply(requestMessage, connection, connectionId, reply); } } catch (RuntimeException | IOException e) { logger.error("Tcp Gateway exception", e); if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessagingException("Failed to send or receive", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new MessageHandlingException(requestMessage, "Interrupted in the [" + this + ']', e); } finally { if (!async) { cleanUp(haveSemaphore, connection, connectionId); } } }
Source:
<code>public Aggregator factorize(final ColumnSelectorFactory metricFactory) <START> { <END> final ColumnValueSelector<BloomKFilter> selector = metricFactory.makeColumnValueSelector(fieldName); if (selector instanceof NilColumnValueSelector) { return NoopAggregator.instance(); } return new BloomFilterMergeAggregator(selector, getMaxNumEntries()); }</code><technical_language>I if this valid? Null empty Bloom filter is</technical_language>

Target:
public Aggregator factorize(final ColumnSelectorFactory metricFactory) { final BaseNullableColumnValueSelector selector = metricFactory.makeColumnValueSelector(fieldName); if (selector instanceof NilColumnValueSelector) { throw new ISE("WTF?! Unexpected NilColumnValueSelector"); } return new BloomFilterMergeAggregator((ColumnValueSelector<Object>) selector, new BloomKFilter(getMaxNumEntries())); }
Source:
<code>public void buildAndSkipDepsNonExistentProject() throws Exception{ AFCompilerService service = new DefaultKieCompilerService(); CompletableFuture<KieCompilationResponse> futureRes = service.build(tmpRoot, mavenRepo.toString(), Boolean.FALSE); KieCompilationResponse res = futureRes.get(); assertThat(res.isSuccessful()).isFalse(); assertThat(res.getDependencies().isEmpty()).isTrue(); <START> assertThat(res.getDependencies().size()).isEqualTo(0); <END> }</code><technical_language>Please replace .size()).isEqualTo( .hasSize( 16x in this PR: Ctrl+f .size()).isEqualTo(</technical_language>

Target:
public void buildAndSkipDepsNonExistentProject() throws Exception{ AFCompilerService service = new DefaultKieCompilerService(); CompletableFuture<KieCompilationResponse> futureRes = service.build(tmpRoot, mavenRepo.toString(), Boolean.FALSE); KieCompilationResponse res = futureRes.get(); assertThat(res.isSuccessful()).isFalse(); assertThat(res.getDependencies()).isEmpty(); }
Source:
<code>default <K extends Comparable<? super K>, V> Map<K, V> toLinkedMap( Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper, BiFunction<? super V, ? super V, ? extends V> merge) { return LinkedHashMap.ofEntries(toMap(keyMapper, valueMapper, merge)); <START> } <END></code><technical_language>I do maintain key order here, is iteration order of elements of this Traversable. result of toMap guarantee specific key order. need do some extra work order keys of LinkedHashMap: java default <K extends Comparable<? super K>, V> Map<K, V> toLinkedMap( Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper, BiFunction<? super V, ? super V, ? extends V> merge) { final Map<K, V> map = toMap(keyMapper, valueMapper, merge); final Iterator<K, V> entries = iterator().map(t -> { key = keyMapper.apply(t); V = map.getOrElse(key, null); // default return Tuple.of(key, value); }); return LinkedHashMap.ofEntries(entries); }</technical_language>

Target:
default <K extends Comparable<? super K>, V> Map<K, V> toLinkedMap( Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper, BiFunction<? super V, ? super V, ? extends V> merge) { final Map<K, V> map = toMap(keyMapper, valueMapper, merge); final Iterator<Tuple2<K, V>> entries = iterator() .map(keyMapper) .distinct() .map(key -> { V value = map.getOrElse(key, null); return Tuple.of(key, value); }); return LinkedHashMap.ofEntries(entries); }
Source:
<code>public int doStartTag() throws JspException { JspWriter jspWriter = pageContext.getOut(); namespace = getNamespace(); StringBuilder display = new StringBuilder(); try { if (licenseIds != null && !licenseIds.isEmpty()) { printLicenses(display, licenseIds); } else { printEmptyLicenses(display); } <START> display.append(String.format("<script>$(document).ready(function () { showLicenseDialogWrapper('%s'); })</script>", id)); <END> jspWriter.print(display.toString()); } catch (Exception e) { throw new JspException(e); } return SKIP_BODY; }</code><technical_language>nice change usage of require discussed in person</technical_language>

Target:
public int doStartTag() throws JspException { JspWriter jspWriter = pageContext.getOut(); namespace = getNamespace(); StringBuilder display = new StringBuilder(); try { String licenseIdsString = (licenseIds != null && !licenseIds.isEmpty()) ? Joiner.on(", ").join(licenseIds) : ""; printHtmlElements(display, licenseIdsString); jspWriter.print(display.toString()); } catch (Exception e) { throw new JspException(e); } return SKIP_BODY; }
Source:
<code>public Boolean getValue(ClusterNetworkModel clusterNetworkModel) { <START> return clusterNetworkModel.isAttached() && clusterNetworkModel.isRequired(); <END> }</code><technical_language>view display model data, logic for showing data represent model values. root of problem resides in- ClusterNetworkModel. public ClusterNetworkModel(Network network)->if (network.getCluster() == null)-> getEntity().setCluster(new NetworkCluster(/*isRequired*/!network.isExternal())); means in case of detached network required is true default (in case of internal network), changed false (no matter if network is internal external)</technical_language>

Target:
public Boolean getValue(ClusterNetworkModel clusterNetworkModel) { return clusterNetworkModel.isRequired(); }
Source:
<code>public JSONArray getInstallablesJson() throws IOException { <START> JSONObject d = Downloadable.get(getId()).getData(); <END> return d == null ? new JSONArray() : d.getJSONArray("list"); }</code><technical_language><code>Downloadable.get()</code> return null. is a mistake in original code, sense fix it</technical_language>

Target:
public JSONArray getInstallablesJson() throws IOException { JSONArray tools = new JSONArray(); final Downloadable d = Downloadable.get(getId()); if (d != null) { final JSONObject data = d.getData(); if (data != null) tools = data.getJSONArray("list"); } return tools; }
Source:
<code><START> public CosemObisCodeDto(final int[] code) { <END> if (code.length != 6) { throw new IllegalArgumentException("ObisCode must have 6 values: " + code.length); } this.a = code[0]; this.b = code[1]; this.c = code[2]; this.d = code[3]; this.e = code[4]; this.f = code[5]; this.checkValues(); }</code><technical_language>nature of this class, I in a case this, option suppress parameters warning. fields defined a specification, is refactoring improve structure, constructor a nice explicit mapping design</technical_language>

Target:
public CosemObisCodeDto(final int[] code) { if (code.length != 6) { throw new IllegalArgumentException("ObisCode must have 6 values: " + code.length); } this.a = code[0]; this.b = code[1]; this.c = code[2]; this.d = code[3]; this.e = code[4]; this.f = code[5]; this.checkValues(this.a, this.b, this.c, this.d, this.e, this.f); }
Source:
<code>public void start(BundleContext context) throws Exception { super.start(context); IExtensionRegistry registry = Platform.getExtensionRegistry(); this.descriptionConverterRegistry = new ItemRegistry<>(); this.descriptionConverterListener = new DescriptorRegistryEventListener<>(PLUGIN_ID, DESCRIPTION_CONVERTER_EXTENSION_POINT, this.descriptionConverterRegistry); registry.addListener(this.descriptionConverterListener, PLUGIN_ID + '.' + DESCRIPTION_CONVERTER_EXTENSION_POINT); this.descriptionConverterListener.readRegistry(registry); this.descriptionLinkResolverRegistry = new ItemRegistry<>(); this.descriptionLinkResolverListener = new DescriptorRegistryEventListener<>(PLUGIN_ID, DESCRIPTION_LINK_RESOLVER_EXTENSION_POINT, this.descriptionLinkResolverRegistry); registry.addListener(this.descriptionLinkResolverListener, PLUGIN_ID + '.' + DESCRIPTION_LINK_RESOLVER_EXTENSION_POINT); this.descriptionLinkResolverListener.readRegistry(registry); <START> INSTANCE.startPropertiesPreferencesManagement(); <END> }</code><technical_language>I matter in practice, technically a "stopPropertiesPreferencesManagement()" in Bundle#stop()</technical_language>

Target:
public void start(BundleContext context) throws Exception { super.start(context); IExtensionRegistry registry = Platform.getExtensionRegistry(); this.descriptionConverterRegistry = new ItemRegistry<>(); this.descriptionConverterListener = new DescriptorRegistryEventListener<>(PLUGIN_ID, DESCRIPTION_CONVERTER_EXTENSION_POINT, this.descriptionConverterRegistry); registry.addListener(this.descriptionConverterListener, PLUGIN_ID + '.' + DESCRIPTION_CONVERTER_EXTENSION_POINT); this.descriptionConverterListener.readRegistry(registry); this.descriptionLinkResolverRegistry = new ItemRegistry<>(); this.descriptionLinkResolverListener = new DescriptorRegistryEventListener<>(PLUGIN_ID, DESCRIPTION_LINK_RESOLVER_EXTENSION_POINT, this.descriptionLinkResolverRegistry); registry.addListener(this.descriptionLinkResolverListener, PLUGIN_ID + '.' + DESCRIPTION_LINK_RESOLVER_EXTENSION_POINT); this.descriptionLinkResolverListener.readRegistry(registry); }