auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<Project.NameKey> getAllParents(final Project.NameKey projectName) { final List<Project.NameKey> parents = new ArrayList<Project.NameKey>(); Project.NameKey p = projectName; <START> while (p != null && !parents.contains(p)) { <END> final ProjectState e = projectCache.get(p); if (e == null) { break; } p = getParentName(e.getProject()); if (p != null) { parents.add(p); } } return parents; }</code><technical_language>This !parents.add(p) instead of !contains eliminate line 222. eliminate double lookup potentially detect a parent loop step earlier (I a parent points original project)</technical_language>

Target:
private List<Project.NameKey> getAllParents(final Project.NameKey projectName) { final List<Project.NameKey> parents = new ArrayList<Project.NameKey>(); Project.NameKey p = projectName; while (p != null && parents.add(p)) { final ProjectState e = projectCache.get(p); if (e == null) { break; } p = getParentName(e.getProject()); } return parents; }
Source:
<code>public KijiCell<T> next() { KijiCell<T> cell = null; <START> while (mKVs.hasNext() && null == cell) { <END> try { KeyValue kv = mKVs.next(); final KijiColumnName colName = mColumnNameTranslator.toKijiColumnName( new HBaseColumnName(kv.getFamily(), kv.getQualifier())); if (colName.getFamily().equals(mFamily)) { mNumVersions += 1; cell = new KijiCell<T>(mFamily, colName.getQualifier(), kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } } catch (IOException ex) { throw new KijiIOException(ex.getMessage()); } } return cell; }</code><technical_language>This feels convoluted me: drop cell variable, "return new KijiCell" loop. I missing something</technical_language>

Target:
public KijiCell<T> next() { while (mKVs.hasNext()) { try { KeyValue kv = mKVs.next(); final KijiColumnName colName = mColumnNameTranslator.toKijiColumnName( new HBaseColumnName(kv.getFamily(), kv.getQualifier())); if (colName.getFamily().equals(mFamily)) { mNumVersions += 1; return new KijiCell<T>(mFamily, colName.getQualifier(), kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } } catch (IOException ex) { throw new KijiIOException(ex); } } return null; }
Source:
<code>public void restoreSnapshot(PeriodSnapshot s) { synchronized (coreLock) { if (s.getId() != getId()) { return; } if (getCurrentJam() != s.getCurrentJam()) { set(Value.CURRENT_JAM, s.getCurrentJam()); <START> getLast(NChild.JAM).unlink(); <END> } } }</code><technical_language>jam moved, deleted. Deleting remove lineups entered for jam</technical_language>

Target:
public void restoreSnapshot(PeriodSnapshot s) { synchronized (coreLock) { if (s.getId() != getId()) { return; } if (getCurrentJam() != s.getCurrentJam()) { remove(NChild.JAM, getCurrentJam()); set(Value.CURRENT_JAM, s.getCurrentJam()); } } }
Source:
<code>public void union() { NumberExpression<Integer> one = Expressions.ONE; NumberExpression<Integer> two = Expressions.TWO; NumberExpression<Integer> three = Expressions.THREE; Path<Integer> col1 = Expressions.path(Integer.class,"col1"); Union union = query.union( select(one.as(col1)), select(two), select(three)); if (templates.getDummyTable() == null) { assertEquals( <START> "select 1 as col1\n" + <END> "union\n" + "select 2\n" + "union\n" + "select 3", union.toString()); } else { String dummyTable = templates.getDummyTable(); assertEquals( "select 1 as col1 from " + dummyTable + "\n" + "union\n" + "select 2 from " + dummyTable + "\n" + "union\n" + "select 3 from " + dummyTable, union.toString()); } }</code><technical_language>this changed in subclass, test failures alternatively parametrize</technical_language>

Target:
public void union() { NumberExpression<Integer> one = Expressions.ONE; NumberExpression<Integer> two = Expressions.TWO; NumberExpression<Integer> three = Expressions.THREE; Path<Integer> col1 = Expressions.path(Integer.class,"col1"); Union union = query.union( select(one.as(col1)), select(two), select(three)); if (templates.getDummyTable() == null) { if (templates.isUnionsWrapped()) { assertEquals( "(select 1 as col1)\n" + "union\n" + "(select 2)\n" + "union\n" + "(select 3)", union.toString()); } else { assertEquals( "select 1 as col1)\n" + "union\n" + "select 2\n" + "union\n" + "select 3", union.toString()); } } else { String dummyTable = templates.getDummyTable(); if (templates.isUnionsWrapped()) { assertEquals( "(select 1 as col1 from " + dummyTable + ")\n" + "union\n" + "(select 2 from " + dummyTable + ")\n" + "union\n" + "(select 3 from " + dummyTable + ")", union.toString()); } else { assertEquals( "select 1 as col1 from " + dummyTable + "\n" + "union\n" + "select 2 from " + dummyTable + "\n" + "union\n" + "select 3 from " + dummyTable, union.toString()); } } }
Source:
<code>public static JsonValue makeRequest(String url) throws IOException { long startTime = 0; HttpClient httpClient = new DefaultHttpClient(); try { HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); InputStream in = entity.getContent(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { <START> throw new IOException("The status code for " + url + " is not OK (200). It's " + statusCode); <END> } try { JsonValue response = JsonValue.readFrom(new InputStreamReader( in)); return response; } catch (ParseException e) { throw new IOException(e); } } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } finally { httpClient.getConnectionManager().shutdown(); } }</code><technical_language>put messages property bundle properly localized</technical_language>

Target:
public static JsonValue makeRequest(String url) throws IOException { long startTime = 0; HttpClient httpClient = new DefaultHttpClient(); try { HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); InputStream in = entity.getContent(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { } try { JsonValue response = JsonValue.readFrom(new InputStreamReader( in)); return response; } catch (ParseException e) { throw new IOException(e); } } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } finally { httpClient.getConnectionManager().shutdown(); } }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); RevCommit commit = getSelectedCommit(event, repository); <START> if (commit != null) { <END> try { CommitEditor.open(new RepositoryCommit(repository, commit)); } catch (PartInitException e) { Activator.showError("Error opening commit viewer", e); } } return null; }</code><technical_language>Style nit: curlies needed</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); RevCommit commit = getSelectedCommit(event, repository); if (commit != null) CommitEditor.openQuiet((new RepositoryCommit(repository, commit))); return null; }
Source:
<code>public String asCql() { StringBuilder builder = new StringBuilder("UPDATE "); CqlHelper.qualify(keyspace, table, builder); if (timestamp != null) { builder.append(" USING TIMESTAMP "); if (timestamp instanceof BindMarker) { ((BindMarker) timestamp).appendTo(builder); } else { builder.append(timestamp); } } if (ttl != null) { <START> builder.append(" USING TTL "); <END> if (ttl instanceof BindMarker) { ((BindMarker) ttl).appendTo(builder); } else { builder.append(ttl); } } CqlHelper.append(assignments, builder, " SET ", ", ", null); CqlHelper.append(relations, builder, " WHERE ", " AND ", null); if (ifExists) { builder.append(" IF EXISTS"); } else { CqlHelper.append(conditions, builder, " IF ", " AND ", null); } return builder.toString(); }</code><technical_language>here, need check if clauses present append if required</technical_language>

