auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ScaleGestureDetector(Context context, SimpleOnScaleGestureListener simpleOnScaleGestureListener) { try { Class.forName("android.view.ScaleGestureDetector"); Class<?> classRealScaleGestureDetector = Class.forName("com.jjoe64.graphview.compatible.RealScaleGestureDetector"); method_getScaleFactor = classRealScaleGestureDetector.getMethod("getScaleFactor"); method_isInProgress = classRealScaleGestureDetector.getMethod("isInProgress"); method_onTouchEvent = classRealScaleGestureDetector.getMethod("onTouchEvent", MotionEvent.class); Constructor<?> constructor = classRealScaleGestureDetector.getConstructor(Context.class, getClass(), SimpleOnScaleGestureListener.class); realScaleGestureDetector = constructor.newInstance(context, this, simpleOnScaleGestureListener); } catch (Exception e) { <START> e.printStackTrace(); <END> } }</code><technical_language>this warning is desired</technical_language>

Target:
public ScaleGestureDetector(Context context, SimpleOnScaleGestureListener simpleOnScaleGestureListener) { try { Class.forName("android.view.ScaleGestureDetector"); Class<?> classRealScaleGestureDetector = Class.forName("com.jjoe64.graphview.compatible.RealScaleGestureDetector"); method_getScaleFactor = classRealScaleGestureDetector.getMethod("getScaleFactor"); method_isInProgress = classRealScaleGestureDetector.getMethod("isInProgress"); method_onTouchEvent = classRealScaleGestureDetector.getMethod("onTouchEvent", MotionEvent.class); Constructor<?> constructor = classRealScaleGestureDetector.getConstructor(Context.class, getClass(), SimpleOnScaleGestureListener.class); realScaleGestureDetector = constructor.newInstance(context, this, simpleOnScaleGestureListener); } catch (Exception e) { Log.w("com.jjoe64.graphview", "*** WARNING *** No scaling available for graphs. Exception:"); e.printStackTrace(); } }
Source:
<code>private void testRcTextCharDecoding(boolean rcFileOptimizedWriterEnabled, boolean rcFileOptimizedReaderEnabled) throws Exception { String catalog = getSession().getCatalog().get(); Session session = Session.builder(getSession()) <START> .setCatalogSessionProperty(catalog, RCFILE_OPTIMIZED_WRITER_ENABLED, "" + rcFileOptimizedWriterEnabled) <END> .setCatalogSessionProperty(catalog, RCFILE_OPTIMIZED_READER_ENABLED, "" + rcFileOptimizedReaderEnabled) .build(); assertUpdate(session, "CREATE TABLE test_table_with_char WITH (format = 'RCTEXT') AS SELECT CAST('khaki' AS CHAR(7)) char_column", 1); assertQuery(session, "SELECT * FROM test_table_with_char WHERE char_column = 'khaki '", "VALUES (CAST('khaki' AS CHAR(7)))"); assertUpdate(session, "DROP TABLE test_table_with_char"); }</code><technical_language>Boolean.toString</technical_language>

Target:
private void testRcTextCharDecoding(boolean rcFileOptimizedWriterEnabled, boolean rcFileOptimizedReaderEnabled) throws Exception { String catalog = getSession().getCatalog().get(); Session session = Session.builder(getSession()) .setCatalogSessionProperty(catalog, RCFILE_OPTIMIZED_WRITER_ENABLED, Boolean.toString(rcFileOptimizedWriterEnabled)) .setCatalogSessionProperty(catalog, RCFILE_OPTIMIZED_READER_ENABLED, Boolean.toString(rcFileOptimizedReaderEnabled)) .build(); assertUpdate(session, "CREATE TABLE test_table_with_char WITH (format = 'RCTEXT') AS SELECT CAST('khaki' AS CHAR(7)) char_column", 1); try { assertQuery(session, "SELECT * FROM test_table_with_char WHERE char_column = 'khaki '", "VALUES (CAST('khaki' AS CHAR(7)))"); } finally { assertUpdate(session, "DROP TABLE test_table_with_char"); } }
Source:
<code>private void logExceptionBeforeFailOver(Exception ex, MessageHandler handler, Message<?> message) { if (this.logger.isInfoEnabled()) { this.logger.info("An exception was thrown by '" + handler + "' while handling '" + message + "': " + ex.getMessage() + ". Failing over to the next subscriber."); } else if (this.logger.isDebugEnabled()) { this.logger.debug("An exception was thrown by '" + handler + "' while handling '" + message + <START> "'. Failing over to the next subscriber.", ex); <END> } }</code><technical_language>Debug detected INFO branch</technical_language>

Target:
private void logExceptionBeforeFailOver(Exception ex, MessageHandler handler, Message<?> message) { if (this.logger.isDebugEnabled()) { this.logger.debug("An exception was thrown by '" + handler + "' while handling '" + message + "'. Failing over to the next subscriber.", ex); } else if (this.logger.isInfoEnabled()) { this.logger.info("An exception was thrown by '" + handler + "' while handling '" + message + "': " + ex.getMessage() + ". Failing over to the next subscriber."); } }
Source:
<code>private static void testTriggerDatabaseBackup() throws MambuApiException { DatabaseService databaseService = MambuAPIFactory.getDatabaseService(); DatabaseBackupRequest databaseRequestObject = new DatabaseBackupRequest(); databaseRequestObject.setCallback("<LINK_0>"); DatabaseBackupResponse response = databaseService.createDatabaseBackup(databaseRequestObject); <START> System.out.println(response); <END> }</code><technical_language>add a print prefix for logging analysis, "Database request Response:\n"</technical_language>

