auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>static void runSQL(String sql, Connection cx) throws SQLException { Statement st = cx.createStatement(); try { st.execute(sql); } <START> catch (SQLException e) { <END> LOGGER.log(Level.WARNING, e.getMessage(), e); } finally { close(st); } }</code><technical_language>catching this logging for now</technical_language>

Target:
static void runSQL(String sql, Connection cx) throws SQLException { Statement st = cx.createStatement(); try { st.execute(sql); } finally { close(st); } }
Source:
<code>public void stopServer() { if (server == null) throw new IllegalStateException("Jetty has to be initialized before stopping it"); if (server.isStopped() || server.isStopping()) <START> throw new IllegalStateException("Jetty is not running stopped"); <END> try { server.stop(); } catch (Exception e) { log.severe(e.getMessage()); throw new KumuluzServerException(e.getMessage(), e.getCause()); } }</code><technical_language>fix exception message to: "Jetty is stopped"</technical_language>

Target:
public void stopServer() { if (server == null) throw new IllegalStateException("Jetty has to be initialized before stopping it"); if (server.isStopped() || server.isStopping()) throw new IllegalStateException("Jetty is already stopped"); try { server.stop(); } catch (Exception e) { log.severe(e.getMessage()); throw new KumuluzServerException(e.getMessage(), e.getCause()); } }
Source:
<code>protected void addVirtualEvents(FormattedEventBase[] indexedEvents, int initialIndex) { <START> for (int index = initialIndex; index < mMinItems; ++index) { <END> if (indexedEvents[index] == null) { indexedEvents[index] = mVirtualEvent; } } }</code><technical_language>I for index++ (seems more common in code base)</technical_language>

Target:
protected void addVirtualEvents(FormattedEventBase[] indexedEvents, int initialIndex) { for (int index = initialIndex; index < mMinItems; index++) { if (indexedEvents[index] == null) { indexedEvents[index] = mVirtualEvent; } } }
Source:
<code>private static Map<String, Collection<String>> caseInsensitiveCopyOf(Map<String, Collection<String>> headers) { Map<String, Collection<String>> result = new TreeMap<String, Collection<String>>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, Collection<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); Collection<String> values = result.get(headerName); if (values == null) { values = new LinkedList<String>(); <START> result.put(headerName.toLowerCase(Locale.US), values); <END> } values.addAll(entry.getValue()); } return result; }</code><technical_language>I Local.ROOT is a choice</technical_language>

Target:
private static Map<String, Collection<String>> caseInsensitiveCopyOf(Map<String, Collection<String>> headers) { Map<String, Collection<String>> result = new TreeMap<String, Collection<String>>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry<String, Collection<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); if (!result.containsKey(headerName)) { result.put(headerName.toLowerCase(Locale.ROOT), new LinkedList<String>()); } result.get(headerName).addAll(entry.getValue()); } return result; }
Source:
<code>public void setCompletionInfo(String deviceId, String folderId, CompletionInfo completionInfo) { if (!deviceFolderMap.containsKey(deviceId)) { deviceFolderMap.put(deviceId, defaultDevice); } deviceFolderMap.get(deviceId).put(folderId, completionInfo); <START> } <END></code><technical_language>Again, default is misused, do: if deviceMap.contains(deviceId) { deviceMap.get(deviceId).put(folderId, completionInfo) } else { Map<String, Completion> deviceCompletion = new HashMap<String, Completion>() deviceCompletion.put(folder, completion) deviceMap.put(device, deviceCompeltion) }</technical_language>

Target:
public void setCompletionInfo(String deviceId, String folderId, CompletionInfo completionInfo) { if (!deviceFolderMap.containsKey(deviceId)) { deviceFolderMap.put(deviceId, new HashMap<String, CompletionInfo>()); } deviceFolderMap.get(deviceId).put(folderId, completionInfo); }
Source:
<code>private static CharPredicate getHostMatcherForPattern(GrokParserStageSequenceBuilder.GrokPattern pattern) { final List<Character> hostNameCharacters = ImmutableList.of('-', '.', '_'); final CharPredicate hostNameMatcher = c -> Character.isDigit(c) || Character.isLetter(c) || hostNameCharacters.contains(c); final CharPredicate ipV4AddressMatcher = c -> Character.isDigit(c) || c == '.'; final CharPredicate ipV6AddressMatcher = c -> Character.digit(c, 16) >= 0 || c == ':'; final CharPredicate ipV4OrV6AddressMatcher = ipV4AddressMatcher.or(ipV6AddressMatcher); final CharPredicate hostnameOrIPMatcher = hostNameMatcher.or(ipV4OrV6AddressMatcher); switch (pattern) { case HOSTNAME: return hostNameMatcher; case HOSTNAMEORIP: return hostnameOrIPMatcher; case IPADDRESS: return ipV4OrV6AddressMatcher; default: <START> throw new IllegalArgumentException("Unsupported pattern."); <END> } }</code><technical_language>I include pattern in exception message</technical_language>

Target:
private static CharPredicate getHostMatcherForPattern(GrokParserStageSequenceBuilder.GrokPattern pattern) { final List<Character> hostNameCharacters = ImmutableList.of('-', '.', '_'); final CharPredicate hostNameMatcher = c -> Character.isDigit(c) || Character.isLetter(c) || hostNameCharacters.contains(c); final CharPredicate ipV4AddressMatcher = c -> Character.isDigit(c) || c == '.'; final CharPredicate ipV6AddressMatcher = c -> Character.digit(c, 16) >= 0 || c == ':'; final CharPredicate ipV4OrV6AddressMatcher = ipV4AddressMatcher.or(ipV6AddressMatcher); final CharPredicate hostnameOrIPMatcher = hostNameMatcher.or(ipV4OrV6AddressMatcher); switch (pattern) { case HOSTNAME: return hostNameMatcher; case HOSTNAMEORIP: return hostnameOrIPMatcher; case IPADDRESS: return ipV4OrV6AddressMatcher; default: throw new IllegalArgumentException("Unsupported host pattern '" + pattern + "'"); } }
Source:
<code>public String marshal( final RuleModel model ) { return marshalRule( model, <START> null ); <END> }</code><technical_language>Collections.emptySet() (or similar) nicer</technical_language>

