auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void addField(String name, Object value) { if (name == null) { throw new NullPointerException("name"); } if (value == null) { throw new NullPointerException("value"); } try { if (value instanceof Iterable) { addFieldIterable(name, (Iterable) value); } else if (value.getClass().isArray()) { <START> Iterable arrayAsList = Arrays.asList((Object[]) value); <END> addFieldIterable(name, arrayAsList); } else { addFieldString(name, value.toString()); } } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>This cast fail primitive array. e.g., java new int[] { 1, 2, 3 };</technical_language>

Target:
public void addField(String name, Object value) { if (name == null) { throw new NullPointerException("name"); } if (value == null) { throw new NullPointerException("value"); } try { if (value instanceof Iterable) { addFieldIterable(name, (Iterable) value); } else if (value.getClass().isArray()) { addFieldArray(name, value); } else { addFieldString(name, value.toString()); } } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code><START> Map<String, Object> constructRequestArgs() { <END> Map<String, Object> queryArgs = new HashMap<String, Object>(); if (eventCollection != null) { queryArgs.put(KeenQueryConstants.EVENT_COLLECTION, eventCollection); } if (interval != null) { queryArgs.put(KeenQueryConstants.INTERVAL, interval); } if (groupBy != null) { queryArgs.put(KeenQueryConstants.GROUP_BY, groupBy); } if (maxAge != null) { queryArgs.put(KeenQueryConstants.MAX_AGE, maxAge); } if (targetProperty != null) { queryArgs.put(KeenQueryConstants.TARGET_PROPERTY, targetProperty); } if (percentile != null) { queryArgs.put(KeenQueryConstants.PERCENTILE, percentile); } if (filters != null) { queryArgs.put(KeenQueryConstants.FILTERS, filters.constructParameterRequestArgs()); } if (timeframe != null) { queryArgs.putAll(timeframe.constructTimeframeArgs()); } return queryArgs; }</code><technical_language>generally wrangle in exposed surface area of SDK in parts touched deemed package internal with, yeah a breaking change is a breaking change. Do a strong opinion other this specific change? imply making this a public method KeenQueryRequest abstract base</technical_language>

Target:
Map<String, Object> constructRequestArgs() { Map<String, Object> queryArgs = new HashMap<String, Object>(); if (eventCollection != null) { queryArgs.put(KeenQueryConstants.EVENT_COLLECTION, eventCollection); } if (interval != null) { queryArgs.put(KeenQueryConstants.INTERVAL, interval); } if (timezone != null) { queryArgs.put(KeenQueryConstants.TIMEZONE, timezone); } if (groupBy != null) { queryArgs.put(KeenQueryConstants.GROUP_BY, groupBy); } if (maxAge != null) { queryArgs.put(KeenQueryConstants.MAX_AGE, maxAge); } if (targetProperty != null) { queryArgs.put(KeenQueryConstants.TARGET_PROPERTY, targetProperty); } if (percentile != null) { queryArgs.put(KeenQueryConstants.PERCENTILE, percentile); } if (filters != null) { queryArgs.put(KeenQueryConstants.FILTERS, filters.constructParameterRequestArgs()); } if (timeframe != null) { queryArgs.putAll(timeframe.constructTimeframeArgs()); } return queryArgs; }
Source:
<code>private void checkWeekProfileMapping(final WeekProfile weekProfile) { <START> assertEquals("weekProfile1", weekProfile.getWeekProfileName()); <END> this.checkDayTypeMapping(weekProfile.getSunday()); this.checkDayTypeMapping(weekProfile.getMonday()); this.checkDayTypeMapping(weekProfile.getTuesday()); this.checkDayTypeMapping(weekProfile.getWednesday()); this.checkDayTypeMapping(weekProfile.getThursday()); this.checkDayTypeMapping(weekProfile.getFriday()); this.checkDayTypeMapping(weekProfile.getSaturday()); }</code><technical_language>check if weekProfile is null</technical_language>

Target:
private void checkWeekProfileMapping(final WeekProfile weekProfile) { assertNotNull(weekProfile); assertEquals(WEEKPROFILENAME, weekProfile.getWeekProfileName()); this.checkDayTypeMapping(weekProfile.getSunday()); this.checkDayTypeMapping(weekProfile.getMonday()); this.checkDayTypeMapping(weekProfile.getTuesday()); this.checkDayTypeMapping(weekProfile.getWednesday()); this.checkDayTypeMapping(weekProfile.getThursday()); this.checkDayTypeMapping(weekProfile.getFriday()); this.checkDayTypeMapping(weekProfile.getSaturday()); }
Source:
<code>public void testGenerateToolTipText() throws FileNotFoundException { VirtualFile myFile = myFixture.copyFileToProject("themeEditor/styles_1.xml", "res/values/styles.xml"); myFixture.copyFileToProject("themeEditor/attrs.xml", "res/values/attrs.xml"); <START> ConfigurationManager configurationManager = ConfigurationManager.create(myModule); <END> Configuration configuration = configurationManager.getConfiguration(myFile); ThemeResolver themeResolver = new ThemeResolver(configuration); ThemeEditorStyle theme = themeResolver.getTheme("@style/AppTheme"); assert theme != null; Collection<ItemResourceValue> values = theme.getValues(); assertEquals(values.size(), 6); for (ItemResourceValue item : values) { String doc = ThemeEditorUtils.generateToolTipText(item, myModule, configuration); assertNotNull(doc); compareWithAns(doc, myFixture.getTestDataPath() + "/themeEditor/tooltipDocAns/" + item.getName() + ".ans"); } }</code><technical_language>Get configuration myFacet.getConfigurationManager().getConfiguration(myFile) instead</technical_language>

Target:
public void testGenerateToolTipText() throws FileNotFoundException { VirtualFile myFile = myFixture.copyFileToProject("themeEditor/styles_1.xml", "res/values/styles.xml"); myFixture.copyFileToProject("themeEditor/attrs.xml", "res/values/attrs.xml"); Configuration configuration = myFacet.getConfigurationManager().getConfiguration(myFile); ThemeResolver themeResolver = new ThemeResolver(configuration); ThemeEditorStyle theme = themeResolver.getTheme("@style/AppTheme"); assertNotNull(theme); Collection<ItemResourceValue> values = theme.getValues(); assertEquals(6, values.size()); for (ItemResourceValue item : values) { String doc = ThemeEditorUtils.generateToolTipText(item, myModule, configuration); compareWithAns(doc, myFixture.getTestDataPath() + "/themeEditor/tooltipDocAns/" + item.getName() + ".ans"); } }
Source:
<code>public void addRoutingTableChangeListener( final RoutingTableChangeListener routingTableChangeListener, Object context, boolean isTriggerCallback) { _routingTableChangeListenerMap.put(routingTableChangeListener, new ListenerContext(context)); logger.info("Attach RoutingTableProviderChangeListener {}.", routingTableChangeListener.getClass().getName(), isTriggerCallback); if (isTriggerCallback) { <START> logger.info("The isTriggerCallback value for the listener is true"); <END> final NotificationContext periodicRefreshContext = new NotificationContext(_helixManager); periodicRefreshContext.setType(NotificationContext.Type.PERIODIC_REFRESH); _routerUpdater.queueEvent(periodicRefreshContext, ClusterEventType.PeriodicalRebalance, null); } }</code><technical_language>I meant is log "Force triggering a callback for new listener" here. log care name of parameter "isTriggerCallback"</technical_language>

Target:
public void addRoutingTableChangeListener( final RoutingTableChangeListener routingTableChangeListener, Object context, boolean isTriggerCallback) { _routingTableChangeListenerMap.put(routingTableChangeListener, new ListenerContext(context)); logger.info("Attach RoutingTableProviderChangeListener {}.", routingTableChangeListener.getClass().getName()); if (isTriggerCallback) { logger.info("Force triggering a callback for the new listener in routing table provider"); final NotificationContext periodicRefreshContext = new NotificationContext(_helixManager); periodicRefreshContext.setType(NotificationContext.Type.PERIODIC_REFRESH); _routerUpdater.queueEvent(periodicRefreshContext, ClusterEventType.PeriodicalRebalance, null); } }
Source:
<code>public void mutate(List<Cell> rawList, List<TxnView> txns, List<Cell> results) throws IOException { <START> final boolean dataToReturnIsEmpty = dataToReturn.isEmpty(); final boolean resultsIsEmpty = results.isEmpty(); final boolean maxTombstoneIsNull = maxTombstone == null; final boolean rawListAndTxnListSameSize = rawList.size() == txns.size(); final boolean debugSortCheck = !LOG.isDebugEnabled() || isSorted(rawList); if (!debugSortCheck) { bypassPurge = true; LOG.warn("Skipping tombstone purge. rawList is not sorted."); } if (!dataToReturnIsEmpty) { bypassPurge = true; LOG.warn("Skipping tombstone purge. dataToReturn is not properly initialized."); } if (!resultsIsEmpty) { bypassPurge = true; LOG.warn("Skipping tombstone purge. results list not properly initialized."); } if (!maxTombstoneIsNull) { bypassPurge = true; LOG.warn("Skipping tombstone purge. maxTombstone not properly initialized to null."); } if (!rawListAndTxnListSameSize) { bypassPurge = true; LOG.warn("Skipping tombstone purge. rawList and txn list not the same length."); <END> } assert dataToReturnIsEmpty; assert resultsIsEmpty; assert maxTombstoneIsNull; assert debugSortCheck : "CompactionStateMutate: rawList not sorted"; assert rawListAndTxnListSameSize; try { Iterator<TxnView> it = txns.iterator(); for (Cell aRawList : rawList) { TxnView txn = it.next(); mutate(aRawList, txn); } Stream<Cell> stream = dataToReturn.stream(); if (shouldPurgeDeletes()) stream = stream.filter(not(this::purgeableDeletedRow)); if (shouldPurgeUpdates()) stream = stream.filter(not(this::purgeableOldUpdate)); stream.forEachOrdered(results::add); assert !LOG.isDebugEnabled() || isSorted(results) : "CompactionStateMutate: results not sorted"; } catch (AssertionError e) { LOG.error(e); LOG.error(rawList.toString()); LOG.error(txns.toString()); throw e; } }</code><technical_language>move checks a separate method bring focus logic of method</technical_language>

Target:
public long mutate(List<Cell> rawList, List<TxnView> txns, List<Cell> results) throws IOException { handleSanityChecks(results, rawList, txns); long totalSize = 0; try { Iterator<TxnView> it = txns.iterator(); for (Cell cell : rawList) { totalSize += KeyValueUtil.length(cell); TxnView txn = it.next(); mutate(cell, txn); } Stream<Cell> stream = dataToReturn.stream(); if (shouldPurgeDeletes()) stream = stream.filter(not(this::purgeableDeletedRow)); if (shouldPurgeUpdates()) stream = stream.filter(not(this::purgeableOldUpdate)); stream.forEachOrdered(results::add); final boolean debugSortCheck = !LOG.isDebugEnabled() || isSorted(results); if (!debugSortCheck) setBypassPurgeWithWarning("CompactionStateMutate: results not sorted."); assert debugSortCheck : "CompactionStateMutate: results not sorted"; return totalSize; } catch (AssertionError e) { LOG.error(e); LOG.error(rawList.toString()); LOG.error(txns.toString()); throw e; } }
Source:
<code>public void populateKeyFields() <START> { <END> this.keys = keyFieldStr.split(","); }</code><technical_language>is this public? usage i is in populateFields() is private</technical_language>

Target:
private void populateKeyFields() { leftStore.setKeys(keyFieldStr.split(",")[0]); rightStore.setKeys(keyFieldStr.split(",")[1]); }
Source:
<code>private Set<SitemapEvent> constructSitemapEvents(Item item, List<Widget> widgets) { Set<SitemapEvent> events = new HashSet<>(); for (Widget w : widgets) { if (w instanceof Frame) { events.addAll(constructSitemapEvents(item, itemUIRegistry.getChildren((Frame) w))); } if (w.getItem() != null && w.getItem().equals(item.getName())) { boolean skipWidget = false; if (w instanceof Chart) { Chart chartWidget = (Chart) w; skipWidget = chartWidget.getRefresh() > 0; } <START> if (!skipWidget || definesVisibility(w, item.getName())) { <END> SitemapWidgetEvent event = new SitemapWidgetEvent(); event.sitemapName = sitemapName; event.pageId = pageId; event.label = itemUIRegistry.getLabel(w); event.labelcolor = itemUIRegistry.getLabelColor(w); event.valuecolor = itemUIRegistry.getValueColor(w); event.widgetId = itemUIRegistry.getWidgetId(w); event.visibility = itemUIRegistry.getVisiblity(w); String widgetTypeName = w.eClass().getInstanceTypeName() .substring(w.eClass().getInstanceTypeName().lastIndexOf(".") + 1); boolean drillDown = "mapview".equalsIgnoreCase(widgetTypeName); Predicate<Item> itemFilter = (i -> i.getType().equals(CoreItemFactory.LOCATION)); event.item = EnrichedItemDTOMapper.map(item, drillDown, itemFilter, null, null); event.state = itemUIRegistry.getState(w).toFullString(); if (event.state != null && event.state.equals(event.item.state)) { event.state = null; } events.add(event); } } } return events; }</code><technical_language>visibility for a chart widget checked in chart specific block (lines 198 - 201)? chart widget receive frequent updates defining a visibility rule</technical_language>

Target:
private Set<SitemapEvent> constructSitemapEvents(Item item, List<Widget> widgets) { Set<SitemapEvent> events = new HashSet<>(); for (Widget w : widgets) { if (w instanceof Frame) { events.addAll(constructSitemapEvents(item, itemUIRegistry.getChildren((Frame) w))); } if (w.getItem() != null && w.getItem().equals(item.getName())) { boolean skipWidget = false; if (w instanceof Chart) { Chart chartWidget = (Chart) w; skipWidget = chartWidget.getRefresh() > 0; } if (!skipWidget || definesVisibilityOrColor(w, item.getName())) { SitemapWidgetEvent event = new SitemapWidgetEvent(); event.sitemapName = sitemapName; event.pageId = pageId; event.label = itemUIRegistry.getLabel(w); event.labelcolor = itemUIRegistry.getLabelColor(w); event.valuecolor = itemUIRegistry.getValueColor(w); event.widgetId = itemUIRegistry.getWidgetId(w); event.visibility = itemUIRegistry.getVisiblity(w); String widgetTypeName = w.eClass().getInstanceTypeName() .substring(w.eClass().getInstanceTypeName().lastIndexOf(".") + 1); boolean drillDown = "mapview".equalsIgnoreCase(widgetTypeName); Predicate<Item> itemFilter = (i -> i.getType().equals(CoreItemFactory.LOCATION)); event.item = EnrichedItemDTOMapper.map(item, drillDown, itemFilter, null, null); event.state = itemUIRegistry.getState(w).toFullString(); if (event.state != null && event.state.equals(event.item.state)) { event.state = null; } events.add(event); } } } return events; }
Source:
<code><START> public static LockManager getInstance() { <END> if (lockManager == null) { lockManager = new LockManager(); } return lockManager; }</code><technical_language>Race condition, multiple instances constructed once</technical_language>

Target:
public static LockManager getInstance() { return lockManager; }
Source:
<code>protected boolean canDoAction() { boolean returnValue = CanRemoveVds(getVdsId(), getReturnValue().getCanDoActionMessages()); storage_pool storagePool = getStoragePoolDAO().getForVds(getParameters().getVdsId()); if (returnValue && storagePool != null && storagePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!getStorageDomainDAO().getAllForStoragePool(storagePool.getId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_WITH_LOCAL_STORAGE); returnValue = false; } } if (isGlusterEnabled() && hasVolumeOnServer()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); <START> return false; <END> } addCanDoActionMessage(VdcBllMessages.VAR__ACTION__REMOVE); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__HOST); return returnValue; }</code><technical_language>this method is written in a 'single return point' way, (means set returanValue false instead of return here) refactor method multiple return points. please, if choose refactor, in a separate patch change this patch is doing</technical_language>