Target:
private static void testTriggerDatabaseBackup() throws MambuApiException { System.out.println(methodName = "\nIn testTriggerDatabaseBackup"); DatabaseService databaseService = MambuAPIFactory.getDatabaseService(); DatabaseBackupRequest databaseRequestObject = new DatabaseBackupRequest(); databaseRequestObject.setCallback("<LINK_0>"); DatabaseBackupResponse response = databaseService.createDatabaseBackup(databaseRequestObject); System.out.println("Database request Response:\n" + response); }
Source:
<code>public HitPolicy getHitPolicy() { <START> return hitPolicy == null ? HitPolicy.NONE : hitPolicy; <END> }</code><technical_language>HitPolicy.getDefault()</technical_language>

Target:
public HitPolicy getHitPolicy() { return hitPolicy == null ? HitPolicy.getDefault(): hitPolicy; }
Source:
<code>public void updatePhysics(GlowBlock block) { Byte initalData = block.getState().getRawData(); if (isStationary(block.getType())) { block.setType(getOpposite(block.getType()), block.getData(), false); } if (Byte.compare(block.getState().getRawData(), STRENGTH_SOURCE) != 0) { BlockFace[] faces = {UP, NORTH, EAST, SOUTH, WEST}; boolean connected = false; int count = 0; for (BlockFace face : faces) { if (block.getRelative(face).getType() == block.getType()) { if (count < 2 && face != UP && Byte.compare(block.getRelative(face).getState().getRawData(), STRENGTH_SOURCE) == 0) { count++; } if (!connected && face == UP || Byte.compare(block.getRelative(face).getState().getRawData(), block.getState().getRawData()) < 0) { connected = true; if (block.getWorld().getServer().getClassicWater()) { block.getState().setRawData(STRENGTH_SOURCE); } } if (block.getWorld().getServer().getClassicWater() && Byte.compare(block.getRelative(face).getState().getRawData(), STRENGTH_SOURCE) == 0) { block.getRelative(face).setType(Material.AIR); } } } if (!connected) { block.setType(Material.AIR); return; } if (count == 2) { block.getState().setRawData(STRENGTH_SOURCE); return; } } if (!(Byte.compare(block.getState().getRawData(), isWater(block.getType()) || block.getBiome() == Biome.HELL ? STRENGTH_MIN_WATER : STRENGTH_MIN_LAVA) == 0) || block.getRelative(DOWN).getType() == Material.AIR) { calculateFlow(block); } <START> if (initalData != block.getState().getRawData()) { <END> block.getWorld().requestSinglePulse(block, isWater(block.getType()) || block.getBiome() == Biome.HELL ? TICK_RATE_WATER : TICK_RATE_LAVA); } }</code><technical_language>I understand this is doing</technical_language>

Target:
public void updatePhysics(GlowBlock block) { if (isStationary(block.getType())) { block.setType(getOpposite(block.getType()), block.getData(), false); } if (Byte.compare(block.getState().getRawData(), STRENGTH_SOURCE) != 0) { BlockFace[] faces = {UP, NORTH, EAST, SOUTH, WEST}; boolean connected = false; int count = 0; for (BlockFace face : faces) { if (block.getRelative(face).getType() == block.getType()) { if (count < 2 && face != UP && Byte.compare(block.getRelative(face).getState().getRawData(), STRENGTH_SOURCE) == 0) { count++; } if (!connected && face == UP || Byte.compare(block.getRelative(face).getState().getRawData(), block.getState().getRawData()) < 0) { connected = true; if (block.getWorld().getServer().getClassicWater()) { block.getState().setRawData(STRENGTH_SOURCE); } } if (block.getWorld().getServer().getClassicWater() && Byte.compare(block.getRelative(face).getState().getRawData(), STRENGTH_SOURCE) == 0) { block.getRelative(face).setType(Material.AIR); } } } if (!connected) { block.setType(Material.AIR); return; } if (count == 2) { block.getState().setRawData(STRENGTH_SOURCE); return; } } if (!(Byte.compare(block.getState().getRawData(), isWater(block.getType()) || block.getBiome() == Biome.HELL ? STRENGTH_MIN_WATER : STRENGTH_MIN_LAVA) == 0) || block.getRelative(DOWN).getType() == Material.AIR) { calculateFlow(block); } }
Source:
<code>private void checkTimeoutDecreaseProcFailed(boolean sync, Client client, String procName, Object...params) throws IOException, ProcCallException, InterruptedException { checkDeploymentPropertyValue(client, "querytimeout", Integer.toString(TIMEOUT_NORMAL)); try { client.callProcedure(procName, params); } <START> catch (Exception ex) { <END> fail(procName + " is supposed to succeed, but failed with message " + ex.getMessage()); } checkDeploymentPropertyValue(client, "querytimeout", Integer.toString(TIMEOUT_NORMAL)); if (sync) { try { client.callProcedureWithTimeout(TIMEOUT_SHORT, procName, params); fail(procName + PROMPTMSG); } catch (Exception ex) { assertTrue(ex.toString() + " did not contain " + ERRORMSG, ex.getMessage().contains(ERRORMSG)); } } else { client.callProcedureWithTimeout(m_callback, TIMEOUT_SHORT, procName, params); client.drain(); checkCallbackTimeoutError(ERRORMSG);; } checkDeploymentPropertyValue(client, "querytimeout", Integer.toString(TIMEOUT_NORMAL)); try { client.callProcedure(procName, params); } catch (Exception ex) { fail(procName + " is supposed to succeed, but failed with message " + ex.getMessage() + "\n"); ex.printStackTrace(); } checkDeploymentPropertyValue(client, "querytimeout", Integer.toString(TIMEOUT_NORMAL)); }</code><technical_language>change this expect a ProcCallException above</technical_language>