Target:
public String marshal(final RuleModel model) { return marshalRule(model, Collections.emptyList()); }
Source:
<code>private void setupRuleModeller() { view.setupRuleModellerWidget(ruleModeller()); <START> if (plugin() instanceof BRLActionColumnPlugin) { <END> view.setRuleModelerDescription(translate(GuidedDecisionTableErraiConstants.RuleModellerPage_InsertAnActionBRLFragment)); } else { view.setRuleModelerDescription(translate(GuidedDecisionTableErraiConstants.RuleModellerPage_InsertAConditionBRLFragment)); } }</code><technical_language>@jomarko Personally, I add a method in HasRuleModellerPage get description. I a good idea avoid instanceOf follow open/closed principle. However, I approach is a bit more prolix. do think</technical_language>

Target:
private void setupRuleModeller() { view.setupRuleModellerWidget(ruleModeller()); view.setRuleModelerDescription(plugin().getRuleModellerDescription()); }
Source:
<code>public boolean canPublicAndRetrictPage(Page currentPage, String currentUser) throws WikiException { boolean canPublicAndRetrictPage = false; if (currentPage.getPermissions() != null) { for (PermissionEntry permissionEntry : currentPage.getPermissions()) { if(permissionEntry.getId().equals(currentUser)) { for(Permission permission : permissionEntry.getPermissions()) { if(permission.getPermissionType().equals(PermissionType.EDITPAGE) && permission.isAllowed()) { <START> canPublicAndRetrictPage = true; <END> break; } } } if(canPublicAndRetrictPage) { break; } } } Wiki wiki = getWikiByTypeAndOwner(currentPage.getWikiType(), currentPage.getWikiOwner()); return hasAdminPagePermission(wiki.getType(), wiki.getOwner()) || hasAdminSpacePermission(wiki.getType(), wiki.getOwner()) || canPublicAndRetrictPage; }</code><technical_language>If canPublicAndRetrictPage is true return IMO. optimize method avoid calling getWikiByTypeAndOwner, hasAdminPagePermission, hasAdminSpacePermission for nothing</technical_language>

Target:
public boolean canPublicAndRetrictPage(Page currentPage, String currentUser) throws WikiException { if (currentPage.getPermissions() != null) { for (PermissionEntry permissionEntry : currentPage.getPermissions()) { if(permissionEntry.getId().equals(currentUser)) { for(Permission permission : permissionEntry.getPermissions()) { if(permission.getPermissionType().equals(PermissionType.EDITPAGE) && permission.isAllowed()) { return true; } } } } } Wiki wiki = getWikiByTypeAndOwner(currentPage.getWikiType(), currentPage.getWikiOwner()); return hasAdminPagePermission(wiki.getType(), wiki.getOwner()) || hasAdminSpacePermission(wiki.getType(), wiki.getOwner()); }
Source:
<code>public void testToString() { SmsMessage.Builder builder = new SmsMessage.Builder(); SmsMessage smsMessage = builder.newDataObject(); <START> assertNotNull(smsMessage.toString()); <END> }</code><technical_language>enough test ToString returns a null value, check actual well. need similar test for testSmsMessage_EmptyBuilder() testGetBuilder() testGetBuilder()_EmptyMessage()</technical_language>

Target:
public void testToString() { SmsMessage.Builder builder = new SmsMessage.Builder(); SmsMessage smsMessage = builder.newDataObject(); assertNotNull(smsMessage.toString()); assertEquals(emptyString, smsMessage.toString()); }
Source:
<code>public Dialect getDialect() { Dialect dialect = myDialect; if (dialect == null) { String dialectClass = (String) myEntityManagerFactory.getJpaPropertyMap().get("hibernate.dialect"); dialect = ReflectionUtil.newInstanceOrReturnNull(dialectClass, Dialect.class); <START> Validate.notNull(dialect, "Unable to create class: %s", dialectClass); <END> myDialect = dialect; } return dialect; }</code><technical_language>suggestion Validate.notNull(dialect, "Unable create instance of class: %s", dialectClass);</technical_language>

Target:
public Dialect getDialect() { Dialect dialect = myDialect; if (dialect == null) { String dialectClass = (String) myEntityManagerFactory.getJpaPropertyMap().get("hibernate.dialect"); dialect = ReflectionUtil.newInstanceOrReturnNull(dialectClass, Dialect.class); Validate.notNull(dialect, "Unable to create instance of class: %s", dialectClass); myDialect = dialect; } return dialect; }
Source:
<code>void shouldNotFailOnDeleteByIdWithNullVersion(@Autowired VersionedThingWithAssignedIdRepository repository) { try (Session session = driver.session()) { session.writeTransaction(tx -> { <START> tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume(); return null; <END> }); } StepVerifier.create(repository.deleteById(1L)) .verifyComplete(); try (Session session = driver.session()) { long count = session.readTransaction(tx -> tx.run("MATCH (v:VersionedThingWithAssignedId) return count(v) as vCount").next() .get("vCount").asLong()); assertThat(count).isEqualTo(0); } }</code><technical_language>suggestion return tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume();</technical_language>