Target:
public String asCql() { StringBuilder builder = new StringBuilder("UPDATE "); CqlHelper.qualify(keyspace, table, builder); if (timestamp != null) { builder.append(" USING TIMESTAMP "); if (timestamp instanceof BindMarker) { ((BindMarker) timestamp).appendTo(builder); } else { builder.append(timestamp); } } if (ttlInSeconds != null) { builder.append((timestamp != null) ? " AND " : " USING ").append("TTL "); if (ttlInSeconds instanceof BindMarker) { ((BindMarker) ttlInSeconds).appendTo(builder); } else { builder.append(ttlInSeconds); } } CqlHelper.append(assignments, builder, " SET ", ", ", null); CqlHelper.append(relations, builder, " WHERE ", " AND ", null); if (ifExists) { builder.append(" IF EXISTS"); } else { CqlHelper.append(conditions, builder, " IF ", " AND ", null); } return builder.toString(); }
Source:
<code>protected void createCacheManagers() throws Throwable { cchf = new ControlledConsistentHashFactory.Default(new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 0}}); configBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configBuilder.clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES); configBuilder.clustering().hash().numSegments(4).stateTransfer().timeout(30000); globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); <START> globalBuilder.serialization().addAdvancedExternalizer(2500, new JGroupsAddress.Externalizer()); <END> }</code><technical_language>id for reading, id Externalizer.getId() for writing</technical_language>

Target:
protected void createCacheManagers() throws Throwable { cchf = new ControlledConsistentHashFactory.Default(new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 0}}); configBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configBuilder.clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES); configBuilder.clustering().hash().numSegments(4).stateTransfer().timeout(30000); globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalBuilder.serialization().addAdvancedExternalizer(JBossUserMarshaller.USER_EXT_ID_MIN, new JGroupsAddress.Externalizer()); }
Source:
<code>private List<Pair<String, String>> getSignalParams(Entry<Signal, Operation> signal) { List<Pair<String, String>> ret = new ArrayList<Pair<String, String>>(); for (Parameter param : signal.getValue().getOwnedParameters().stream() <START> .filter(p -> !p.getType().getName().equals(signal.getKey().getName())).collect(Collectors.toList())) { <END> ret.add(new Pair<String, String>(param.getType().getName(), param.getName())); } return ret; }</code><technical_language>I a variable introduced for this long expression</technical_language>

Target:
private List<Pair<String, String>> getSignalParams(Entry<Signal, Operation> signal) { List<Pair<String, String>> ret = new ArrayList<Pair<String, String>>(); List<Parameter> selfFilteredParameters = signal.getValue().getOwnedParameters().stream() .filter(p -> !p.getType().getName().equals(signal.getKey().getName())).collect(Collectors.toList()); for (Parameter param : selfFilteredParameters) { ret.add(new Pair<String, String>(param.getType().getName(), param.getName())); } return ret; }
Source:
<code>public LocalCluster(String jarFileName, List<String> regexes, int siteCount, int hostCount, int kfactor, BackendTarget target) { this(jarFileName, siteCount, hostCount, kfactor, target, null); m_hasLocalServer = false; m_regexResults = new ConcurrentHashMap<>(); m_regexes = new ConcurrentHashMap<>(); for (int i = 0; i < regexes.size(); i++) { String s = regexes.get(i); Pattern p = Pattern.compile(s); m_regexes.put(s, p); } for (int i = 0; i < hostCount; i++) { <START> m_regexResults.put(i, new ConcurrentHashSet<>()); <END> } }</code><technical_language>This initialization is needed care of in startOne()</technical_language>

Target:
public LocalCluster(String jarFileName, List<String> regexes, int siteCount, int hostCount, int kfactor, BackendTarget target) { this(jarFileName, siteCount, hostCount, kfactor, target, null); m_hasLocalServer = false; m_logMessageMatchResults = new ConcurrentHashMap<>(); m_logMessageMatchPatterns = new ConcurrentHashMap<>(); for (int i = 0; i < regexes.size(); i++) { String s = regexes.get(i); Pattern p = Pattern.compile(s); m_logMessageMatchPatterns.put(s, p); } }
Source:
<code><START> private static boolean proxyHolderContainsHost(ProxyHolder holder, String uriString) { <END> return holder != null && (holder.getProxyMap().containsKey(uriString) || holder.getProxyMap().containsKey(uriString.substring(0, uriString.indexOf(":")))); }</code><technical_language>is reason of this method static</technical_language>