Target:
private void checkTimeoutDecreaseProcFailed(boolean sync, Client client, String procName, Object...params) throws IOException, ProcCallException, InterruptedException { checkDeploymentPropertyValue(client, "querytimeout", Integer.toString(TIMEOUT_NORMAL)); try { client.callProcedure(procName, params); } catch (Exception ex) { fail(procName + " is supposed to succeed, but failed with message " + ex.getMessage()); } checkDeploymentPropertyValue(client, "querytimeout", Integer.toString(TIMEOUT_NORMAL)); if (sync) { try { client.callProcedureWithTimeout(TIMEOUT_SHORT, procName, params); fail(procName + PROMPTMSG); } catch (Exception ex) { assertTrue(ex.toString() + " did not contain " + ERRORMSG, ex.getMessage().contains(ERRORMSG)); } } else { client.callProcedureWithTimeout(m_callback, TIMEOUT_SHORT, procName, params); client.drain(); checkCallbackTimeoutError(ERRORMSG);; } checkDeploymentPropertyValue(client, "querytimeout", Integer.toString(TIMEOUT_NORMAL)); try { client.callProcedure(procName, params); } catch (Exception ex) { fail(procName + " is supposed to succeed, but failed with message " + ex.getMessage() + "\n"); } checkDeploymentPropertyValue(client, "querytimeout", Integer.toString(TIMEOUT_NORMAL)); }
Source:
<code>public void setAsyncExecutor(Executor executor) { if (executor == null && logger.isWarnEnabled()) { <START> logger.warn("A null executor disables the async gateway; methods returning Future<?> will run on the calling thread"); <END> } this.asyncExecutor = (executor instanceof AsyncTaskExecutor || executor == null) ? (AsyncTaskExecutor) executor : new TaskExecutorAdapter(executor); }</code><technical_language>info, end-user difinatelly decide disable asyncExecutor</technical_language>

Target:
public void setAsyncExecutor(Executor executor) { if (executor == null && logger.isInfoEnabled()) { logger.info("A null executor disables the async gateway; methods returning Future<?> will run on the calling thread"); } this.asyncExecutor = (executor instanceof AsyncTaskExecutor || executor == null) ? (AsyncTaskExecutor) executor : new TaskExecutorAdapter(executor); }
Source:
<code>protected Map<String, String>[] BuildStructFromConnectionListObject() { <START> final StoragePool storage_pool = <END> DbFacade.getInstance().getStoragePoolDao().getForVds(getParameters().getVdsId()); final Map<String, String>[] result = new HashMap[getParameters().getConnectionList().size()]; int i = 0; for (StorageServerConnections connection : getParameters().getConnectionList()) { result[i] = CreateStructFromConnection(connection, storage_pool); i++; } return result; }</code><technical_language>change variable name storagePool</technical_language>

Target:
protected Map<String, String>[] BuildStructFromConnectionListObject() { final StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().getForVds(getParameters().getVdsId()); final Map<String, String>[] result = new HashMap[getParameters().getConnectionList().size()]; int i = 0; for (StorageServerConnections connection : getParameters().getConnectionList()) { result[i] = CreateStructFromConnection(connection, storagePool); i++; } return result; }
Source:
<code>public String formatRate(int energy) { <START> return String.format("%.0f %s/t", energy * factor, energyName); <END> }</code><technical_language>This class a localized number format matches language set in game instead of language of system. java Locale locale = MinecraftForgeClient.getLocale(); NumberFormat numberFormat = NumberFormat.getIntegerInstance(locale); float amount = energy * factor; String amountString = numberFormat.format(amount); return String.format("%s %s/t", amountString, energyName);</technical_language>

Target:
public String formatRate(int energy) { String amountString = formatEnergyNum(energy); return String.format("%s %s/t", amountString, energyName); }
Source:
<code>public boolean isStackChecked(String workspaceName) { <START> String attrValue = <END> redrawUiElementsTimeout .until( visibilityOfElementLocated( By.xpath(format(Locators.STACK_ITEM_CHECKBOX_XPATH_PATTERN, workspaceName)))) .getAttribute("aria-checked"); return Boolean.parseBoolean(attrValue); }</code><technical_language>I propose move code separate method of **SeleniumWebDriverHelper** class similar **waitVisibilityAndGetValue**</technical_language>

Target:
public boolean isStackChecked(String workspaceName) { String attrValue = seleniumWebDriverHelper.waitVisibilityAndGetAttribute( By.xpath(format(Locators.STACK_ITEM_CHECKBOX_XPATH_PATTERN, workspaceName)), "aria-checked"); return Boolean.parseBoolean(attrValue); }
Source:
<code>public void wrongValueTypeThrowsException() <START> throws IllegalAccessException, InstantiationException { <END> final Store kvStore = factory.newStore( new StoreConfigurationImpl<K, V>(factory.getKeyType(), factory.getValueType(), ClassLoader.getSystemClassLoader())); K key = factory.getKeyType().newInstance(); try { if (this.factory.getKeyType() == String.class) { kvStore.remove(key, 1.0f); } else { kvStore.remove(key, "value"); } throw new AssertionError("Expected ClassCastException because the value is of the wrong type"); } catch (ClassCastException e) { } catch (CacheAccessException e) { System.err.println("Warning, an exception is thrown due to the SPI test"); e.printStackTrace(); } }</code><technical_language>fixed in place. This issue exists in a few, this class others well</technical_language>

Target:
public void wrongValueTypeThrowsException() throws IllegalAccessException, InstantiationException { final Store kvStore = factory.newStore( new StoreConfigurationImpl<K, V>(factory.getKeyType(), factory.getValueType(), ClassLoader.getSystemClassLoader())); K key = factory.getKeyType().newInstance(); try { if (this.factory.getValueType() == String.class) { kvStore.remove(key, 1.0f); } else { kvStore.remove(key, "value"); } throw new AssertionError("Expected ClassCastException because the value is of the wrong type"); } catch (ClassCastException e) { } catch (CacheAccessException e) { System.err.println("Warning, an exception is thrown due to the SPI test"); e.printStackTrace(); } }
Source:
<code><START> protected ProjectAssetsQuery createProjectQuery(String filter, <END> String filterType, int startIndex, int amount) { List<String> suffixes = Collections.EMPTY_LIST; Category category = getCategory(filterType); if (category != null) { suffixes = this.getSuffixes(category); } return new ProjectAssetsQuery(libraryPlaces.getProjectInfo().getProject(), filter, startIndex, amount, suffixes); }</code><technical_language>@manstis I some experience , this replaced Instance<Category> category class field</technical_language>