Target:
protected boolean canDoAction() { boolean returnValue = CanRemoveVds(getVdsId(), getReturnValue().getCanDoActionMessages()); storage_pool storagePool = getStoragePoolDAO().getForVds(getParameters().getVdsId()); if (returnValue && storagePool != null && storagePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!getStorageDomainDAO().getAllForStoragePool(storagePool.getId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_WITH_LOCAL_STORAGE); returnValue = false; } } if (isGlusterEnabled() && hasVolumeOnServer()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); returnValue = false; } addCanDoActionMessage(VdcBllMessages.VAR__ACTION__REMOVE); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__HOST); return returnValue; }
Source:
<code><START> private List<?> findMissingTokens() { <END> return configuration.getAccessTokenConfigurations() .stream() .map(AccessTokenConfiguration::getTokenId) .filter(tokenId -> !accessTokens.containsKey(tokenId)) .collect(toList()); }</code><technical_language>Technically, a breaking change</technical_language>

Target:
protected List<?> findMissingTokens() { return configuration.getAccessTokenConfigurations() .stream() .map(AccessTokenConfiguration::getTokenId) .filter(tokenId -> !accessTokens.containsKey(tokenId)) .collect(toList()); }
Source:
<code>protected static SagaLifecycle getInstance() { SagaLifecycle instance = Scope.getCurrentScope(); <START> if (instance == null) { <END> throw new IllegalStateException("Cannot retrieve current SagaLifecycle; none is yet defined"); } return instance; }</code><technical_language>This happen (instance == null), getCurrentScope throw exception Scope defined/set</technical_language>