Target:
void shouldNotFailOnDeleteByIdWithNullVersion(@Autowired VersionedThingWithAssignedIdRepository repository) { try (Session session = driver.session()) { session.writeTransaction(tx -> tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume()); } StepVerifier.create(repository.deleteById(1L)) .verifyComplete(); try (Session session = driver.session()) { long count = session.readTransaction(tx -> tx.run("MATCH (v:VersionedThingWithAssignedId) return count(v) as vCount").next() .get("vCount").asLong()); assertThat(count).isEqualTo(0); } }
Source:
<code>public void commitCreateTable(JdbcOutputTableHandle handle) { StringBuilder sql = new StringBuilder() .append("sp_rename ") .append("'" + quoted(handle.getCatalogName(), handle.getSchemaName(), handle.getTemporaryTableName()) + "'") .append(", ") .append("'" + handle.getTableName() + "'"); try (Connection connection = this.getConnection(handle)) { this.execute(connection, sql.toString()); } catch (SQLException e) { <START> throw new PrestoException(JDBC_ERROR, e); <END> } }</code><technical_language>this relate SQL_TYPES map initialized earlier</technical_language>

Target:
public void commitCreateTable(JdbcOutputTableHandle handle) { try (Connection connection = getConnection(handle); PreparedStatement statement = connection.prepareStatement("EXEC sp_rename ?, ?")) { statement.setString(1, quoted(handle.getCatalogName(), handle.getSchemaName(), handle.getTemporaryTableName())); statement.setString(2, handle.getTableName()); statement.executeUpdate(); } catch (SQLException e) { throw new PrestoException(JDBC_ERROR, e); } }
Source:
<code>static boolean ignoreOptionName(final String name, final String value) { return name.equalsIgnoreCase("takeUnitControl") || (name.equalsIgnoreCase("giveUnitControl") <START> && (value.equals("false") || value.equals("true"))); <END> }</code><technical_language>positive null here? I remember if translate empty values empty strings null values</technical_language>

Target:
static boolean ignoreOptionName(final String name, final String value) { return name.equalsIgnoreCase("takeUnitControl") || (name.equalsIgnoreCase("giveUnitControl") && (value == null || value.equals("false") || value.equals("true"))); }
Source:
<code>public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); <START> final Resource[] resources = new Resource[] { new ClassPathResource("schemas/common.xsd"), <END> new ClassPathResource("schemas/adhocmanagement.xsd") }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }</code><technical_language>Move String values more a constant</technical_language>

Target:
public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); final Resource[] resources = new Resource[] { new ClassPathResource(COMMON_XSD_PATH), new ClassPathResource(ADHOC_MANAGEMENT_XSD_PATH) }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }
Source:
<code>public FileManager create() { final short hdfsReplication = configuration.configuration() .getSinkConfiguration(Objects.requireNonNull(name), HdfsSinkConfiguration.class).replication; try { final String hdfsWorkingDir = configuration.configuration().getSinkConfiguration(name, FileSinkConfiguration.class).fileStrategy.workingDir; final String hdfsPublishDir = configuration.configuration().getSinkConfiguration(name, FileSinkConfiguration.class).fileStrategy.publishDir; return new HdfsFileManager(getFileSystemInstance(), hdfsReplication, hdfsWorkingDir, hdfsPublishDir, schema); } catch (final IOException e) { logger.error("Failed to construct HDFS file system instance from verified configuration."); <START> throw new RuntimeException(e); <END> } }</code><technical_language>This UncheckedIOException</technical_language>

Target:
public FileManager create() { final short hdfsReplication = configuration.configuration() .getSinkConfiguration(Objects.requireNonNull(name), HdfsSinkConfiguration.class).replication; try { final String hdfsWorkingDir = configuration.configuration().getSinkConfiguration(name, FileSinkConfiguration.class).fileStrategy.workingDir; final String hdfsPublishDir = configuration.configuration().getSinkConfiguration(name, FileSinkConfiguration.class).fileStrategy.publishDir; return new HdfsFileManager(getFileSystemInstance(), hdfsReplication, hdfsWorkingDir, hdfsPublishDir, schema); } catch (final IOException e) { logger.error("Failed to construct HDFS file system instance from verified configuration."); throw new UncheckedIOException(e); } }
Source:
<code>public List<Substudy> getSubstudies(StudyIdentifier studyId, boolean includeDeleted) { checkNotNull(studyId); Map<String,Object> parameters = ImmutableMap.of("studyId", studyId.getIdentifier()); String query = "from HibernateSubstudy as substudy where studyId=:studyId"; if (!includeDeleted) { query += " and deleted != 1"; } return hibernateHelper.queryGet(query, parameters, null, null, HibernateSubstudy.class) <START> .stream().map((oneSubstudy) -> (Substudy) oneSubstudy).collect(Collectors.toList()); <END> }</code><technical_language>Minor: easier ImmutableList.copyOf()</technical_language>

Target:
public List<Substudy> getSubstudies(StudyIdentifier studyId, boolean includeDeleted) { checkNotNull(studyId); Map<String,Object> parameters = ImmutableMap.of("studyId", studyId.getIdentifier()); String query = "from HibernateSubstudy as substudy where studyId=:studyId"; if (!includeDeleted) { query += " and deleted != 1"; } return ImmutableList.copyOf(hibernateHelper.queryGet(query, parameters, null, null, HibernateSubstudy.class)); }
Source:
<code>protected List<MethodMatcher> getMethodInvocationMatchers() { <START> return ImmutableList.of(FOREACH); <END> }</code><technical_language>I Collections.singletonList guava for this</technical_language>

Target:
protected List<MethodMatcher> getMethodInvocationMatchers() { return Collections.singletonList(FOREACH); }
Source:
<code>public void checkNonCacheableReads() throws Exception { final int size = 10; <START> final long start = 0L, end = start + size; <END> LogUnitServer logUnitServer = (LogUnitServer) getDefaultServer(); setServer(logUnitServer); List<Long> addresses = LongStream.range(start, end).boxed().collect(Collectors.toList()); List<LogData> payloads = new ArrayList<>(); for (long i = start; i < end; i++) { LogData logData = new LogData(DataType.DATA, new Object()); logData.setGlobalAddress(i); payloads.add(logData); } sendMessage(CorfuMsgType.RANGE_WRITE.payloadMsg(new RangeWriteMsg(payloads))); waitForLogUnit(logUnitServer); sendMessage(CorfuMsgType.MULTIPLE_READ_REQUEST.payloadMsg(new MultipleReadRequest(addresses, false))); waitForLogUnit(logUnitServer); checkReadResponse(getLastPayloadMessageAs(ReadResponse.class), size); assertThat(logUnitServer.getDataCache().getSize()).isEqualTo(0); sendMessage(CorfuMsgType.MULTIPLE_READ_REQUEST.payloadMsg(new MultipleReadRequest(addresses, true))); waitForLogUnit(logUnitServer); checkReadResponse(getLastPayloadMessageAs(ReadResponse.class), size); assertThat(logUnitServer.getDataCache().getSize()).isEqualTo(size); }</code><technical_language>long start = 0L; long end = start + size;</technical_language>