Target:
protected ProjectAssetsQuery createProjectQuery(String filter, String filterType, int startIndex, int amount) { Category category = categoriesManagerCache.getCategory(filterType); List<String> suffixes = this.getSuffixes(category); return new ProjectAssetsQuery(libraryPlaces.getActiveWorkspaceContext(), filter, startIndex, amount, suffixes); }
Source:
<code>public void onPersonSelected(Person person) { FragmentManager fragmentManager = getFragmentManager(); PersonDetailFragment personDetailFragment = (PersonDetailFragment) fragmentManager.findFragmentByTag(KEY_PERSON_DETAIL_FRAGMENT); long personID = person.getPersonID(); <START> int localTableBlogID = person.getLocalTableBlogId(); <END> if (personDetailFragment == null) { personDetailFragment = PersonDetailFragment.newInstance(personID, localTableBlogID); } else { personDetailFragment.setPersonDetails(personID, localTableBlogID); } if (!personDetailFragment.isAdded()) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.setCustomAnimations(R.animator.fragment_slide_in_from_right, R.animator.fragment_slide_out_to_left, R.animator.fragment_slide_in_from_left, R.animator.fragment_slide_out_to_right); fragmentTransaction.replace(R.id.fragment_container, personDetailFragment, KEY_PERSON_DETAIL_FRAGMENT); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }</code><technical_language>Earlier in file, a semantically variable/parameter is named localBlogId. suggest naming same. I localTableBlogID is more suitable name so, I suggest renaming parameter of refreshUsersList() method above? Cheers</technical_language>

Target:
public void onPersonSelected(Person person) { FragmentManager fragmentManager = getFragmentManager(); PersonDetailFragment personDetailFragment = (PersonDetailFragment) fragmentManager .findFragmentByTag(KEY_PERSON_DETAIL_FRAGMENT); long personID = person.getPersonID(); int localTableBlogID = person.getLocalTableBlogId(); if (personDetailFragment == null) { personDetailFragment = PersonDetailFragment.newInstance(personID, localTableBlogID); } else { personDetailFragment.setPersonDetails(personID, localTableBlogID); } if (!personDetailFragment.isAdded()) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.fragment_container, personDetailFragment, KEY_PERSON_DETAIL_FRAGMENT); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }
Source:
<code>public void testIterateWhilePresent() { assertEquals( asList(), Seq.iterateWhilePresent(null, i -> Optional.empty()).toList() <START> ); <END> assertEquals( asList(2), Seq.iterateWhilePresent(2, i -> Optional.empty()).toList() ); assertEquals( asList(2, 4, 16, 256, 65536), Seq.iterateWhilePresent(2, i -> i <= 256 ? Optional.of(i * i) : Optional.empty()).toList() ); }</code><technical_language>I find this surprising. This equal asList((Object) null). Illustration: <LINK_0></technical_language>