Target:
protected static SagaLifecycle getInstance() { return Scope.getCurrentScope(); }
Source:
<code>protected String generateSequenceName( Map<Integer, Long> startPartitions, Optional<DateTime> minimumMessageTime, Optional<DateTime> maximumMessageTime ) { <START> int groupId = getTaskGroupIdForPartition(startPartitions.keySet().iterator().next()); <END> ImmutableMap<Integer, Long> partitionOffsets = ImmutableMap.of(groupId, (long) groupId); final TaskGroup taskGroup = new TaskGroup( partitionOffsets, minimumMessageTime, maximumMessageTime ); return generateSequenceName(taskGroup); }</code><technical_language>Suggest change this method this: java @Override protected String generateSequenceName( Map<Integer, Long> startPartitions, Optional<DateTime> minimumMessageTime, Optional<DateTime> maximumMessageTime ) { final int groupId = getTaskGroupIdForPartition(startPartitions.keySet().iterator().next()); return StringUtils.format("sequenceName-%d", groupId); }</technical_language>

Target:
protected String generateSequenceName( Map<Integer, Long> startPartitions, Optional<DateTime> minimumMessageTime, Optional<DateTime> maximumMessageTime ) { final int groupId = getTaskGroupIdForPartition(startPartitions.keySet().iterator().next()); return StringUtils.format("sequenceName-%d", groupId); }
Source:
<code>public boolean store(Checkpoint checkpoint) { Path path = new Path(getCheckpointPath(checkpoint)); <START> if (!ensureDirExists(getCheckpointDir(checkpoint))) { <END> LOG.warning("Failed to ensure dir exists: " + getCheckpointDir(checkpoint)); return false; } FSDataOutputStream out = null; try { out = fileSystem.create(path); checkpoint.checkpoint().writeTo(out); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to persist", e); return false; } finally { SysUtils.closeIgnoringExceptions(out); } return true; }</code><technical_language>this part of initialization fail start failing checkpoint</technical_language>

Target:
public void store(Checkpoint checkpoint) throws StatefulStorageException { Path path = new Path(getCheckpointPath(checkpoint.getTopologyName(), checkpoint.getCheckpointId(), checkpoint.getComponent(), checkpoint.getTaskId())); String checkpointDir = getCheckpointDir(checkpoint.getTopologyName(), checkpoint.getCheckpointId(), checkpoint.getComponent()); createDir(checkpointDir); FSDataOutputStream out = null; try { out = fileSystem.create(path); checkpoint.getCheckpoint().writeTo(out); } catch (IOException e) { throw new StatefulStorageException("Failed to persist", e); } finally { SysUtils.closeIgnoringExceptions(out); } }
Source:
<code>private void closeRecordManager() { if (recMan != null) { try { recMan.close(); } catch (IOException e1) { <START> <END> } } }</code><technical_language>don t log here</technical_language>

Target:
private void closeRecordManager() { if (recMan != null) { try { recMan.close(); } catch (IOException e1) { log.trace("Error when closing record manager", e1); } } }
Source:
<code>public synchronized void initScanner() throws SQLException { if (closed) { return; } ResultIterator delegate = this.scanIterator; if (delegate == UNINITIALIZED_SCANNER) { try { this.scanIterator = new ScanningResultIterator(htable.getScanner(scan), scanMetrics); } catch (IOException e) { <START> if(handleSplitRegionBoundaryFailureDuringInitialization) { <END> try { throw ServerUtil.parseServerException(e); } catch(StaleRegionBoundaryCacheException s) { if(scan.getAttribute(NON_AGGREGATE_QUERY)!=null) { plan.getContext().getConnection().getQueryServices().clearTableRegionCache(htable.getTableName()); this.scanIterator = plan.iterator(DefaultParallelScanGrouper.getInstance(), scan); } } } else { Closeables.closeQuietly(htable); throw ServerUtil.parseServerException(e); } } } }</code><technical_language>a handleSplitRegionBoundaryFailureDuringInitialization, work throw caller deal it? a variable name 50 characters, a sign special of a case. :-)</technical_language>

Target:
public synchronized void initScanner() throws SQLException { if (closed) { return; } ResultIterator delegate = this.scanIterator; if (delegate == UNINITIALIZED_SCANNER) { try { this.scanIterator = new ScanningResultIterator(htable.getScanner(scan), scanMetrics); } catch (IOException e) { Closeables.closeQuietly(htable); throw ServerUtil.parseServerException(e); } } }
Source:
<code>public Map<String, Set<String>> recognise(String text) { Map<String, Set<String>> entities = new HashMap<>(); try { <START> int port = 8881; <END> String url = restHostUrlStr + "/nltk"; Response response = WebClient.create(url).post(text); int responseCode = response.getStatus(); if (responseCode == 200) { String result = response.readEntity(String.class); JSONParser parser = new JSONParser(); JSONObject j = (JSONObject) parser.parse(result); Set s = entities.put("NAMES", new HashSet((Collection) j.get("names"))); } } catch (Exception e) { LOG.debug(e.getMessage(), e); } ENTITY_TYPES.clear(); ENTITY_TYPES.addAll(entities.keySet()); return entities; }</code><technical_language>unused variable, remove</technical_language>

Target:
public Map<String, Set<String>> recognise(String text) { Map<String, Set<String>> entities = new HashMap<>(); try { String url = restHostUrlStr + "/nltk"; Response response = WebClient.create(url).accept(MediaType.TEXT_HTML).post(text); int responseCode = response.getStatus(); if (responseCode == 200) { String result = response.readEntity(String.class); JSONParser parser = new JSONParser(); JSONObject j = (JSONObject) parser.parse(result); Set s = entities.put("NAMES", new HashSet((Collection) j.get("names"))); } } catch (Exception e) { LOG.debug(e.getMessage(), e); } ENTITY_TYPES.clear(); ENTITY_TYPES.addAll(entities.keySet()); return entities; }
Source:
<code>public List<ExtensionEntry> getProvidedExtensions(String provides) { List<ExtensionEntry> results = new ArrayList<>(); for (ExtensionEntry entry : loadedEntries.values()) { <START> if (entry.getProvides().contains(provides)) { <END> results.add(entry); } } return results; }</code><technical_language>entry.isActivated() &&</technical_language>

Target:
public List<ExtensionEntry> getProvidedExtensions(String provides) { List<ExtensionEntry> results = new ArrayList<>(); for (ExtensionEntry entry : loadedEntries.values()) { if (entry.getProvides().contains(provides) && entry.isActivated()) { results.add(entry); } } return results; }
Source:
<code>private List<String> tableOptParser(JSONArray raw) { List<String> ret = new ArrayList<>(); if(raw == null || raw.length() == 0) { return ret; } for(int i = 0 ; i < raw.length() ; i++) { String s = ""; try { s = raw.getString(i).trim().toUpperCase(); } catch (JSONException e) { e.printStackTrace(); } <START> if(s.length() > 0) <END> ret.add(s.toString()); } return ret; }</code><technical_language>Add braces line</technical_language>

Target:
private List<String> tableOptParser(JSONArray raw) { List<String> ret = new ArrayList<>(); if(raw == null || raw.length() == 0) { return ret; } for(int i = 0 ; i < raw.length() ; i++) { try { String s = raw.getString(i).trim().toUpperCase(); if(s.length() > 0) { ret.add(s.toString()); } } catch (JSONException e) { throw new RuntimeException(e.getMessage()); } } return ret; }
Source:
<code>protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests(authz -> authz .anyRequest().authenticated() ) <START> .saml2Login(saml2 -> {}); <END> }</code><technical_language>Customizer#withDefaultslooks more readable me</technical_language>