Target:
public void checkNonCacheableReads() throws Exception { final int size = 10; final long start = 0L; final long end = start + size; LogUnitServer logUnitServer = (LogUnitServer) getDefaultServer(); setServer(logUnitServer); List<Long> addresses = LongStream.range(start, end).boxed().collect(Collectors.toList()); List<LogData> payloads = new ArrayList<>(); for (long i = start; i < end; i++) { LogData logData = new LogData(DataType.DATA, new Object()); logData.setGlobalAddress(i); payloads.add(logData); } sendMessage(CorfuMsgType.RANGE_WRITE.payloadMsg(new RangeWriteMsg(payloads))); waitForLogUnit(logUnitServer); sendMessage(CorfuMsgType.MULTIPLE_READ_REQUEST.payloadMsg(new MultipleReadRequest(addresses, false))); waitForLogUnit(logUnitServer); checkReadResponse(getLastPayloadMessageAs(ReadResponse.class), size); assertThat(logUnitServer.getDataCache().getSize()).isEqualTo(0); sendMessage(CorfuMsgType.MULTIPLE_READ_REQUEST.payloadMsg(new MultipleReadRequest(addresses, true))); waitForLogUnit(logUnitServer); checkReadResponse(getLastPayloadMessageAs(ReadResponse.class), size); assertThat(logUnitServer.getDataCache().getSize()).isEqualTo(size); }
Source:
<code>public Map<String, Map> getFlooders() { return new HashedMap() { { put("consumers", new HashMap<String, Set<String>>() {{ put("event_types", getChildren(Type.CONSUMER_ET)); put("apps", getChildren(Type.CONSUMER_APP)); }}); put("producers", new HashMap<String, Set<String>>() {{ put("event_types", getChildren(Type.PRODUCER_ET)); put("apps", getChildren(Type.PRODUCER_APP)); <START> }}); <END> } }; }</code><technical_language>I do this method. create anonymous classes in is bad. This method called 100 times second, time create class static initializer (new class, instance). means, 10 minutes class list in application 10 \* 60 \* 100 = 60000 classes (and multiplied 3, 3 static initializers -> 180K classes), if is unload it</technical_language>

Target:
public Map<String, Map> getFlooders() { return ImmutableMap.of( "consumers", ImmutableMap.of( "event_types", getChildren(Type.CONSUMER_ET), "apps", getChildren(Type.CONSUMER_APP)), "producers", ImmutableMap.of( "event_types", getChildren(Type.PRODUCER_ET), "apps", getChildren(Type.PRODUCER_APP))); }
Source:
<code>private CompletableFuture<Long> replicate(List<Entry> entries) { CompletableFuture<Long> future = new CompletableFuture<>(); FutureUtils.addListener(conn <START> .replay(regionInfo.getTable(), regionInfo.getEncodedNameAsBytes(), entries, <END> regionInfo.getReplicaId(), 1, operationTimeoutNs, location), (r, e) -> { if (e != null) { LOG.warn("Failed to replicate to {}", regionInfo); LOG.warn("Exception: " + e); future.completeExceptionally(e); } else { future.complete(r); } }); return future; }</code><technical_language>pass regionInfo instead of table, encoded name replica id</technical_language>

Target:
private CompletableFuture<Long> replicate(List<Entry> entries) { CompletableFuture<Long> future = new CompletableFuture<>(); FutureUtils.addListener(conn .replay(regionInfo.getTable(), regionInfo.getEncodedNameAsBytes(), regionInfo.getStartKey(), entries, regionInfo.getReplicaId(), numRetries, operationTimeoutNs), (r, e) -> { if (e != null) { LOG.warn("Failed to replicate to {}, exception: ", regionInfo, e); future.completeExceptionally(e); } else { future.complete(r); } }); return future; }
Source:
<code>public void onButtonClick() { <START> if (MultiClickGuard.allowClick(QuestionWidget.class.getName())) { <END> if (!isUrlEmpty(stringAnswer)) { customTabHelper.bindCustomTabsService(getContext(), null); customTabHelper.openUri(getContext(), uri); } else { Toast.makeText(getContext(), "No URL set", Toast.LENGTH_SHORT).show(); } } }</code><technical_language>This check needed in case of single widget button. If create WidgetButton class extend com.google.android.material.button.MaterialButton (then in layout file). In a class override: @Override public boolean performClick() { if (MultiClickGuard.allowClick(getClass().getName())) { return super.performClick(); } else { return false; } } do this approach</technical_language>

Target:
public void onButtonClick() { if (!isUrlEmpty(binding.urlAnswerText)) { customTabHelper.bindCustomTabsService(getContext(), null); customTabHelper.openUri(getContext(), getUri()); } else { ToastUtils.showShortToast("No URL set"); } }
Source:
<code>public void addMemberToSynchronizedGroup() throws Exception { System.out.println(CLASS_NAME + "addMemberToSynchronizedGroup"); vo = setUpVo(); setUpGroup(vo); <START> Attribute synchroAttr = new Attribute(perun.getAttributesManager().getAttributeDefinition(sess, "urn:perun:group:attribute-def:def:synchronizationEnabled")); <END> synchroAttr.setValue("true"); perun.getAttributesManager().setAttribute(sess, group, synchroAttr); Member member = setUpMember(vo); groupsManager.addMember(sess, group, member); }</code><technical_language>passing attribute name, constant GroupsManager.GROUPSYNCHROENABLED_ATTRNAME (as do in entry logic code) prevent breaking changes in a future</technical_language>