Target:
public void testIterateWhilePresent() { assertThrows(NullPointerException.class, () -> Seq.iterateWhilePresent(null, i -> Optional.empty()).toList()); assertEquals( asList(2), Seq.iterateWhilePresent(2, i -> Optional.empty()).toList() ); assertEquals( asList(2, 4, 16, 256, 65536), Seq.iterateWhilePresent(2, i -> i <= 256 ? Optional.of(i * i) : Optional.empty()).toList() ); }
Source:
<code>public void testDoWhileWhitespaceAround() throws Exception { final String[] expected = { "9:16: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "while"), }; <START> verify(checkConfig, getPath("InputWhitespaceAroundDoWhileWhitespaceAround.java"), expected); <END> }</code><technical_language>problem weird new name</technical_language>

Target:
public void testDoWhileWhitespaceAround() throws Exception { final String[] expected = { "9:16: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "while"), }; verify(checkConfig, getPath("InputWhitespaceAroundDoWhile.java"), expected); }
Source:
<code><START> public void clear() throws Exception { <END> trigger.clear(window); }</code><technical_language>suggestion @Override public void clear() throws Exception {</technical_language>

Target:
void clear() throws Exception { trigger.clear(window); }
Source:
<code><START> private Refreshable<Long> getIncrementingLongRefreshableThrowingOnSpecificValue(long badValue) { <END> AtomicLong atomicLong = new AtomicLong(); PollingRefreshable<Long> pollingRefreshable = PollingRefreshable.createWithSpecificPoller( () -> { long newValue = atomicLong.incrementAndGet(); if (newValue == badValue) { throw new RuntimeException(badValue + " is illegal"); } return newValue; }, scheduler); return pollingRefreshable.getRefreshable(); }</code><technical_language>Out of order -- move tests</technical_language>

Target:
private Refreshable<Long> getIncrementingLongRefreshableThrowingOnSpecificValue(long badValue) { AtomicLong atomicLong = new AtomicLong(); PollingRefreshable<Long> pollingRefreshable = PollingRefreshable.createWithSpecificPoller( () -> { long newValue = atomicLong.incrementAndGet(); if (newValue == badValue) { throw new RuntimeException(badValue + " is illegal"); } return newValue; }, REFRESH_INTERVAL, scheduler); return pollingRefreshable.getRefreshable(); }
Source:
<code>public String toString() { StringBuilder builder = new StringBuilder(); builder.append("TmfConstantTransform [ offset="); <START> builder.append(new TmfNanoTimestamp(fOffset)); <END> builder.append(" ]"); return builder.toString(); }</code><technical_language>toString() output dependent timestamp preference settings</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("TmfConstantTransform [ offset = "); builder.append(fOffset); builder.append(" ]"); return builder.toString(); }
Source:
<code>public void testVHTLocal() throws Exception { TestParams vhtConfig = new TestParams.Builder() <START> .setInputInstances(200_000) <END> .setSamplingSize(20_000) .setEvaluationInstances(200_000) .setClassifiedInstances(200_000) .setClassificationsCorrect(75f) .setKappaStat(0f) .setKappaTempStat(0f) .setCLIStringTemplate(TestParams.Templates.PREQEVAL_VHT_RANDOMTREE) .setResultFilePollTimeout(10) .setPrePollWait(10) .setTaskClassName(LocalDoTask.class.getName()) .build(); TestUtils.test(vhtConfig); }</code><technical_language>do removing "set" prefixes fluent API</technical_language>

Target:
public void testVHTLocal() throws Exception { TestParams vhtConfig = new TestParams.Builder() .inputInstances(200_000) .samplingSize(20_000) .evaluationInstances(200_000) .classifiedInstances(200_000) .classificationsCorrect(75f) .kappaStat(0f) .kappaTempStat(0f) .cliStringTemplate(TestParams.Templates.PREQEVAL_VHT_RANDOMTREE) .resultFilePollTimeout(10) .prePollWait(10) .taskClassName(LocalDoTask.class.getName()) .build(); TestUtils.test(vhtConfig); }
Source:
<code>private void compareValues(String expandedContent, String expandedValue) throws Exception { Diff diff = new Diff(expandedContent, expandedValue); diff.overrideDifferenceListener(new DifferenceListener() { public int differenceFound(Difference diff) { if (allowWildcards && (diff.getId() == DifferenceEngine.TEXT_VALUE.getId() || diff.getId() == DifferenceEngine.ATTR_VALUE .getId())) { try { Tools.assertSimilar(diff.getControlNodeDetail().getValue(), diff.getTestNodeDetail().getValue(), '*'); } catch (ComparisonFailure e) { return Diff.RETURN_ACCEPT_DIFFERENCE; } <START> return Diff.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; <END> } return Diff.RETURN_ACCEPT_DIFFERENCE; } public void skippedComparison(Node arg0, Node arg1) { } }); if (!diff.identical()) { throw new Exception(diff.toString()); } }</code><technical_language>Personally I clearer if move this line immediately call assertSimilar(), try block</technical_language>

Target:
private void compareValues(String expandedContent, String expandedValue) throws Exception { Diff diff = new Diff(expandedContent, expandedValue); diff.overrideDifferenceListener(new DifferenceListener() { public int differenceFound(Difference diff) { if (allowWildcards && (diff.getId() == DifferenceEngine.TEXT_VALUE.getId() || diff.getId() == DifferenceEngine.ATTR_VALUE .getId())) { try { Tools.assertSimilar(diff.getControlNodeDetail().getValue(), diff.getTestNodeDetail().getValue(), '*'); return Diff.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; } catch (ComparisonFailure e) { return Diff.RETURN_ACCEPT_DIFFERENCE; } } return Diff.RETURN_ACCEPT_DIFFERENCE; } public void skippedComparison(Node arg0, Node arg1) { } }); if (!diff.identical()) { throw new Exception(diff.toString()); } }
Source:
<code>public void writeFormattedMessageLine(String format, Object... args) { super.writeFormattedMessageLine(format, args); <START> if (LOG.isDebugEnabled()) { <END> LOG.debug("writeFormattedMessageLine, the format: " + format); int i = 0; for (Object arg : args) { LOG.debug("writeFormattedMessageLine, the " + i + " arg is " + arg.toString()); i++; } } }</code><technical_language>this code extracted in a separate method logging is called super call</technical_language>

Target:
public void writeFormattedMessageLine(String format, Object... args) { super.writeFormattedMessageLine(format, args); debugWriteFormattedMessageLine(format, args); }
Source:
<code>protected void render0(FunctionRenderContext context) { Object[] jsonPathElements = new Object[context.getArgumentsSize() - 2]; <START> for (int i = 2; i < context.getArgumentsSize(); i++) { <END> try { jsonPathElements[i - 2] = Integer.parseInt(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } catch (NumberFormatException e) { jsonPathElements[i - 2] = JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i)); } } context.addChunk("(select "); context.addChunk("json_merge_patch("); context.addArgument(0); context.addChunk(", concat('"); for (int i = 0; i < jsonPathElements.length; i++) { startJsonPathElement(context, jsonPathElements, i); } context.addChunk("', "); context.addChunk("temp.val"); context.addChunk(", '"); for (int i = jsonPathElements.length - 1; i >= 0; i--) { endJsonPathElement(context, jsonPathElements, i); } context.addChunk("'))"); context.addChunk(" from (values row("); context.addArgument(1); context.addChunk(")) temp(val))"); }</code><technical_language>Please start 0 jsonPathElements.length add offset context.getArgument(i + 2) subtracting it</technical_language>

Target:
protected void render0(FunctionRenderContext context) { List<Object> jsonPathElements = AbstractJsonGetFunction.retrieveJsonPathElements(context, 2); context.addChunk("(select "); context.addChunk("case when lower(temp.val) = 'null' then json_set("); context.addArgument(0); context.addChunk(",'"); context.addChunk(AbstractJsonGetFunction.toJsonPath(jsonPathElements, jsonPathElements.size(), true)); context.addChunk("', null) else "); context.addChunk("json_merge_patch("); context.addArgument(0); context.addChunk(", concat('"); for (int i = 0; i < jsonPathElements.size(); i++) { startJsonPathElement(context, jsonPathElements, i); } context.addChunk("', "); context.addChunk("temp.val"); context.addChunk(", '"); for (int i = jsonPathElements.size() - 1; i >= 0; i--) { endJsonPathElement(context, jsonPathElements, i); } context.addChunk("')) end"); context.addChunk(" from (values row("); context.addArgument(1); context.addChunk(")) temp(val))"); }
Source:
<code>private static ByteBuffer encodeElement(Element element) { if (element instanceof SequencedElement) { ByteBuffer buffer = ByteBuffer.allocate(SEQ_NUM_OFFSET + ELEMENT_PAYLOAD_OFFSET + element.getPayload().remaining()); buffer.putLong(((SequencedElement)element).getSequenceNumber()); buffer.putInt(element.getPayload().remaining()); buffer.put(element.getPayload()); buffer.flip(); return buffer; <START> } <END> ByteBuffer buffer = ByteBuffer.allocate(ELEMENT_PAYLOAD_OFFSET + element.getPayload().remaining()); buffer.putInt(element.getPayload().remaining()); buffer.put(element.getPayload()); buffer.flip(); return buffer; }</code><technical_language>else here..also some duplicate code avoided (from 139-142) if part of code is common. abstract allocate difference sequenced normal elements a template pattern here?. possibly a future refactoring</technical_language>

Target:
private static ByteBuffer encodeElement(Element element) { ByteBuffer buffer = null; if (element instanceof SequencedElement) { buffer = ByteBuffer.allocate(SEQ_NUM_OFFSET + ELEMENT_PAYLOAD_OFFSET + element.getPayload().remaining()); buffer.putLong(((SequencedElement)element).getSequenceNumber()); } else { buffer = ByteBuffer.allocate(ELEMENT_PAYLOAD_OFFSET + element.getPayload().remaining()); } buffer.putInt(element.getPayload().remaining()); buffer.put(element.getPayload()); buffer.flip(); return buffer; }
Source:
<code><START> public void invalidateAll() <END> throws InterruptedException, ExecutionException, TimeoutException, NetworkException { final int numPulls = 1000; final CountDownLatch countDownLatch = new CountDownLatch(1); final ExecutorService pool = Executors.newSingleThreadExecutor(); pool.submit(() -> { for (int pull = 0; pull < numPulls; ++pull) { parameterWorker.pull(0); parameterWorker.invalidateAll(); } countDownLatch.countDown(); }); pool.shutdown(); final boolean allThreadsFinished = countDownLatch.await(10, TimeUnit.SECONDS); parameterWorker.close(ParameterWorkerTestUtil.CLOSE_TIMEOUT); assertTrue(ParameterWorkerTestUtil.MSG_THREADS_SHOULD_FINISH, allThreadsFinished); verify(mockSender, times(numPulls)).sendPullMsg(anyString(), anyObject()); }</code><technical_language>please remove invalidateAllAsync method in AsyncWorkerTest.java style in this PR</technical_language>

Target:
public void invalidateAll() throws InterruptedException, ExecutionException, TimeoutException, NetworkException { final int numPulls = 1000; final CountDownLatch countDownLatch = new CountDownLatch(1); final ExecutorService pool = Executors.newSingleThreadExecutor(); final SSPParameterWorker sspParameterWorker = (SSPParameterWorker) parameterWorker; pool.submit(() -> { for (int pull = 0; pull < numPulls; ++pull) { sspParameterWorker.pull(0); sspParameterWorker.invalidateAll(); } countDownLatch.countDown(); }); pool.shutdown(); final boolean allThreadsFinished = countDownLatch.await(10, TimeUnit.SECONDS); sspParameterWorker.close(ParameterWorkerTestUtil.CLOSE_TIMEOUT); assertTrue(ParameterWorkerTestUtil.MSG_THREADS_SHOULD_FINISH, allThreadsFinished); verify(mockSender, times(numPulls)).sendPullMsg(anyString(), anyObject()); }
Source:
<code>public void waitUntilInstanceReady(final HttpClient client, final String host) { <START> final StatusResponseHandler handler = StatusResponseHandler.getInstance(); <END> RetryUtil.retryUntilTrue( () -> { try { StatusResponseHolder response = client.go( new Request(HttpMethod.GET, new URL(StringUtils.format("%s/status/health", host))), handler ).get(); LOG.info("%s %s", response.getStatus(), response.getContent()); return response.getStatus().equals(HttpResponseStatus.OK); } catch (Throwable e) { LOG.error(e, ""); return false; } }, "Waiting for instance to be ready: [" + host + "]" ); }</code><technical_language>This variable is unnecessary now</technical_language>

Target:
public void waitUntilInstanceReady(final HttpClient client, final String host) { RetryUtil.retryUntilTrue( () -> { try { StatusResponseHolder response = client.go( new Request(HttpMethod.GET, new URL(StringUtils.format("%s/status/health", host))), StatusResponseHandler.getInstance() ).get(); LOG.info("%s %s", response.getStatus(), response.getContent()); return response.getStatus().equals(HttpResponseStatus.OK); } catch (Throwable e) { LOG.error(e, ""); return false; } }, "Waiting for instance to be ready: [" + host + "]" ); }
Source:
<code>public ViewBundle() { <START> this(ImmutableList.copyOf(ServiceFinder.find(ViewRenderer.class))); <END> }</code><technical_language>I more sense create immutable copy of Iterable in ViewBundle(Iterable<ViewRenderer>) constructor instead of here</technical_language>

Target:
public ViewBundle() { this(ServiceFinder.find(ViewRenderer.class)); }
Source:
<code><START> public static List<Matrix> computeCovariances(Dataset<EmptyContext, GmmPartitionData> dataset, <END> Vector clusterProbs, Vector[] means) { List<CovarianceMatricesAggregator> aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); List<Matrix> res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; }</code><technical_language>a bit odd a mess of public static other methods. sense move public static methods util class this class visibility is package? if goal avoid unnecessary serialization lets define this explicitly</technical_language>

Target:
static List<Matrix> computeCovariances(Dataset<EmptyContext, GmmPartitionData> dataset, Vector clusterProbs, Vector[] means) { List<CovarianceMatricesAggregator> aggregators = dataset.compute( data -> map(data, means), CovarianceMatricesAggregator::reduce ); if (aggregators == null) return Collections.emptyList(); List<Matrix> res = new ArrayList<>(); for (int i = 0; i < aggregators.size(); i++) res.add(aggregators.get(i).covariance(clusterProbs.get(i))); return res; }
Source:
<code>public StepUpdate(@Nullable Key<?> changedKey) { <START> super(new Object[]{DynamicWizardStep.this, changedKey}); <END> myChangedKey = changedKey; }</code><technical_language>tl;dr: need a unique identity object, array is unnecessary, "new Object()"? This CL a newly created array identity object (e.g. unpack objects). Basically, updates unique thanks this fix. I do making updates unique is a good fix drawback a slight performance hit due extraneous updates. Note regression 1.0 updates directly, merging. replace array construction intimidating</technical_language>

Target:
public StepUpdate(@Nullable Key<?> changedKey) { super(DynamicWizardStep.this); myChangedKey = changedKey; }
Source:
<code>private void addRoleWidget(StringBuilder sb, IAtsWorkItem workItem, IAtsWidgetDefinition widget) { sb.append("Roles: "); Collection<String> roles = atsServer.getAttributeResolver().getAttributesToStringList(workItem, AtsAttributeTypes.Role); if (!roles.isEmpty()) { <START> sb.append("<table border=\"1\" align=\"center\" width=\"90%\"><tr><th>Role</th><th>User</th><th>Completed</th><th>Hours Spent</th></tr>"); <END> for (String xml : roles) { sb.append("<tr>"); for (String key : roleKeys) { sb.append("<td>"); String data = AXml.getTagData(xml, key); if (key.equals("userId")) { data = atsServer.getUserService().getUserById(data).getName(); } sb.append(data); sb.append("</td>"); } sb.append("</tr>"); } sb.append("</table>"); } }</code><technical_language>Suggest making string a constant</technical_language>

Target:
private void addRoleWidget(StringBuilder sb, IAtsWorkItem workItem, IAtsWidgetDefinition widget) { sb.append("Roles: "); Collection<String> roles = atsServer.getAttributeResolver().getAttributesToStringList(workItem, AtsAttributeTypes.Role); if (!roles.isEmpty()) { sb.append(ROLE_TABLE_HEADER); for (String xml : roles) { sb.append("<tr>"); for (String key : roleKeys) { sb.append("<td>"); String data = AXml.getTagData(xml, key); if (key.equals("userId")) { data = atsServer.getUserService().getUserById(data).getName(); } sb.append(data); sb.append("</td>"); } sb.append("</tr>"); } sb.append("</table>"); } }
Source:
<code>public void stop() { try { <START> semaphore.acquire(Integer.MAX_VALUE); <END> } catch (InterruptedException e) { log.warnUnableToCloseDb(e); log.warnUnableToCloseExpiredDb(e); return; } try { db.close(); } catch (IOException e) { log.warnUnableToCloseDb(e); } try { expiredDb.close(); } catch (IOException e) { log.warnUnableToCloseExpiredDb(e); } }</code><technical_language>@rvansa I stop() release semaphore permits. Threads read from/write store stopped throw exception immediately, block forever</technical_language>

Target:
public void stop() { try { semaphore.acquire(Integer.MAX_VALUE); } catch (InterruptedException e) { throw new PersistenceException("Cannot acquire semaphore", e); } try { try { db.close(); } catch (IOException e) { log.warnUnableToCloseDb(e); } try { expiredDb.close(); } catch (IOException e) { log.warnUnableToCloseExpiredDb(e); } } finally { stopped = true; semaphore.release(Integer.MAX_VALUE); } }
Source:
<code>public Builder setCollectorType(CollectorFactory.CollectorType collectorType) { <START> this.collectorType = collectorType; <END> return this; }</code><technical_language>Avoid this</technical_language>

Target:
public Builder setCollectorType(CollectorFactory.CollectorType collectorType) { _collectorType = collectorType; return this; }
Source:
<code>private static long convertToBytes(String sizeWithSuffix) { if (sizeWithSuffix == null || sizeWithSuffix.length() == 0) { return 0; } <START> String suffix = sizeWithSuffix.substring(sizeWithSuffix.length() - 2).toLowerCase(); <END> String sizeValue = sizeWithSuffix.substring(0, sizeWithSuffix.length() - 2); double value = Long.parseLong(sizeValue); long bytes = 0; switch (suffix) { case "kb": bytes = (long) value * 1024; break; case "mb": bytes = (long) value * 1024 * 1024; break; case "gb": bytes = (long) value * 1024 * 1024 * 1024; break; } return bytes; }</code><technical_language>error if length is 1</technical_language>

Target:
private static long convertToBytes(String sizeWithSuffix) { if (sizeWithSuffix == null || sizeWithSuffix.length() == 0) { return 0; } String suffix; String sizeValue; try { suffix = sizeWithSuffix.substring(sizeWithSuffix.length() - 2).toLowerCase(); sizeValue = sizeWithSuffix.substring(0, sizeWithSuffix.length() - 2).trim(); } catch (IndexOutOfBoundsException e) { LOG.warn("Invalid file size '" + sizeWithSuffix + "'. The file size must include a size and the units. eg 128MB"); throw e; } double value = Long.parseLong(sizeValue); long bytes; switch (suffix) { case "kb": bytes = (long) value * 1024; break; case "mb": bytes = (long) value * 1024 * 1024; break; case "gb": bytes = (long) value * 1024 * 1024 * 1024; break; default: LOG.warn("Could not parse unit suffix of '" + suffix + "' from max file size '" + sizeWithSuffix + "'"); throw new IllegalArgumentException("Invalid unit suffix " + suffix); } return bytes; }
Source:
<code>public Object parse(byte[] fileByteContent) throws ParseException { try ( ByteArrayInputStream inputStream = new ByteArrayInputStream(fileByteContent); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(streamReader); CSVReader flatFileReader = buildFlatFileReader(bufferedReader); <START> ) { <END> return parseResultFromReader(flatFileReader); } catch (Exception e) { throw new ParseException("Exception encountered while parsing delimited flat file", e); } }</code><technical_language>is this close open curly brace doing</technical_language>

Target:
public Object parse(byte[] fileByteContent) throws ParseException { try (ByteArrayInputStream inputStream = new ByteArrayInputStream(fileByteContent); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(streamReader); CSVReader flatFileReader = buildFlatFileReader(bufferedReader)) { return parseResultFromReader(flatFileReader); } catch (Exception e) { throw new ParseException("Exception encountered while parsing delimited flat file", e); } }
Source:
<code>public ResponseEntity<String> delete(@PathVariable("id") Long id) { try { userUtil.extractLoggedAppUserFromDatabase(); Loan loan = loanDao.findOne(id); if(loan == null){ throw new NotFoundException("Loan not found"); } <START> loanDao.delete(id); <END> loanDao.flush(); } catch (EmptyResultDataAccessException emptyResultDataAccessException) { throw new NotFoundException(emptyResultDataAccessException.getMessage()); } return new ResponseEntity<>("Loan deleted", HttpStatus.NO_CONTENT); }</code><technical_language>check if Counterparty deleted belongs logged AppUser</technical_language>

Target:
public ResponseEntity<String> delete(@PathVariable("id") Long id) { try { userUtil.extractLoggedAppUserFromDatabase(); Loan loan = loanDao.findOne(id); if(loan == null){ throw new NotFoundException("Loan not found"); } AppUser appUser = userUtil.extractLoggedAppUserFromDatabase(); if(appUser.getUserId() != loan.getUser().getUserId()){ throw new BadRequestException("Bad request"); } loanDao.delete(id); loanDao.flush(); } catch (EmptyResultDataAccessException emptyResultDataAccessException) { throw new NotFoundException(emptyResultDataAccessException.getMessage()); } return new ResponseEntity<>("Loan deleted", HttpStatus.NO_CONTENT); }
Source:
<code>void close() { if (isOpen.compareAndSet(true, false)) { Iterator<DeleteOperation> iter = deleteOperations.iterator(); while (iter.hasNext()) { DeleteOperation deleteOperation = iter.next(); <START> iter.remove(); <END> NonBlockingRouter.completeOperation(deleteOperation.getFutureResult(), deleteOperation.getCallback(), null, new RouterException("Aborted operation because Router is closed.", RouterErrorCode.RouterClosed)); } } }</code><technical_language>this difference</technical_language>

Target:
void close() { for (DeleteOperation op : deleteOperations) { if (deleteOperations.remove(op)) { NonBlockingRouter.completeOperation(op.getFutureResult(), op.getCallback(), null, new RouterException("Aborted operation because Router is closed.", RouterErrorCode.RouterClosed)); } } }
Source:
<code>public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { AuthorizationResult authorizationResult = context.authorize(operation); if (authorizationResult.getDecision() == AuthorizationResult.Decision.DENY) { throw ControllerLogger.ROOT_LOGGER.unauthorized(operation.get(OP).asString(), context.getCurrentAddress(), authorizationResult.getExplanation()); } ModelNode commentNode = COMMENT.resolveModelAttribute(context, operation); ModelNode snapshotNode = SNAPSHOT_NAME.resolveModelAttribute(context, operation); String comment = commentNode.isDefined() ? commentNode.asString() : null; <START> String snapshot = snapshotNode.isDefined() ? snapshotNode.asString() : null; <END> try { String name = persister.snapshot(snapshot, comment); context.getResult().set(name); } catch (ConfigurationPersistenceException e) { throw new OperationFailedException(e); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); }</code><technical_language>Code simplified org.jboss.dmr.ModelNode#asStringOrNull</technical_language>

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { AuthorizationResult authorizationResult = context.authorize(operation); if (authorizationResult.getDecision() == AuthorizationResult.Decision.DENY) { throw ControllerLogger.ROOT_LOGGER.unauthorized(operation.get(OP).asString(), context.getCurrentAddress(), authorizationResult.getExplanation()); } ModelNode commentNode = COMMENT.resolveModelAttribute(context, operation); ModelNode snapshotNode = SNAPSHOT_NAME.resolveModelAttribute(context, operation); String comment = commentNode.asStringOrNull(); String snapshot = snapshotNode.asStringOrNull(); try { String name = persister.snapshot(snapshot, comment); context.getResult().set(name); } catch (ConfigurationPersistenceException e) { throw new OperationFailedException(e); } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); }
Source:
<code>private static INDArray buildArray(List<Integer> dimensions, String rawArray) { int rank = dimensions.size(); int[] shape = new int[rank]; <START> for(int i = 0; i < rank; i++) { <END> shape[i] = dimensions.get(i); } String[] entries = rawArray.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\\n", "").split(","); double[] entryValues = new double[entries.length]; for (int i = 0; i < entries.length; i++) { entryValues[i] = Double.parseDouble(entries[i]); } return Nd4j.create(entryValues, shape); }</code><technical_language>consider guava here? int[] shape = Ints.toArray(dimensions);</technical_language>

Target:
private static INDArray buildArray(List<Integer> dimensions, String rawArray) { int[] shape = Ints.toArray(dimensions); String[] entries = StringUtils.replacePattern(rawArray, "[\\[\\]\\n]", "").split(","); double[] entryValues = new double[entries.length]; for (int i = 0; i < entries.length; i++) { entryValues[i] = Double.parseDouble(entries[i]); } return Nd4j.create(entryValues, shape); }
Source:
<code>private static boolean prefixExists(SubfieldPath subfieldPath, Collection<SubfieldPath> subfieldPaths) { <START> List<PathElement> path = subfieldPath.getPath(); <END> for (SubfieldPath otherSubfiledPath : subfieldPaths) { List<PathElement> otherPath = otherSubfiledPath.getPath(); if (!otherPath.isEmpty() && otherPath.size() < path.size() && Objects.equals(otherPath, path.subList(0, otherPath.size()))) { return true; } } return false; }</code><technical_language>I rename getPath getPathParts</technical_language>

Target:
private static boolean prefixExists(SubfieldPath subfieldPath, Collection<SubfieldPath> subfieldPaths) { return subfieldPaths.stream() .filter(path -> path.isPrefix(subfieldPath)) .findAny() .isPresent(); }