Target:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests(authz -> authz .anyRequest().authenticated() ) .saml2Login(withDefaults()); }
Source:
<code>public Principal authenticate(String username, String password) throws SecurityException { AuthorizingCallbackHandler handler = securityRealm.getAuthorizingCallbackHandler(AuthMechanism.PLAIN); NameCallback ncb = new NameCallback("name", username); ncb.setName(username); VerifyPasswordCallback vpcb = new VerifyPasswordCallback(password); try { handler.handle(new Callback[] { ncb, vpcb }); } catch (Exception e) { <START> } <END> if (vpcb.isVerified()) { try { SubjectUserInfo subjectUserInfo = handler.createSubjectUserInfo(Collections.singletonList(new SimpleUserPrincipal(username))); return Security.getSubjectUserPrincipal(subjectUserInfo.getSubject()); } catch (IOException e) { throw new SecurityException("Invalid credentials", e); } } else throw new SecurityException("Invalid credentials"); }</code><technical_language>log least</technical_language>

Target:
public Principal authenticate(String username, String password) throws SecurityException { AuthorizingCallbackHandler handler = securityRealm.getAuthorizingCallbackHandler(AuthMechanism.PLAIN); NameCallback ncb = new NameCallback("name", username); ncb.setName(username); VerifyPasswordCallback vpcb = new VerifyPasswordCallback(password); try { handler.handle(new Callback[] { ncb, vpcb }); } catch (Exception e) { ROOT_LOGGER.authenticationError(e); } if (vpcb.isVerified()) { try { SubjectUserInfo subjectUserInfo = handler.createSubjectUserInfo(Collections.singletonList(new SimpleUserPrincipal(username))); return Security.getSubjectUserPrincipal(subjectUserInfo.getSubject()); } catch (IOException e) { throw new SecurityException("Invalid credentials", e); } } else throw new SecurityException("Invalid credentials"); }
Source:
<code>public void infersFromKnownVersionStrings() { <START> Arrays.stream(AtlasDbHttpProtocolVersion.values()) <END> .forEach(value -> { Optional<String> protocolVersionString = Optional.of(value.getProtocolVersionString()); assertThat(AtlasDbHttpProtocolVersion.inferFromString(protocolVersionString)) .isEqualTo(value); }); }</code><technical_language>prefer if this written out explicitly for AtlasDbHttpProtocolVersion</technical_language>