Target:
private static boolean proxyHolderContainsHost(ProxyHolder holder, String uriString) { return holder != null && (holder.getProxyMap().containsKey(uriString) || (uriString.contains(":") && holder.getProxyMap().containsKey(uriString.substring(0, uriString.indexOf(":"))))); }
Source:
<code>public void onCompletedTasksListToggled(boolean isExpanded) { if (!mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { <START> return; <END> } toggleCompletedView(!isExpanded); }</code><technical_language>Exiting early flatten multiple nested if statements simplify a complex conditional statement. In this case, nested statements early exit is slightly more complicated not. do this? java @Override public void onCompletedTasksListToggled(boolean isExpanded) { if (mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { toggleCompletedView(!isExpanded); } }</technical_language>

Target:
public void onCompletedTasksListToggled(boolean isExpanded) { if (mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { toggleCompletedView(!isExpanded); } }
Source:
<code>public void rawSampleBuilderWithSingleInputYieldsThatInputWithInfiniteRate() throws IOException { Points<SimpleNumber> input = new Points<SimpleNumber>(); input.add(new Points.Point<SimpleNumber>(1234L, new SimpleNumber(3L))); BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromRawSamples(input); Number count = rollup.getCount(); assertNotNull(count); assertThat(count, is(CoreMatchers.<Number>instanceOf(Long.class))); assertEquals(3L, count.longValue()); <START> assertEquals(Double.POSITIVE_INFINITY, rollup.getRate(), 0.00001d); END> assertEquals(1, rollup.getSampleCount()); }</code><technical_language>Wait what? test for infinity? is getRate() returning infinity here</technical_language>

Target:
public void rawSampleBuilderWithSingleInputYieldsThatInputWithInfiniteRate() throws IOException { Points<SimpleNumber> input = new Points<SimpleNumber>(); input.add(new Points.Point<SimpleNumber>(1234L, new SimpleNumber(3L))); BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromRawSamples(input); Number count = rollup.getCount(); assertNotNull(count); assertThat(count, is(CoreMatchers.<Number>instanceOf(Long.class))); assertEquals(3L, count.longValue()); assertTrue(Double.isInfinite(rollup.getRate())); assertTrue(rollup.getRate() > 0); assertEquals(1, rollup.getSampleCount()); }
Source:
<code>protected void execute() { if(execThread.getState() == State.NEW) { <START> log.debug("Starting exec thread"); <END> this.execThread.start(); } if(this.completionLocks != null) { Set<ScriptedCommandCompletionLock> locksToRemove = new HashSet<>(); for(ScriptedCommandCompletionLock lock : this.completionLocks) { if(lock.updateLock()) { log.debug("Found lock to remove: " + lock.toString()); locksToRemove.add(lock); } } if(!locksToRemove.isEmpty()) { log.debug("Removing " + locksToRemove.size() + " locks"); completionLocks.removeAll(locksToRemove); } } }</code><technical_language>Good info level, I</technical_language>

Target:
public void execute() { if(execThread != null && execThread.getState() == State.NEW) { log.info("Starting exec thread"); this.execThread.start(); } if(execThread != null && this.completionLocks != null) { Set<ScriptedCommandCompletionLock> locksToRemove = new HashSet<>(); for(ScriptedCommandCompletionLock lock : this.completionLocks) { if(lock.updateLock()) { log.debug("Found lock to remove: " + lock.toString()); locksToRemove.add(lock); } } if(!locksToRemove.isEmpty()) { log.info("Removing " + locksToRemove.size() + " locks"); completionLocks.removeAll(locksToRemove); } } }
Source:
<code>public static void setRobolectricPackageManager(RobolectricPackageManager newPackageManager) { <START> if (packageManager != null) packageManager.reset(); <END> packageManager = newPackageManager; }</code><technical_language>braces conditionals, I results in clearer code</technical_language>

Target:
public static void setRobolectricPackageManager(RobolectricPackageManager newPackageManager) { if (packageManager != null) { packageManager.reset(); } packageManager = newPackageManager; }
Source:
<code>public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.equals(customApiUrlPref) && newValue instanceof String) { String apiUrl = (String) newValue; if (!TextUtils.isEmpty(apiUrl)) { Application.get().setCurrentRegion(null); if (BuildConfig.DEBUG) { Log.d(TAG, "User entered new API URL, set region to null."); } } else { if (BuildConfig.DEBUG) { Log.d(TAG, "User entered blank API URL, re-initializing regions..."); } NavHelp.goHome(this); } } else if (preference.equals(analyticsPref) && newValue instanceof Boolean) { Boolean isAnalyticsActive = (Boolean) newValue; if (!isAnalyticsActive) ObaAnalytics.reportEventWithCategory(ObaAnalytics.ObaEventCategory.APP_SETTINGS.toString(), getString(R.string.analytics_action_edit_general), getString(R.string.analytics_label_analytic_preference) <START> + (isAnalyticsActive ? "YES" : "NO")); <END> } return true; }</code><technical_language>@cagryInside please add dispatchLocalHits() reporting this event? flush existing analytics info here, analytics continuing report (e.g., in 30 min) user opted-out. found, I guess this work devices Google Play Services, effort consistent user's wishes. And, if Google Play Services decides support this in future, set</technical_language>

Target:
public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.equals(customApiUrlPref) && newValue instanceof String) { String apiUrl = (String) newValue; if (!TextUtils.isEmpty(apiUrl)) { Application.get().setCurrentRegion(null); if (BuildConfig.DEBUG) { Log.d(TAG, "User entered new API URL, set region to null."); } } else { if (BuildConfig.DEBUG) { Log.d(TAG, "User entered blank API URL, re-initializing regions..."); } NavHelp.goHome(this); } } else if (preference.equals(analyticsPref) && newValue instanceof Boolean) { Boolean isAnalyticsActive = (Boolean) newValue; if (!isAnalyticsActive) { ObaAnalytics.reportEventWithCategory(ObaAnalytics.ObaEventCategory.APP_SETTINGS.toString(), getString(R.string.analytics_action_edit_general), getString(R.string.analytics_label_analytic_preference) + (isAnalyticsActive ? "YES" : "NO")); GoogleAnalytics.getInstance(getBaseContext()).dispatchLocalHits(); } } return true; }
Source:
<code>public void pairWithPin(String pin) { mySignerId = JPAKE_SIGNERID_SENDER; theirSignerId = JPAKE_SIGNERID_RECEIVER; jParty = new JPakeParty(mySignerId); secret = pin.substring(0, JPAKE_LENGTH_SECRET); channel = pin.substring(JPAKE_LENGTH_SECRET); channelUrl = jpakeServer + channel; <START> prepareStagesAndStartWithPin(true); <END> }</code><technical_language><pre> prepareSenderStages(); start(); </pre> <tt>start()</tt> resets stage counter calls <tt>runNextStage()</tt></technical_language>