Target:
public void addMemberToSynchronizedGroup() throws Exception { System.out.println(CLASS_NAME + "addMemberToSynchronizedGroup"); vo = setUpVo(); setUpGroup(vo); Attribute synchroAttr = new Attribute(perun.getAttributesManager().getAttributeDefinition(sess, GroupsManager.GROUPSYNCHROENABLED_ATTRNAME)); synchroAttr.setValue("true"); perun.getAttributesManager().setAttribute(sess, group, synchroAttr); Member member = setUpMember(vo); groupsManager.addMember(sess, group, member); }
Source:
<code>public void testCreateInvalidConfigAeadWithAuth() throws Exception { IpSecConfig ipSecConfig = new IpSecConfig(); addDefaultSpisAndRemoteAddrToIpSecConfig(ipSecConfig); for (int direction : DIRECTIONS) { ipSecConfig.setAuthentication(direction, AUTH_ALGO); try { ipSecConfig.setAuthenticatedEncryption(direction, <START> AEAD_ALGO); <END> } catch (IllegalArgumentException expected) { } } try { mIpSecService.createTransportModeTransform(ipSecConfig, new Binder()); fail( "IpSecService should have thrown an error on authentication being" + " enabled with authenticated encryption"); } catch (IllegalArgumentException expected) { } }</code><technical_language>If exception is expected, fail if exception is thrown</technical_language>

Target:
public void testCreateInvalidConfigAeadWithAuth() throws Exception { IpSecConfig ipSecConfig = new IpSecConfig(); addDefaultSpisAndRemoteAddrToIpSecConfig(ipSecConfig); for (int direction : DIRECTIONS) { ipSecConfig.setAuthentication(direction, AUTH_ALGO); ipSecConfig.setAuthenticatedEncryption(direction, AEAD_ALGO); } try { mIpSecService.createTransportModeTransform(ipSecConfig, new Binder()); fail( "IpSecService should have thrown an error on authentication being" + " enabled with authenticated encryption"); } catch (IllegalArgumentException expected) { } }
Source:
<code>public ActiveTxnCacheSupplier(TxnSupplier delegate, int initialSize, int maxSize, boolean threadSafe) { <START> this.cache = CacheBuilder.newBuilder().initialCapacity(initialSize).maximumSize(maxSize).concurrencyLevel(threadSafe ? 32 : 1).build(); <END> this.delegate = delegate; }</code><technical_language>32 from</technical_language>