Target:
public void infersFromKnownVersionStrings() { Stream.of(AtlasDbHttpProtocolVersion.LEGACY_OR_UNKNOWN, AtlasDbHttpProtocolVersion.CONJURE_JAVA_RUNTIME) .forEach(value -> { Optional<String> protocolVersionString = Optional.of(value.getProtocolVersionString()); assertThat(AtlasDbHttpProtocolVersion.inferFromString(protocolVersionString)) .isEqualTo(value); }); }
Source:
<code><START> String getBuilder() default "get*Builder"; <END> String setBuilder() default "set*Builder"; String addBuilder() default "add*Builder"; String addAllBuilder() default "addAll*Builder"; String getBuilderList() default "get*BuilderList"; public enum ImplementationVisibility { PUBLIC, SAME, @Deprecated SAME_NON_RETURNED, PACKAGE, PRIVATE }</code><technical_language>I prefer default *Builder" here: default, attribute initializers do set prefixes this ok</technical_language>

Target:
String getBuilder() default "*Builder"; String setBuilder() default "*Builder"; String addBuilder() default "add*Builder"; String addAllBuilder() default "addAll*Builder"; String getBuilderList() default "*Builders"; public enum ImplementationVisibility { PUBLIC, SAME, @Deprecated SAME_NON_RETURNED, PACKAGE, PRIVATE }
Source:
<code>public String generateMatcher() { String output = new String(); final int numConstants = this.enumConstants.size(); for (int currentIndex = 0; currentIndex < numConstants; currentIndex++) { <START> output += " "; <END> if (currentIndex > 0) { output += "} else "; } final String currentEnumString = this.enumConstants.get(currentIndex).getName(); output += "if (xmlStrcmp(text, (const xmlChar*) \"" + currentEnumString + "\") == 0) {" + System.lineSeparator(); output += " return " + currentEnumString + ";" + System.lineSeparator(); } output += " } else {" + System.lineSeparator(); output += " ds3_log_message(log, DS3_ERROR, \"ERROR: Unknown " + getNameUnderscores() + " value of '%s'. Returning " + getEnumConstants().get(0).getName() + " for safety." + System.lineSeparator(); output += " " + "return " + getEnumConstants().get(0).getName() + ";" + System.lineSeparator(); output += " }" + System.lineSeparator(); return output; }</code><technical_language>CHelper.indent(1) (if public) lessen likelihood of mismatched indentations generated code</technical_language>