Target:
public void pairWithPin(String pin) { mySignerId = JPAKE_SIGNERID_SENDER; theirSignerId = JPAKE_SIGNERID_RECEIVER; jParty = new JPakeParty(mySignerId); secret = pin.substring(0, JPAKE_LENGTH_SECRET); channel = pin.substring(JPAKE_LENGTH_SECRET); channelUrl = jpakeServer + channel; prepareSenderStages(); runNextStage(); }
Source:
<code>private boolean shouldValidateBillingPeriodDateRange(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { <START> String frequencyCode = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getAward().getBillingFrequency().getFrequency(); <END> if (StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.LETTER_OF_CREDIT) || StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.PREDETERMINED_BILLING) || StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.MILESTONE)) { if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateBillingPeriodDateRange, the billing frequency '" + frequencyCode + "' should NOT require validation of billing period date range "); } return false; } else { if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateBillingPeriodDateRange, the billing frequency '" + frequencyCode + "' should require validation of billing period date range "); } return true; } }</code><technical_language>null checks refreshReferenceObject() calls needed of objects in this method chain</technical_language>

Target:
private boolean shouldValidateBillingPeriodDateRange(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { String frequencyCode = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getBillingFrequencyCode(); if (StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.LETTER_OF_CREDIT) || StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.PREDETERMINED_BILLING) || StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.MILESTONE)) { if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateBillingPeriodDateRange, the billing frequency '" + frequencyCode + "' should NOT require validation of billing period date range "); } return false; } else { if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateBillingPeriodDateRange, the billing frequency '" + frequencyCode + "' should require validation of billing period date range "); } return true; } }
Source:
<code>public SqlStatements define(String key, Object value) { if (value != null) { attributes.put(key, value); <START> } <END> return this; }</code><technical_language>remove(key) if == null</technical_language>

Target:
public SqlStatements define(String key, Object value) { if (value == null) { attributes.remove(key); } else { attributes.put(key, value); } return this; }
Source:
<code>public AsyncFuture<Void> sendMetrics(Collection<Metric> metrics) { final UUID traceId = UUID.randomUUID(); logger.info("{}: Start sending metrics", traceId); for (Metric metric : metrics) { try { final ApiFuture<String> publish; if (writeCache.isCached(metric)) { publish = ApiFutures.immediateFuture("Metric in cache"); } else { publish = publisher.publish(PubsubMessage.newBuilder() .setData(ByteString.copyFrom(serializer.serialize(metric))) .build() ); } <START> ApiFutures.addCallback(publish, new ApiFutureCallback<String>() { <END> @Override public void onFailure(Throwable t) { logger.error("Failed sending metrics {}", t.getMessage()); writeCache.remove(metric); } @Override public void onSuccess(String messageId) { } }, executorService); } catch (Exception e) { logger.error("Failed to publish metric {}", e); } } logger.info("{}: Finished sending metrics", traceId); return async.resolved(); }</code><technical_language>async callbacks relevant real publishes/cache misses, easier read if add publishPubSub function (with cache changes of course). loop in sendMetrics is starting get large messy</technical_language>

Target:
public AsyncFuture<Void> sendMetrics(Collection<Metric> metrics) { logger.debug("Sending metrics", metrics.size()); try { final ByteString m = ByteString.copyFrom(serializer.serialize(metrics, writeCache)); publishPubSub(m); } catch (Exception e) { logger.error("Failed to serialize batch of metrics {}", e); } return async.resolved(); }
Source:
<code><START> private Map<String, BasicAuthenticatorUser> loadUserMapFromDisk(String prefix) throws Exception <END> { File userMapFile = new File(commonCacheConfig.getCacheDirectory(), getUserMapFilename(prefix)); if (!userMapFile.exists()) { return null; } return objectMapper.readValue( userMapFile, BasicAuthUtils.AUTHENTICATOR_USER_MAP_TYPE_REFERENCE ); }</code><technical_language>reduced throws IOException</technical_language>

Target:
private Map<String, BasicAuthenticatorUser> loadUserMapFromDisk(String prefix) throws IOException { File userMapFile = new File(commonCacheConfig.getCacheDirectory(), getUserMapFilename(prefix)); if (!userMapFile.exists()) { return null; } return objectMapper.readValue( userMapFile, BasicAuthUtils.AUTHENTICATOR_USER_MAP_TYPE_REFERENCE ); }
Source:
<code><START> public static IConsole[] findConsole(IRemoteConnection connection) { <END> ArrayList<IConsole> ret = new ArrayList<IConsole>(); IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager(); IConsole[] consoles = consoleManager.getConsoles(); boolean[] indices = new boolean[consoles.length]; for (IConsole console : consoles) { if (console instanceof TerminalConsole) { TerminalConsole terminalConsole = (TerminalConsole) console; if (terminalConsole.getConnection().equals(connection)) { ret.add(terminalConsole); } } } return (IConsole[]) ret.toArray(new IConsole[ret.size()]); }</code><technical_language>return List<IConsole></technical_language>