Target:
public ActiveTxnCacheSupplier(TxnSupplier delegate, int initialSize, int maxSize, boolean threadSafe) { this.cache = CacheBuilder.newBuilder().initialCapacity(initialSize).maximumSize(maxSize) .concurrencyLevel(threadSafe ? CACHE_DEFAULT_CONCURRENCY_LEVEL : 1).build(); this.delegate = delegate; }
Source:
<code>public static void assertEquals(Object[] actual, Object[] expected, String message) { if (actual == expected) { return; } if ((actual == null && expected != null) || (actual != null && expected == null)) { if (message != null) { fail(message); } else { fail("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual)); } } if (actual.length != expected.length) { failAssertNoEqual( "Arrays do not have the same size:" + actual.length + " != " + expected.length, message); } for(int i=0; i<expected.length; i++) { Object e = expected[i]; Object a = actual[i]; String explanation = "Arrays differ at element [" + i + "]: " + e + " != " + a; String errorMessage = message == null ? explanation : message + ": " + explanation; if(a == null && e == null) continue; if ((a == null && e != null) || (a != null && e == null)) { failNotEquals(a, e, message); } <START> if(a != null && e != null){ <END> if(e.getClass().isArray()) { assertEquals(a, e, errorMessage); } else { assertEqualsImpl(a, e, errorMessage); } } } }</code><technical_language>I do this condition care of other edit checks it</technical_language>

Target:
public static void assertEquals(Object[] actual, Object[] expected, String message) { if (actual == expected) { return; } if ((actual == null && expected != null) || (actual != null && expected == null)) { if (message != null) { fail(message); } else { fail("Arrays not equal: " + Arrays.toString(expected) + " and " + Arrays.toString(actual)); } } if (actual.length != expected.length) { failAssertNoEqual( "Arrays do not have the same size:" + actual.length + " != " + expected.length, message); } for(int i=0; i<expected.length; i++) { Object e = expected[i]; Object a = actual[i]; String explanation = "Arrays differ at element [" + i + "]: " + e + " != " + a; String errorMessage = message == null ? explanation : message + ": " + explanation; if (a == null && e == null) { continue; } if ((a == null && e != null) || (a != null && e == null)) { failNotEquals(a, e, message); } if(e.getClass().isArray()) { assertEquals(a, e, errorMessage); } else { assertEqualsImpl(a, e, errorMessage); } } }
Source:
<code>@Override public final void run() { <START> if (isCanceled) { <END> return; } try { final ResponseWrapper wrapper = obtainResponse(); if (isCanceled) { return; } callbackExecutor.execute(new Runnable() { @Override public void run() { if (!isCanceled) { callback.success((T) wrapper.responseBody, wrapper.response); } } }); } catch (final RetrofitError e) { callbackExecutor.execute(new Runnable() { @Override public void run() { if (!isCanceled) { callback.failure(e); } } }); } }</code><technical_language>Minor: this Square's code formatting? This if-return (and next one) line if so</technical_language>

Target:
@Override public final void run() { if (callback == null) { return; } try { final ResponseWrapper wrapper = obtainResponse(); if (callback == null) { return; } callbackExecutor.execute(new Runnable() { @Override public void run() { if (callback != null) { callback.success((T) wrapper.responseBody, wrapper.response); } } }); } catch (final RetrofitError e) { callbackExecutor.execute(new Runnable() { @Override public void run() { if (callback != null) { callback.failure(e); } } }); } }
Source:
<code>public void testReadObjectsWithFailedGet() throws SignatureException, IOException, XmlProcessingException { final Ds3Client ds3Client = Mockito.mock(Ds3Client.class); final Ds3ClientFactory ds3ClientFactory = ds3ClientFactory(ds3Client); Mockito.when(ds3Client.buildFactory(Mockito.<Iterable<Node>>any())).thenReturn(ds3ClientFactory); final BulkGetResponse buildBulkGetResponse = buildBulkGetResponse(); Mockito.when(ds3Client.bulkGet(hasChunkOrdering(ChunkClientProcessingOrderGuarantee.NONE))).thenReturn(buildBulkGetResponse); final GetAvailableJobChunksResponse jobChunksResponse = buildJobChunksResponse2(); Mockito.when(ds3Client.getAvailableJobChunks(hasJobId(jobId))).thenReturn(jobChunksResponse); Mockito.when(ds3Client.getObject(getRequestHas(MYBUCKET, "foo", jobId, 6))).thenThrow(new StubException()); Mockito.when(ds3Client.getObject(getRequestHas(MYBUCKET, "baz", jobId, 6))).then(getObjectAnswer("ntents")); final Job job = Ds3ClientHelpers.wrap(ds3Client).startReadJob(MYBUCKET, Lists.newArrayList( new Ds3Object("foo"), new Ds3Object("bar"), new Ds3Object("baz") )); job.transfer(new ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { return new ByteArraySeekableByteChannel(); } }); <START> Assert.fail("Should have failed with an exception before we got here."); <END> }</code><technical_language>try catch advantage of method call throw exception, I appreciate wanting standard junit of things. I I prefer try-catch leave you. need line 121</technical_language>

Target:
public void testReadObjectsWithFailedGet() throws SignatureException, IOException, XmlProcessingException { final Ds3Client ds3Client = Mockito.mock(Ds3Client.class); final Ds3ClientFactory ds3ClientFactory = ds3ClientFactory(ds3Client); Mockito.when(ds3Client.buildFactory(Mockito.<Iterable<Node>>any())).thenReturn(ds3ClientFactory); final BulkGetResponse buildBulkGetResponse = buildBulkGetResponse(); Mockito.when(ds3Client.bulkGet(hasChunkOrdering(ChunkClientProcessingOrderGuarantee.NONE))).thenReturn(buildBulkGetResponse); final GetAvailableJobChunksResponse jobChunksResponse = buildJobChunksResponse2(); Mockito.when(ds3Client.getAvailableJobChunks(hasJobId(jobId))).thenReturn(jobChunksResponse); Mockito.when(ds3Client.getObject(getRequestHas(MYBUCKET, "foo", jobId, 6))).thenThrow(new StubException()); Mockito.when(ds3Client.getObject(getRequestHas(MYBUCKET, "baz", jobId, 6))).then(getObjectAnswer("ntents")); final Job job = Ds3ClientHelpers.wrap(ds3Client).startReadJob(MYBUCKET, Lists.newArrayList( new Ds3Object("foo"), new Ds3Object("bar"), new Ds3Object("baz") )); job.transfer(new ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { return new ByteArraySeekableByteChannel(); } }); }
Source:
<code>public void setup() throws Exception { httpClientFactory = new HttpClientFactory(); String[] args = new String[] { "-role", "hub", "-type", "sauce", "-host", "localhost", "-servlets", "com.paypal.selion.grid.servlets.LoginServlet,com.paypal.selion.grid.servlets.SauceServlet", }; GridHubConfiguration ghc = GridHubConfiguration.build(args); hub = new Hub(ghc); <START> System.setProperty("selionHome", (new File("src/main/resources")).getAbsolutePath()); <END> }</code><technical_language>a mock here. This break other tests</technical_language>

Target:
public void setup() throws Exception { httpClientFactory = new HttpClientFactory(); String[] args = new String[] { "-role", "hub", "-type", "sauce", "-host", "localhost", "-servlets", "com.paypal.selion.grid.servlets.LoginServlet,com.paypal.selion.grid.servlets.SauceServlet", }; GridHubConfiguration ghc = GridHubConfiguration.build(args); hub = new Hub(ghc); }
Source:
<code>public void refreshVdsStats() { if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vdsManager::refreshVdsStats entered, vds='{}'({})", vds.getName(), vds.getId()); } fetchHostInterfaces(); VDSReturnValue statsReturnValue = getResourceManager().runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(vds)); getResourceManager().getEventListener().updateSchedulingStats(vds); if (!statsReturnValue.getSucceeded() && statsReturnValue.getExceptionObject() != null) { log.error(" Failed getting vds stats, vds='{}'({}): {}", vds.getName(), vds.getId(), statsReturnValue.getExceptionString()); <START> return; <END> } saveVdsDynamic = true; saveVdsStatistics = true; alertIfLowDiskSpaceOnHost(); checkVdsInterfaces(); if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vds::refreshVdsStats\n{0}", this); } }</code><technical_language>i need throw exception.. no? if "recovering" exception? treatment is in caller.. i missing something</technical_language>