Target:
public String generateMatcher() { final StringBuilder outputBuilder = new StringBuilder(); final int numConstants = this.enumConstants.size(); for (int currentIndex = 0; currentIndex < numConstants; currentIndex++) { outputBuilder.append(CHelper.indent(1)); if (currentIndex > 0) { outputBuilder.append("} else "); } final String currentEnumString = this.enumConstants.get(currentIndex).getName(); outputBuilder.append("if (xmlStrcmp(text, (const xmlChar*) \"").append(currentEnumString).append("\") == 0) {").append(System.lineSeparator()); outputBuilder.append(CHelper.indent(2)).append("return ").append(currentEnumString).append(";").append(System.lineSeparator()); } outputBuilder.append(CHelper.indent(1)).append("} else {").append(System.lineSeparator()); outputBuilder.append(CHelper.indent(2)).append("ds3_log_message(log, DS3_ERROR, \"ERROR: Unknown ").append(getNameUnderscores()).append(" value of '%s'. Returning ").append(getEnumConstants().get(0).getName()).append(" for safety.").append(System.lineSeparator()); outputBuilder.append(CHelper.indent(2)).append("return ").append(getEnumConstants().get(0).getName()).append(";").append(System.lineSeparator()); outputBuilder.append(CHelper.indent(1)).append("}").append(System.lineSeparator()); return outputBuilder.toString(); }
Source:
<code>public static String getFailureMessage(Job failedJob, ObjectMapper jsonMapper) { try { Map<String, String> taskDiagsMap = Maps.newHashMap(); TaskCompletionEvent[] completionEvents = failedJob.getTaskCompletionEvents(0, 100); for (TaskCompletionEvent tce : completionEvents) { String[] taskDiags = failedJob.getTaskDiagnostics(tce.getTaskAttemptId()); String combinedTaskDiags = ""; for (String taskDiag : taskDiags) { combinedTaskDiags += taskDiag; } taskDiagsMap.put(tce.getTaskAttemptId().toString(), combinedTaskDiags); } return jsonMapper.writeValueAsString(taskDiagsMap); } catch (IOException | InterruptedException ie) { <START> log.error("couldn't get failure cause for job."); <END> return null; } }</code><technical_language>Please add exception job name log message</technical_language>

Target:
public static String getFailureMessage(Job failedJob, ObjectMapper jsonMapper) { try { Map<String, String> taskDiagsMap = Maps.newHashMap(); TaskCompletionEvent[] completionEvents = failedJob.getTaskCompletionEvents(0, 100); for (TaskCompletionEvent tce : completionEvents) { String[] taskDiags = failedJob.getTaskDiagnostics(tce.getTaskAttemptId()); String combinedTaskDiags = ""; for (String taskDiag : taskDiags) { combinedTaskDiags += taskDiag; } taskDiagsMap.put(tce.getTaskAttemptId().toString(), combinedTaskDiags); } return jsonMapper.writeValueAsString(taskDiagsMap); } catch (IOException | InterruptedException ie) { log.error(ie, "couldn't get failure cause for job [%s]", failedJob.getJobName()); return null; } }
Source:
<code>public Response tokenRequest(JwtPayload payload) { hiveValidator.validate(payload); JwtTokenVO responseTokenVO = new JwtTokenVO(); UserVO user = userService.findById(payload.getUserId()); if (user == null) { <START> logger.warn("JwtToken: User with specified id was not found"); <END> return ResponseFactory .response(Response.Status.BAD_REQUEST, new ErrorResponse(BAD_REQUEST.getStatusCode(), Messages.INVALID_REQUEST_PARAMETERS)); } if (!user.getStatus().equals(UserStatus.ACTIVE)) { logger.warn("JwtToken: User with specified id is not active"); return ResponseFactory .response(Response.Status.BAD_REQUEST, new ErrorResponse(BAD_REQUEST.getStatusCode(), Messages.INVALID_REQUEST_PARAMETERS)); } logger.debug("JwtToken: generate access and refresh token"); responseTokenVO.setAccessToken(tokenService.generateJwtAccessToken(payload)); responseTokenVO.setRefreshToken(tokenService.generateJwtRefreshToken(payload)); return ResponseFactory.response(CREATED, responseTokenVO, JsonPolicyDef.Policy.JWT_REFRESH_TOKEN_SUBMITTED); }</code><technical_language>print user Id well</technical_language>

Target:
public Response tokenRequest(JwtPayload payload) { hiveValidator.validate(payload); JwtTokenVO responseTokenVO = new JwtTokenVO(); UserVO user = userService.findById(payload.getUserId()); if (user == null) { logger.warn("JwtToken: User with specified id was not found", payload.getUserId()); return ResponseFactory .response(Response.Status.BAD_REQUEST, new ErrorResponse(BAD_REQUEST.getStatusCode(), Messages.INVALID_REQUEST_PARAMETERS)); } if (!user.getStatus().equals(UserStatus.ACTIVE)) { logger.warn("JwtToken: User with specified id is not active", payload.getUserId()); return ResponseFactory .response(Response.Status.BAD_REQUEST, new ErrorResponse(BAD_REQUEST.getStatusCode(), Messages.INVALID_REQUEST_PARAMETERS)); } logger.debug("JwtToken: generate access and refresh token"); responseTokenVO.setAccessToken(tokenService.generateJwtAccessToken(payload)); responseTokenVO.setRefreshToken(tokenService.generateJwtRefreshToken(payload)); return ResponseFactory.response(CREATED, responseTokenVO, JsonPolicyDef.Policy.JWT_REFRESH_TOKEN_SUBMITTED); }
Source:
<code><START> public static GeometryType getGeometryType(Slice shape) <END> { GeometrySerializationType serType = deserializeType(shape); switch (serType) { case POINT: return GeometryType.POINT; case LINE_STRING: return GeometryType.LINE_STRING; case POLYGON: case ENVELOPE: return GeometryType.POLYGON; case MULTI_POINT: return GeometryType.MULTI_POINT; case MULTI_LINE_STRING: return GeometryType.MULTI_LINE_STRING; case MULTI_POLYGON: return GeometryType.MULTI_POLYGON; case GEOMETRY_COLLECTION: return GeometryType.GEOMETRY_COLLECTION; default: throw new IllegalArgumentException("Unexpected type: " + serType); } }</code><technical_language>This function anywhere</technical_language>