Target:
public static List<IConsole> findConsole(IRemoteConnection connection) { ArrayList<IConsole> ret = new ArrayList<IConsole>(); IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager(); IConsole[] consoles = consoleManager.getConsoles(); for (IConsole console : consoles) { if (console instanceof TerminalConsole) { TerminalConsole terminalConsole = (TerminalConsole) console; if (terminalConsole.getConnection().equals(connection)) { ret.add(terminalConsole); } } } return ret; }
Source:
<code>protected static List<ReferenceWithSentimentLabels> convertCitationSentiment(CharSequence publicationId, List<ReferenceMetadata> references, List<CitationSentiment> sentiments) { Preconditions.checkArgument(references.size() != sentiments.size(), "number of sentiments: " + sentiments.size() <START> + " is not equal the number of input references: " + references.size()); <END> List<ReferenceWithSentimentLabels> results = new ArrayList<ReferenceWithSentimentLabels>(references.size()); for (int i = 0; i < references.size(); i++) { ReferenceWithSentimentLabels result = convertCitationSentiment(publicationId, references.get(i), sentiments.get(i)); if (result != null) { results.add(result); } } return results; }</code><technical_language>Please Preconditions.checkArgument(references.size() != sentiments.size(), "number of sentiments: %s is equal number of input references: %s", sentiments.size(), references.size()), string constructed time method is called. I a problem this ended in a huge performance hit</technical_language>

Target:
protected static List<ReferenceWithSentimentLabels> convertCitationSentiment(CharSequence publicationId, List<ReferenceMetadata> references, List<CitationSentiment> sentiments) { Preconditions.checkArgument(references.size() != sentiments.size(), "number of sentiments: %s is not equal the number of input references: %s", sentiments.size(), references.size()); List<ReferenceWithSentimentLabels> results = new ArrayList<ReferenceWithSentimentLabels>(references.size()); for (int i = 0; i < references.size(); i++) { ReferenceWithSentimentLabels result = convertCitationSentiment(publicationId, references.get(i), sentiments.get(i)); if (result != null) { results.add(result); } } return results; }
Source:
<code>public Set<Long> getUserItems(long userId) { if (Context.getPermissionsManager() != null) { Set<Long> result = new HashSet<>(); for (long deviceId : Context.getPermissionsManager().getDevicePermissions(userId)) { <START> Device device = Context.getIdentityManager().getById(deviceId); <END> if (device != null && !device.getDisabled()) { result.add(deviceId); } } return result; } else { return new HashSet<>(); } }</code><technical_language>Do need getIdentityManager here? in DeviceManager</technical_language>

Target:
public Set<Long> getUserItems(long userId) { if (Context.getPermissionsManager() != null) { Set<Long> result = new HashSet<>(); for (long deviceId : Context.getPermissionsManager().getDevicePermissions(userId)) { Device device = getById(deviceId); if (device != null && !device.getDisabled()) { result.add(deviceId); } } return result; } else { return new HashSet<>(); } }
Source:
<code>private static void notify(final String title, final String subtitle, NotificationType type) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { <START> Notification start = new Notification(PantsConstants.PANTS, PantsIcons.Icon, title, subtitle, null, type, null); <END> Notifications.Bus.notify(start); } }); }</code><technical_language>reason for a api for new Notification</technical_language>

Target:
private void notify(final String title, final String subtitle, NotificationType type) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Notification start = new Notification(PantsConstants.PANTS, PantsIcons.Icon, title, subtitle, null, type, null); Notifications.Bus.notify(start); } }); }
Source:
<code>MediaPlayer createMediaPlayer(Context ctx) { if (isUiThread()) { return new MediaPlayer(); } mplayerCreated_ = false; mediaPlayer_ = null; Handler mainHandler = new Handler(ctx.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { synchronized(lock1_) { try { mediaPlayer_ = new MediaPlayer(); Log.e(TAG, "media player created"); } finally { mplayerCreated_ = true; lock1_.notifyAll(); } } } }; mainHandler.post(myRunnable); try { synchronized(lock1_) { <START> while(mplayerCreated_ == false) { <END> lock1_.wait(); } } }catch (InterruptedException e){ Log.e(TAG, "Cought exception", e); } return mediaPlayer_; }</code><technical_language>here, Thread mainLooper is on, lead a race condition block runnable (mediaPlayer-producer) executed? (I if thread loopers message queues.)</technical_language>

Target:
MediaPlayer createMediaPlayer(Context ctx) { if (isUiThread()) { return new MediaPlayer(); } mplayerCreated_ = false; mediaPlayer_ = null; Handler mainHandler = new Handler(ctx.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { synchronized(lock1_) { try { mediaPlayer_ = new MediaPlayer(); Log.i(TAG, "media player created"); } finally { mplayerCreated_ = true; lock1_.notifyAll(); } } } }; mainHandler.post(myRunnable); try { synchronized(lock1_) { while(mplayerCreated_ == false) { lock1_.wait(); } } }catch (InterruptedException e){ Log.e(TAG, "Cought exception", e); } return mediaPlayer_; }
Source:
<code>private int distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); final int fromEnd; if (whereIam == null) { <START> fromEnd = Integer.MAX_VALUE;} <END> else { final Segment activeSeg = Route.journey().activeSegment(); fromEnd = activeSeg.distanceFromEnd(whereIam); } return fromEnd; }</code><technical_language>here: 1. Integer.MAX_VALUE a magic number, instead of (arguably more logical) null a lack of location fix? (You need change return type Integer object int primitive.) 2. Formatting. Yuck! 3. return if branch; do else branch, return inline instead of a fromEnd variable</technical_language>