Target:
public void refreshVdsStats() { if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vdsManager::refreshVdsStats entered, vds='{}'({})", vds.getName(), vds.getId()); } fetchHostInterfaces(); VDSReturnValue statsReturnValue = getResourceManager().runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(vds)); getVdsEventListener().updateSchedulingStats(vds); if (!statsReturnValue.getSucceeded() && statsReturnValue.getExceptionObject() != null) { log.error(" Failed getting vds stats, vds='{}'({}): {}", vds.getName(), vds.getId(), statsReturnValue.getExceptionString()); return; } saveVdsDynamic = true; saveVdsStatistics = true; alertIfLowDiskSpaceOnHost(); checkVdsInterfaces(); if (Config.<Boolean> getValue(ConfigValues.DebugTimerLogging)) { log.debug("vds::refreshVdsStats\n{0}", this); } }
Source:
<code>public void reset() { if (!initialized) { throw new ISE("Grouper is not initialized"); } if (closed) { throw new ISE("Grouper is closed"); } <START> for (Grouper<KeyType> grouper : groupers) { <END> grouper.reset(); } }</code><technical_language>replace forEach</technical_language>

Target:
public void reset() { if (!initialized) { throw new ISE("Grouper is not initialized"); } if (closed) { throw new ISE("Grouper is closed"); } groupers.forEach(Grouper::reset); }
Source:
<code>public void serialize(T t, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { <START> generateObject(t, jsonGenerator); <END> jsonGenerator.writeObjectFieldStart("tuples"); for(String key : t.keys()) jsonGenerator.writeObjectField(key, t.getAll(key)); jsonGenerator.writeEndObject(); }</code><technical_language>Move jsonGenerator.startObject() method call here, subclasses responsible for creating this. is confusing this way</technical_language>

Target:
public void serialize(T t, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); writeUniqueFields(t, jsonGenerator); jsonGenerator.writeObjectFieldStart("tuples"); for(String key : t.keys()) jsonGenerator.writeObjectField(key, t.getAll(key)); jsonGenerator.writeEndObject(); }
Source:
<code>private Collection<CompilerInput> createEntryPointInputs( DependencyOptions depOptions, List<CompilerInput> inputs, SortedDependencies<CompilerInput> sorter) throws MissingModuleException, MissingProvideException { Set<CompilerInput> entryPointInputs = new LinkedHashSet<>(); Map<String, JSModule> modulesByName = getModulesByName(); if (depOptions.shouldPruneDependencies()) { if (!depOptions.shouldDropMoochers()) { entryPointInputs.addAll(sorter.getInputsWithoutProvides()); } for (DependencyOptions.ModuleIdentifier entryPoint : depOptions.getEntryPoints()) { String inputName = entryPoint.getNormalizedModuleName(); int splitPoint = entryPoint.getNormalizedModuleName().indexOf(':'); CompilerInput entryPointInput = null; try { <START> if (splitPoint != -1) { <END> String moduleName = entryPoint.getNormalizedModuleName().substring(0, splitPoint); inputName = entryPoint.getNormalizedModuleName().substring( Math.min(splitPoint + 1, entryPoint.getNormalizedModuleName().length() - 1)); JSModule module = modulesByName.get(moduleName); if (module == null) { throw new MissingModuleException(moduleName); } else { entryPointInput = sorter.getInputProviding(inputName); entryPointInput.overrideModule(module); } } else { entryPointInput = sorter.getInputProviding(inputName); } } catch (MissingProvideException e) { throw new MissingProvideException(entryPoint.getName()); } entryPointInputs.add(entryPointInput); } CompilerInput baseJs = sorter.maybeGetInputProviding("goog"); if (baseJs != null) { entryPointInputs.add(baseJs); } } else { entryPointInputs.addAll(inputs); } return entryPointInputs; }</code><technical_language>optional: move this parsing logic module identifier</technical_language>

Target:
private Collection<CompilerInput> createEntryPointInputs( DependencyOptions depOptions, List<CompilerInput> inputs, SortedDependencies<CompilerInput> sorter) throws MissingModuleException, MissingProvideException { Set<CompilerInput> entryPointInputs = new LinkedHashSet<>(); Map<String, JSModule> modulesByName = getModulesByName(); if (depOptions.shouldPruneDependencies()) { if (!depOptions.shouldDropMoochers()) { entryPointInputs.addAll(sorter.getInputsWithoutProvides()); } for (DependencyOptions.ModuleIdentifier entryPoint : depOptions.getEntryPoints()) { CompilerInput entryPointInput = null; try { if (entryPoint.getClosureNamespace().equals(entryPoint.getModuleName())) { entryPointInput = sorter.getInputProviding(entryPoint.getClosureNamespace()); } else { JSModule module = modulesByName.get(entryPoint.getModuleName()); if (module == null) { throw new MissingModuleException(entryPoint.getModuleName()); } else { entryPointInput = sorter.getInputProviding(entryPoint.getClosureNamespace()); entryPointInput.overrideModule(module); } } } catch (MissingProvideException e) { throw new MissingProvideException(entryPoint.getName(), e); } entryPointInputs.add(entryPointInput); } CompilerInput baseJs = sorter.maybeGetInputProviding("goog"); if (baseJs != null) { entryPointInputs.add(baseJs); } } else { entryPointInputs.addAll(inputs); } return entryPointInputs; }
Source:
<code>public String toStatement(String statement) { <START> return statementBuilder + statement; <END> }</code><technical_language>buildStatement() called here, removing statementBuilder variable completely (if not, making final a good idea). buildStatement() return a String, StringBuilder. for other builders</technical_language>

Target:
public String toStatement(String statement) { return cteStatement + statement; }
Source:
<code>public Future<JsonRpcResponse> call(JsonRpcRequest req, BrokerCommandCallback callback) throws ClientConnectionException { final Call call = new Call(req, <START> executorService, callback); <END> this.tracker.registerCall(req, call); retryCall(req, call); try { this.getClient().sendMessage(jsonToByteArray(req.toJson())); } finally { retryCall(req, call); } return call; }</code><technical_language>executor in this class this field instead of passing part of call object</technical_language>

Target:
public Future<JsonRpcResponse> call(JsonRpcRequest req, BrokerCommandCallback callback) throws ClientConnectionException { final Call call = new Call(req, callback); this.tracker.registerCall(req, call); retryCall(req, call); try { this.getClient().sendMessage(jsonToByteArray(req.toJson())); } finally { retryCall(req, call); } return call; }
Source:
<code>public Bundle[] getBundles(String symbolicName, String versionRange) { Map<String, String> directives = Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, getRequirementFilter(symbolicName, versionRange)); Collection<BundleCapability> matchingBundleCapabilities = fwkWiring.findProviders(ModuleContainer .createRequirement(IdentityNamespace.IDENTITY_NAMESPACE, directives, Collections.emptyMap())); if (matchingBundleCapabilities.isEmpty()) { return null; } <START> Bundle[] results = matchingBundleCapabilities.stream().map(c -> c.getRevision().getBundle()) .filter(bundle -> (bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) .toArray(Bundle[]::new); <END> return results.length > 0 ? results : null; }</code><technical_language>Bundle[] sorted in descending version order. I guaranteed order</technical_language>

Target:
public Bundle[] getBundles(String symbolicName, String versionRange) { Map<String, String> directives = Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, getRequirementFilter(symbolicName, versionRange)); Collection<BundleCapability> matchingBundleCapabilities = fwkWiring.findProviders(ModuleContainer .createRequirement(IdentityNamespace.IDENTITY_NAMESPACE, directives, Collections.emptyMap())); if (matchingBundleCapabilities.isEmpty()) { return null; } Bundle[] results = matchingBundleCapabilities.stream().map(c -> c.getRevision().getBundle()) .filter(bundle -> (bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) .sorted() .toArray(Bundle[]::new); return results.length > 0 ? results : null; }
Source:
<code>private <R> R readCollectionValue(@Nullable List<?> source, ElasticsearchPersistentProperty property, TypeInformation<R> targetType) { if (source == null) { return null; } Collection<Object> target = createCollectionForValue(targetType, source.size()); for (Object value : source) { <START> if(null == value) return null; <END> if (isSimpleType(value)) { target.add( readSimpleValue(value, targetType.getComponentType() != null ? targetType.getComponentType() : targetType)); } else { if (value instanceof List) { target.add(readValue(value, property, property.getTypeInformation().getActualType())); } else { target.add(readEntity(computeGenericValueTypeForRead(property, value), (Map<String, Object>) value)); } } } return (R) target; }</code><technical_language>suggestion if(value == null) { return null; } do comparison other curly braces</technical_language>

Target:
private <R> R readCollectionValue(@Nullable List<?> source, ElasticsearchPersistentProperty property, TypeInformation<R> targetType) { if (source == null) { return null; } Collection<Object> target = createCollectionForValue(targetType, source.size()); for (Object value : source) { if(value == null) { return null; } if (isSimpleType(value)) { target.add( readSimpleValue(value, targetType.getComponentType() != null ? targetType.getComponentType() : targetType)); } else { if (value instanceof List) { target.add(readValue(value, property, property.getTypeInformation().getActualType())); } else { target.add(readEntity(computeGenericValueTypeForRead(property, value), (Map<String, Object>) value)); } } } return (R) target; }
Source:
<code>public void updated(Dictionary<String, ?> config) throws ConfigurationException { Map<String, GC100IRHost> hosts = new HashMap<String, GC100IRHost>(); <START> Enumeration<String> keys = config.keys(); <END> while (keys.hasMoreElements()) { String key = keys.nextElement(); if ("service.pid".equals(key)) { continue; } String[] parts = key.split("\\."); String hostname = parts[0]; GC100IRHost host = hosts.get(hostname); if (host == null) { host = new GC100IRHost(); } String value = ((String) config.get(key)).trim(); if ("host".equals(parts[1])) { host.setHostname(value); } hosts.put(hostname, host); } nameHostMapper = hosts; registerAllWatches(); }</code><technical_language>I for this method called a null for config parameter. Other bindings check for null it. I notice this earlier</technical_language>

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null) { return; } Map<String, GC100IRHost> hosts = new HashMap<String, GC100IRHost>(); Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if ("service.pid".equals(key)) { continue; } String[] parts = key.split("\\."); String hostname = parts[0]; GC100IRHost host = hosts.get(hostname); if (host == null) { host = new GC100IRHost(); } String value = ((String) config.get(key)).trim(); if ("host".equals(parts[1])) { host.setHostname(value); } hosts.put(hostname, host); } nameHostMapper = hosts; registerAllWatches(); }
Source:
<code>public ASTNode transform(Rule node) throws TransformerException { Term body = node.getBody(); if (body instanceof Rewrite) { body = ((Rewrite) body).getLeft(); } if (body instanceof TermCons) { Production prod = context.conses.get(((TermCons) body).getCons()); if (prod.containsAttribute("function") || prod.containsAttribute("predicate")) { node = addFunction(node); } } if (body instanceof KApp) { Term l = ((KApp) body).getLabel(); if (l instanceof KLabelConstant) { KLabelConstant label = (KLabelConstant) l; if (label.isPredicate()) { node = addFunction(node); <START> } else { <END> List<Production> productions = context.productionsOf(label.getLabel()); Production functionProduction = null; for (Production production : productions) { if (production.containsAttribute("function") || production.containsAttribute("predicate")) { functionProduction = production; } else if (functionProduction != null) { GlobalSettings.kem.register(new KException(KException.ExceptionType.ERROR, KException.KExceptionGroup.CRITICAL, "Ambiguity: Top symbol " + label + " corresponds to both a functional declaration (" + functionProduction + ") and to a non-functional one (" + production + ")", getName(), node.getFilename(), node.getLocation())); } } if (functionProduction != null) { node = addFunction(node); } } } } return node; }</code><technical_language>mimic some kind of label.isFunction method one. Is a reason route</technical_language>

Target:
public ASTNode transform(Rule node) throws TransformerException { Term body = node.getBody(); if (body instanceof Rewrite) { body = ((Rewrite) body).getLeft(); } if (body instanceof TermCons) { Production prod = context.conses.get(((TermCons) body).getCons()); if (prod.containsAttribute("function") || prod.containsAttribute("predicate")) { node = addFunction(node); } } if (body instanceof KApp) { Term l = ((KApp) body).getLabel(); if (l instanceof KLabelConstant) { KLabelConstant label = (KLabelConstant) l; if (label.isFunctional(context)) { node = addFunction(node); } } } return node; }