Target:
public static GeometryType getGeometryType(Slice shape) { return deserializeType(shape).geometryType(); }
Source:
<code>public void testBloomFilterVirtualColumn() throws Exception { BloomKFilter filter = new BloomKFilter(1500); filter.addString("a-foo"); filter.addString("-foo"); if (!NullHandling.replaceWithDefault()) { filter.addBytes(null, 0, 0); } byte[] bytes = BloomFilterSerializersModule.bloomKFilterToBytes(filter); <START> String base64 = Base64.encodeBase64String(bytes); <END> testQuery( StringUtils.format("SELECT COUNT(*) FROM druid.foo WHERE bloom_filter_test(concat(dim2, '-foo'), '%s')", base64), ImmutableList.of( Druids.newTimeseriesQueryBuilder() .dataSource(CalciteTests.DATASOURCE1) .intervals(QSS(Filtration.eternity())) .granularity(Granularities.ALL) .virtualColumns() .filters( new ExpressionDimFilter( StringUtils.format("bloom_filter_test(concat(\"dim2\",'-foo'),'%s')", base64), createExprMacroTable() ) ) .aggregators(AGGS(new CountAggregatorFactory("a0"))) .context(TIMESERIES_CONTEXT_DEFAULT) .build() ), ImmutableList.of( new Object[]{5L} ) ); }</code><technical_language>same, java.util.Base64.getEncoder().encodeToString(bytes) better</technical_language>

Target:
public void testBloomFilterVirtualColumn() throws Exception { BloomKFilter filter = new BloomKFilter(1500); filter.addString("a-foo"); filter.addString("-foo"); if (!NullHandling.replaceWithDefault()) { filter.addBytes(null, 0, 0); } byte[] bytes = BloomFilterSerializersModule.bloomKFilterToBytes(filter); String base64 = StringUtils.encodeBase64String(bytes); testQuery( StringUtils.format("SELECT COUNT(*) FROM druid.foo WHERE bloom_filter_test(concat(dim2, '-foo'), '%s')", base64), ImmutableList.of( Druids.newTimeseriesQueryBuilder() .dataSource(CalciteTests.DATASOURCE1) .intervals(QSS(Filtration.eternity())) .granularity(Granularities.ALL) .virtualColumns() .filters( new ExpressionDimFilter( StringUtils.format("bloom_filter_test(concat(\"dim2\",'-foo'),'%s')", base64), createExprMacroTable() ) ) .aggregators(AGGS(new CountAggregatorFactory("a0"))) .context(TIMESERIES_CONTEXT_DEFAULT) .build() ), ImmutableList.of( new Object[]{5L} ) ); }
Source:
<code><START> public FileBasedConfig openUserConfig(Config parent, FS fs) { <END> File home = fs.userHome(); userConfig.compareAndSet(null, new FileBasedConfig(parent, new File(home, ".gitconfig"), fs)); return userConfig.get(); }</code><technical_language>do null check</technical_language>

Target:
public FileBasedConfig openUserConfig(Config parent, FS fs) { FileBasedConfig c = userConfig.get(); if (c == null) { File home = fs.userHome(); userConfig.compareAndSet(null, new FileBasedConfig(parent, new File(home, ".gitconfig"), fs)); c = userConfig.get(); } return c; }
Source:
<code>private List<String> tsConfigs(SensorContext context) { if (tsconfigs == null) { Optional<String> tsConfigProperty = context.config().get(JavaScriptPlugin.TSCONFIG_PATH); if (tsConfigProperty.isPresent()) { Path tsconfig = Paths.get(tsConfigProperty.get()); tsconfig = tsconfig.isAbsolute() ? tsconfig : context.fileSystem().baseDir().toPath().resolve(tsconfig); if (!tsconfig.toFile().exists()) { <START> String msg = format("Provided tsconfig.json path doesn't exists. Path: '%s'", tsconfig); <END> LOG.error(msg); throw new IllegalStateException(msg); } tsconfigs = Collections.singletonList(tsconfig.toString()); LOG.info("Using from property", tsconfig, JavaScriptPlugin.TSCONFIG_PATH); } else { tsconfigs = lookupTsConfig(context); LOG.info("Found " + tsconfigs.size() + " tsconfig.json files: " + tsconfigs); } } return tsconfigs; }</code><technical_language>Typo in exists</technical_language>

Target:
private List<String> tsConfigs(SensorContext context) throws IOException { if (tsconfigs == null) { Optional<String> tsConfigProperty = context.config().get(JavaScriptPlugin.TSCONFIG_PATH); if (tsConfigProperty.isPresent()) { Path tsconfig = Paths.get(tsConfigProperty.get()); tsconfig = tsconfig.isAbsolute() ? tsconfig : context.fileSystem().baseDir().toPath().resolve(tsconfig); if (!tsconfig.toFile().exists()) { String msg = format("Provided tsconfig.json path doesn't exist. Path: '%s'", tsconfig); LOG.error(msg); throw new IllegalStateException(msg); } tsconfigs = Collections.singletonList(tsconfig.toString()); LOG.info("Using from property", tsconfig, JavaScriptPlugin.TSCONFIG_PATH); } else { tsconfigs = lookupTsConfig(context); LOG.info("Found " + tsconfigs.size() + " tsconfig.json file(s): " + tsconfigs); } } return tsconfigs; }
Source:
<code>public void notifyChanged(Notification notification) { StackedchartsPackage pckg = StackedchartsPackage.eINSTANCE; <START> Object feature = notification.getFeature(); <END> ArrayList<EAttribute> visualUpdates = new ArrayList<EAttribute>(); visualUpdates.add(pckg.getChart_Name()); visualUpdates.add(pckg.getStyling_LineStyle()); visualUpdates.add(pckg.getStyling_LineThickness()); visualUpdates.add(pckg.getStyling_MarkerSize()); visualUpdates.add(pckg.getStyling_MarkerStyle()); visualUpdates.add(pckg.getPlainStyling_Color()); for (final EAttribute thisA : visualUpdates) { if (feature == thisA) { refreshVisuals(); break; } } ArrayList<EReference> childrenUpdates = new ArrayList<EReference>(); childrenUpdates.add(pckg.getChart_MaxAxes()); childrenUpdates.add(pckg.getChart_MinAxes()); for (final EReference thisA : childrenUpdates) { if (feature == thisA) { refreshChildren(); break; } } }</code><technical_language>@dinkoivanov - I trouble scanning feature types in _if_ construct. But, I realise test for PlainStyling_Color missing. I of alternate strategy for _if_ construct easier scan features. implementation inferior performance of: - implementation drops out soon a match is (the equality comparisons called) - implementation **refreshChildren** test if **refreshVisuals** called. But, this method called UI change, UI changes many, times longer performance costs above. If of alternate representation is more architecturally attractive, I welcome thoughts</technical_language>