Target:
private Integer distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); if (whereIam != null) { final Segment activeSeg = Route.journey().activeSegment(); return activeSeg.distanceFromEnd(whereIam); } return null; }
Source:
<code>public void leaveTree(CssRootNode root) { <START> String remaining = Generator.escape(sb.toString()); <END> masterStringBuilder.append(remaining).append("\")"); super.leaveTree(root); }</code><technical_language>This escape call sense concat function below, _also_ escapes contents adds. get a string written in java write more strings written in java..</technical_language>

Target:
public void leaveTree(CssRootNode root) { masterStringBuilder.append(flushInternalStringBuilder()).append(")"); super.leaveTree(root); }
Source:
<code>public BundleMessagesRequestDto mapAllActions(final BundleMessageRequest bundleMessageDataContainer, final SmartMeter smartMeter) throws FunctionalException { final List<ActionDto> actionValueObjectDtoList = new ArrayList<>(); for (ActionRequest action : bundleMessageDataContainer.getBundleList()) { @SuppressWarnings("unchecked") final CustomValueToDtoConverter<ActionRequest, ActionRequestDto> customValueToDtoConverter = (CustomValueToDtoConverter<ActionRequest, ActionRequestDto>) CUSTOM_CONVERTER_FOR_CLASS .get(action.getClass()); if (customValueToDtoConverter != null) { actionValueObjectDtoList.add(new ActionDto(customValueToDtoConverter.convert(action, smartMeter))); } else { final ConfigurableMapper mapper = CLASS_TO_MAPPER_MAP.get(action.getClass()); final Class<? extends ActionRequestDto> clazz = CLASS_MAP.get(action.getClass()); if (mapper != null) { <START> if (action instanceof MBusActionRequest) { <END> action = this.verifyAndFindChannelForMBusRequest((MBusActionRequest) action, smartMeter); } actionValueObjectDtoList.add(new ActionDto(this.performDefaultMapping(action, mapper, clazz))); } else { throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.DOMAIN_SMART_METERING, new AssertionError("No mapper defined for class: " + clazz.getName())); } } } return new BundleMessagesRequestDto(actionValueObjectDtoList); }</code><technical_language>MBus -> Mbus for applicable elements</technical_language>

Target:
public BundleMessagesRequestDto mapAllActions(final BundleMessageRequest bundleMessageDataContainer, final SmartMeter smartMeter) throws FunctionalException { final List<ActionDto> actionValueObjectDtoList = new ArrayList<>(); for (ActionRequest action : bundleMessageDataContainer.getBundleList()) { @SuppressWarnings("unchecked") final CustomValueToDtoConverter<ActionRequest, ActionRequestDto> customValueToDtoConverter = (CustomValueToDtoConverter<ActionRequest, ActionRequestDto>) CUSTOM_CONVERTER_FOR_CLASS .get(action.getClass()); if (customValueToDtoConverter != null) { actionValueObjectDtoList.add(new ActionDto(customValueToDtoConverter.convert(action, smartMeter))); } else { final ConfigurableMapper mapper = CLASS_TO_MAPPER_MAP.get(action.getClass()); final Class<? extends ActionRequestDto> clazz = CLASS_MAP.get(action.getClass()); if (mapper != null) { if (action instanceof MbusActionRequest) { action = this.verifyAndFindChannelForMbusRequest((MbusActionRequest) action, smartMeter); } actionValueObjectDtoList.add(new ActionDto(this.performDefaultMapping(action, mapper, clazz))); } else { throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.DOMAIN_SMART_METERING, new AssertionError("No mapper defined for class: " + clazz.getName())); } } } return new BundleMessagesRequestDto(actionValueObjectDtoList); }
Source:
<code>public boolean verifyDigitalSignature( InputStream data, InputStream signature, String certificateAlias) throws IOException, CatalogCommandRuntimeException { byte[] sigToVerify = IOUtils.toByteArray(signature); Certificate certificate = getCertificate(certificateAlias); if (certificate == null) { throw new CatalogCommandRuntimeException(""); } try (BufferedInputStream bufferedInputStream = new BufferedInputStream(data)) { Signature rsa = Signature.getInstance("SHA256withRSA"); rsa.initVerify(certificate); byte[] buffer = new byte[BUFFER_SIZE]; int len; while (bufferedInputStream.available() != 0) { len = bufferedInputStream.read(buffer); rsa.update(buffer, OFFSET, len); } return rsa.verify(sigToVerify); } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) { <START> String message = "An error occurred while signing file"; <END> LOGGER.debug(message, e); throw new CatalogCommandRuntimeException(message, e); } }</code><technical_language>worthwhile add a more descriptive error message</technical_language>

Target:
public boolean verifyDigitalSignature( InputStream data, InputStream signature, String certificateAlias) throws IOException { byte[] sigToVerify = IOUtils.toByteArray(signature); Certificate certificate = getCertificate(certificateAlias); if (certificate == null) { throw new CatalogCommandRuntimeException("Unable to retrieve certificate"); } try { Signature rsa = Signature.getInstance("SHA256withRSA"); rsa.initVerify(certificate); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = data.read(buffer)) >= 0) { rsa.update(buffer, OFFSET, len); } return rsa.verify(sigToVerify); } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) { String message = "An error occurred while verifying file"; LOGGER.debug(message, e); throw new CatalogCommandRuntimeException(message, e); } }
Source:
<code>protected void paintCenter(GC g) { TableMergeViewer leftMergeViewer = getLeftMergeViewer(); TableMergeViewer rightMergeViewer = getRightMergeViewer(); Table leftTable = leftMergeViewer.getStructuredViewer().getTable(); Table rightTable = rightMergeViewer.getStructuredViewer().getTable(); Rectangle leftClientArea = leftTable.getClientArea(); Rectangle rightClientArea = rightTable.getClientArea(); TableItem[] leftItems = leftTable.getItems(); TableItem[] rightItems = rightTable.getItems(); TableItem[] selection = leftTable.getSelection(); for (TableItem leftItem : leftItems) { final boolean selected; if (selection.length > 0) { selected = leftItem == selection[0]; } else { selected = false; } final Diff leftDiff = ((IMergeViewerItem)leftItem.getData()).getDiff(); <START> <END> if (leftDiff != null) { TableItem rightItem = findRightTableItemFromLeftDiff(rightItems, leftDiff); if (rightItem != null) { Color strokeColor = getCompareColor().getStrokeColor(leftDiff, isThreeWay(), false, selected); g.setForeground(strokeColor); drawCenterLine(g, leftClientArea, rightClientArea, leftItem, rightItem); } } } }</code><technical_language>paintCenter method needs account filters. Please add condition somthing : && MergeViewerUtil.isVisibleInMergeViewer(leftDiff, getEMFCompareConfiguration() .getSelectedGroup(), getEMFCompareConfiguration().getAggregatedPredicate())</technical_language>

Target:
protected void paintCenter(GC g) { TableMergeViewer leftMergeViewer = getLeftMergeViewer(); TableMergeViewer rightMergeViewer = getRightMergeViewer(); Table leftTable = leftMergeViewer.getStructuredViewer().getTable(); Table rightTable = rightMergeViewer.getStructuredViewer().getTable(); Rectangle leftClientArea = leftTable.getClientArea(); Rectangle rightClientArea = rightTable.getClientArea(); TableItem[] leftItems = leftTable.getItems(); TableItem[] rightItems = rightTable.getItems(); final ImmutableSet<TableItem> selection = ImmutableSet.copyOf(leftTable.getSelection()); for (TableItem leftItem : leftItems) { final boolean selected = Iterables.any(selection, equalTo(leftItem)); IMergeViewerItem leftData = (IMergeViewerItem)leftItem.getData(); final Diff leftDiff = ((IMergeViewerItem)leftItem.getData()).getDiff(); boolean doPaint = true; if (leftDiff != null) { for (IDifferenceFilter filter : getEMFCompareConfiguration().getSelectedFilters()) { TreeNode treeNode = MergeViewerUtil.getTreeNode(getEMFCompareConfiguration() .getComparison(), getEMFCompareConfiguration().getSelectedGroup(), leftDiff); if (filter.getPredicateWhenSelected().apply(treeNode) && !DiffUtil.isPrimeRefining(treeNode.getData())) { doPaint = false; break; } } } if (doPaint) { if (leftDiff != null) { TableItem rightItem = findRightTableItemFromLeftDiff(rightItems, leftDiff, leftData); if (rightItem != null) { Color strokeColor = getCompareColor().getStrokeColor(leftDiff, isThreeWay(), false, selected); g.setForeground(strokeColor); drawCenterLine(g, leftClientArea, rightClientArea, leftItem, rightItem); } } } } }
Source:
<code>private void startDismissTimerIfNeeded() { <START> if (!(dismissDuration >= 0)) <END> return; if (scheduleDismissRunnable != null) return; scheduleDismissRunnable = new Runnable() { public void run() { if (currentActivity != null) { dismissAndAwaitNextMessage(null); scheduleDismissRunnable = null; } else { shouldDismissWhenActive = true; } } }; handler.postDelayed(scheduleDismissRunnable, (long) dismissDuration * 1_000); }</code><technical_language>this dismissDuration < 0</technical_language>

Target:
private void startDismissTimerIfNeeded() { if (dismissDuration <= 0) return; if (scheduleDismissRunnable != null) return; scheduleDismissRunnable = new Runnable() { public void run() { if (currentActivity != null) { dismissAndAwaitNextMessage(null); scheduleDismissRunnable = null; } else { shouldDismissWhenActive = true; } } }; handler.postDelayed(scheduleDismissRunnable, (long) dismissDuration * 1_000); }
Source:
<code>public void testTimeout() throws InterruptedException { final String lockOwner1 = "LO1"; final String lockOwner2 = "LO2"; <START> final InfinispanLock lock = new InfinispanLock(commonPool(), commonPool(), AbstractCacheTest.TIME_SERVICE); <END> final LockPromise lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS); final LockPromise lockPromise2 = lock.acquire(lockOwner2, 0, TimeUnit.MILLISECONDS); assertTrue(lockPromise1.isAvailable()); assertTrue(lockPromise2.isAvailable()); lockPromise1.lock(); assertEquals(lockOwner1, lock.getLockOwner()); try { lockPromise2.lock(); fail(); } catch (TimeoutException e) { } lock.release(lockOwner1); assertNull(lock.getLockOwner()); assertFalse(lock.isLocked()); lock.release(lockOwner2); assertFalse(lock.isLocked()); assertNull(lock.getLockOwner()); }</code><technical_language>Please AbstractInfinispanTest.testExecutor() in tests, common pool impossible filter logs test</technical_language>