Target:
public void notifyChanged(Notification notification) { Object feature = notification.getFeature(); for (final EAttribute thisA : _visualUpdates) { if (feature == thisA) { refreshVisuals(); break; } } for (final EReference thisA : _childrenUpdates) { if (feature == thisA) { refreshChildren(); break; } } }
Source:
<code>public static void main(String[] args) throws NoFatWarDeploymentSupportedException { <START> throw new NoFatWarDeploymentSupportedException(); <END> }</code><technical_language>So, delete this line try run discussed in #124 (but support officially)</technical_language>

Target:
public static void main(String[] args) { SpringApplication.run(SelfAdministration.class, args); }
Source:
<code>public void testConcurrentAccess() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("MultiTasker", "314 Littleton Rd, Westford, MA 01886", 500); assertEquals(sfsb1.queryEmployeeNameNoTX(500),"MultiTasker"); final int numThreads = 10; <START> ExecutorService executorService = Executors.newFixedThreadPool(numThreads); <END> Future[] results = new Future[numThreads]; for(int i = 0; i < numThreads; ++i) { results[i] = executorService.submit(new CallingClass()); } for(int i = 0; i < numThreads; ++i) { results[i].get(); } }</code><technical_language>This injected ManagedExecutorService. this ExecutorService needs shutdown</technical_language>

Target:
public void testConcurrentAccess() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("MultiTasker", "314 Littleton Rd, Westford, MA 01886", 500); assertEquals(sfsb1.queryEmployeeNameNoTX(500),"MultiTasker"); final int numThreads = 10; ExecutorService executorService = Executors.newFixedThreadPool(numThreads); Future[] results = new Future[numThreads]; for(int i = 0; i < numThreads; ++i) { results[i] = executorService.submit(new CallingClass()); } for(int i = 0; i < numThreads; ++i) { results[i].get(); } executorService.shutdown(); }
Source:
<code>public String scheduleAOneTimeJob(Object instance, String methodName, Class<?>[] inputTypes, <START> Object[] inputParams, <END> long initialDelay, TimeUnit timeUnit) { String jobName = generateUniqueNameForInstance(instance, methodName); JobDetail job = new JobDetail(jobName, Scheduler.DEFAULT_GROUP, JobWrapper.class); JobDataMap data = job.getJobDataMap(); setBasicMapValues(data, instance, methodName, inputTypes, inputParams); Date runTime = getFutureDate(initialDelay, timeUnit); String triggerName = generateUniqueNameForInstance(instance, TRIGGER_PREFIX); SimpleTrigger trigger = new SimpleTrigger(triggerName, Scheduler.DEFAULT_GROUP, runTime); try { sched.scheduleJob(job, trigger); } catch (SchedulerException se) { log.error("failed to schedule job", se); } return jobName; }</code><technical_language>is a lot more duplication factored out. Additionally methods - creating a job scheduling it. I consider refactoring based separating actions</technical_language>

Target:
public String scheduleAOneTimeJob(Object instance, String methodName, Class<?>[] inputTypes, Object[] inputParams, long initialDelay, TimeUnit timeUnit) { JobDetail job = createJobWithBasicMapValues(instance, methodName, inputTypes, inputParams); SimpleTrigger trigger = createSimpleTrigger(initialDelay, timeUnit, instance); try { sched.scheduleJob(job, trigger); } catch (SchedulerException se) { log.error("failed to schedule job", se); } return job.getName(); }
Source:
<code>protected Control createDialogArea(Composite parent) { final Composite composite = (Composite) super.createDialogArea(parent); composite.setLayout(new GridLayout(2, false)); getShell().setText( changeCredentials ? UIText.LoginDialog_changeCredentials : UIText.LoginDialog_login); Label uriLabel = new Label(composite, SWT.NONE); uriLabel.setText(UIText.LoginDialog_repository); Text uriText = new Text(composite, SWT.READ_ONLY); uriText.setText(uri.toString()); Label userLabel = new Label(composite, SWT.NONE); userLabel.setText(UIText.LoginDialog_user); if (isUserSet) { user = new Text(composite, SWT.BORDER | SWT.READ_ONLY); user.setText(uri.getUser()); <START> } else { <END> user = new Text(composite, SWT.BORDER); } GridDataFactory.fillDefaults().grab(true, false).applyTo(user); Label passwordLabel = new Label(composite, SWT.NONE); passwordLabel.setText(UIText.LoginDialog_password); password = new Text(composite, SWT.PASSWORD | SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(password); if (isUserSet) password.setFocus(); else user.setFocus(); return composite; }</code><technical_language>braces single line blocks</technical_language>

Target:
protected Control createDialogArea(Composite parent) { final Composite composite = (Composite) super.createDialogArea(parent); composite.setLayout(new GridLayout(2, false)); getShell().setText( changeCredentials ? UIText.LoginDialog_changeCredentials : UIText.LoginDialog_login); Label uriLabel = new Label(composite, SWT.NONE); uriLabel.setText(UIText.LoginDialog_repository); Text uriText = new Text(composite, SWT.READ_ONLY); uriText.setText(uri.toString()); Label userLabel = new Label(composite, SWT.NONE); userLabel.setText(UIText.LoginDialog_user); if (isUserSet) { user = new Text(composite, SWT.BORDER | SWT.READ_ONLY); user.setText(uri.getUser()); } else user = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(user); Label passwordLabel = new Label(composite, SWT.NONE); passwordLabel.setText(UIText.LoginDialog_password); password = new Text(composite, SWT.PASSWORD | SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(password); if (isUserSet) password.setFocus(); else user.setFocus(); return composite; }