Target:
public void testTimeout() throws InterruptedException { final String lockOwner1 = "LO1"; final String lockOwner2 = "LO2"; final InfinispanLock lock = new InfinispanLock(testExecutor(), AbstractCacheTest.TIME_SERVICE); final LockPromise lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS); final LockPromise lockPromise2 = lock.acquire(lockOwner2, 0, TimeUnit.MILLISECONDS); assertTrue(lockPromise1.isAvailable()); assertTrue(lockPromise2.isAvailable()); lockPromise1.lock(); assertEquals(lockOwner1, lock.getLockOwner()); try { lockPromise2.lock(); fail(); } catch (TimeoutException e) { } lock.release(lockOwner1); assertNull(lock.getLockOwner()); assertFalse(lock.isLocked()); lock.release(lockOwner2); assertFalse(lock.isLocked()); assertNull(lock.getLockOwner()); }
Source:
<code>public void apply(NodeRemovalNomadChange change) throws NomadException { Cluster runtime = topologyService.getRuntimeNodeContext().getCluster(); Node node = change.getNode(); if (!runtime.containsNode(node.getUID())) { return; } if (killAtCommit.equals(topologyService.getUpcomingNodeContext().getNode().getTcProperties().orDefault().get(failoverKey))) { Path path = null; try { path = path().resolve("killed"); Files.createFile(path); platformService.stopPlatform(); <START> } catch (IOException e) { <END> LOGGER.warn(e.getMessage(), e); try { org.terracotta.utilities.io.Files.deleteIfExists(path); } catch (IOException ex) { throw new RuntimeException(ex); } } } try { LOGGER.info("Removing node: from stripe UID: {}", node.getName(), change.getStripeUID()); LOGGER.debug("Calling mBean {}#{}", TOPOLOGY_MBEAN, PLATFORM_MBEAN_OPERATION_NAME); mbeanServer.invoke( TOPOLOGY_MBEAN, PLATFORM_MBEAN_OPERATION_NAME, new Object[]{node.getHostname(), node.getPort().orDefault(), node.getGroupPort().orDefault()}, new String[]{String.class.getName(), int.class.getName(), int.class.getName()} ); dynamicConfigEventFiring.onNodeRemoval(change.getStripeUID(), node); } catch (RuntimeException | JMException e) { throw new NomadException("Error when applying: '" + change.getSummary() + "': " + e.getMessage(), e); } }</code><technical_language>catch FileAlreadyExistsException throw in other cases</technical_language>

Target:
public void apply(NodeRemovalNomadChange change) throws NomadException { Cluster runtime = topologyService.getRuntimeNodeContext().getCluster(); Node node = change.getNode(); if (!runtime.containsNode(node.getUID())) { return; } if (killAtCommit.equals(topologyService.getUpcomingNodeContext().getNode().getTcProperties().orDefault().get(failoverKey))) { Path path = null; try { path = path().resolve("killed"); Files.createFile(path); platformService.stopPlatform(); } catch (FileAlreadyExistsException e) { LOGGER.warn(e.getMessage(), e); try { org.terracotta.utilities.io.Files.deleteIfExists(path); } catch (IOException ex) { throw new RuntimeException(ex); } } catch (IOException e) { throw new RuntimeException(e); } } try { LOGGER.info("Removing node: from stripe UID: {}", node.getName(), change.getStripeUID()); LOGGER.debug("Calling mBean {}#{}", TOPOLOGY_MBEAN, PLATFORM_MBEAN_OPERATION_NAME); mbeanServer.invoke( TOPOLOGY_MBEAN, PLATFORM_MBEAN_OPERATION_NAME, new Object[]{node.getHostname(), node.getPort().orDefault(), node.getGroupPort().orDefault()}, new String[]{String.class.getName(), int.class.getName(), int.class.getName()} ); dynamicConfigEventFiring.onNodeRemoval(change.getStripeUID(), node); } catch (RuntimeException | JMException e) { throw new NomadException("Error when applying: '" + change.getSummary() + "': " + e.getMessage(), e); } }
Source:
<code>public TimerJobInstance getTimerByName(String jobName) { if(USE_LOCAL_CACHE) { if (localCache.containsKey(jobName)) { logger.debug("Found job in cache returning", jobName); return localCache.get(jobName); } } TimerJobInstance found = null; for (Timer timer : timerService.getTimers()) { try { Serializable info = timer.getInfo(); if (info instanceof EjbTimerJob) { EjbTimerJob job = (EjbTimerJob) info; EjbGlobalJobHandle handle = (EjbGlobalJobHandle) job.getTimerJobInstance().getJobHandle(); if(USE_LOCAL_CACHE) <START> localCache.putIfAbsent(jobName, handle.getTimerJobInstance()); <END> if (handle.getUuid().equals(jobName)) { logger.debug("Job does match timer and is going to be returned", jobName); found = handle.getTimerJobInstance(); } } } catch (NoSuchObjectLocalException e) { logger.debug("Timer info for was not found ", timer); } } return found; }</code><technical_language>Please brackets for if statements</technical_language>

Target:
public TimerJobInstance getTimerByName(String jobName) { if (USE_LOCAL_CACHE) { if (localCache.containsKey(jobName)) { logger.debug("Found job in cache returning", jobName); return localCache.get(jobName); } } TimerJobInstance found = null; for (Timer timer : timerService.getTimers()) { try { Serializable info = timer.getInfo(); if (info instanceof EjbTimerJob) { EjbTimerJob job = (EjbTimerJob) info; EjbGlobalJobHandle handle = (EjbGlobalJobHandle) job.getTimerJobInstance().getJobHandle(); if (USE_LOCAL_CACHE) { localCache.putIfAbsent(jobName, handle.getTimerJobInstance()); } if (handle.getUuid().equals(jobName)) { logger.debug("Job does match timer and is going to be returned", jobName); found = handle.getTimerJobInstance(); } } } catch (NoSuchObjectLocalException e) { logger.debug("Timer info for was not found ", timer); } } return found; }
Source:
<code><START> public Boolean isDirectDownload() { <END> return directDownload == null ? Boolean.FALSE : directDownload; }</code><technical_language>boolean</technical_language>

Target:
public boolean isDirectDownload() { return directDownload; }