auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> private static MethodHandle reorderArguments(Method method, MethodHandle handle, String[] argumentNames) { <END> if (method.isAnnotationPresent(GoloFunction.class)) { String[] parameterNames = method.getAnnotation(GoloFunction.class).parameters(); int[] argumentsOrder = new int[parameterNames.length]; for (int i = 0; i < argumentNames.length; i++) { int actualPosition = -1; for (int j = 0; j < parameterNames.length; j++) { if (parameterNames[j].equals(argumentNames[i])) { actualPosition = j; } } if (actualPosition == -1) { throw new IllegalArgumentException("Argument name " + argumentNames[i] + " not in parameter names used in declaration: " + method.getName() + Arrays.toString(parameterNames)); } argumentsOrder[actualPosition] = i; } return permuteArguments(handle, handle.type(), argumentsOrder); } return handle; }</code><technical_language>Lovely</technical_language>

Target:
public static MethodHandle reorderArguments(Method method, MethodHandle handle, String[] argumentNames) { if (Arrays.stream(method.getParameters()).allMatch(p -> p.isNamePresent())) { String[] parameterNames = Arrays.stream(method.getParameters()).map(Parameter::getName).toArray(String[]::new); int[] argumentsOrder = new int[parameterNames.length]; for (int i = 0; i < argumentNames.length; i++) { int actualPosition = -1; for (int j = 0; j < parameterNames.length; j++) { if (parameterNames[j].equals(argumentNames[i])) { actualPosition = j; } } if (actualPosition == -1) { throw new IllegalArgumentException("Argument name " + argumentNames[i] + " not in parameter names used in declaration: " + method.getName() + Arrays.toString(parameterNames)); } argumentsOrder[actualPosition] = i; } return permuteArguments(handle, handle.type(), argumentsOrder); } return handle; }
Source:
<code>protected void internalReceiveCommand(String itemName, Command command) { for (EdimaxBindingProvider provider : providers) { EdimaxBindingConfiguration config = ((EdimaxGenericBindingProvider) provider) .getConfig(itemName); String deviceIP = getDeviceIP(config.getMacAddress()); if (deviceIP == null) { <START> logger.debug("No real device for item: " + itemName + " found."); <END> continue; } changeValue(itemName, deviceIP, config, command); break; } }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
protected void internalReceiveCommand(String itemName, Command command) { for (EdimaxBindingProvider provider : providers) { EdimaxBindingConfiguration config = ((EdimaxGenericBindingProvider) provider).getConfig(itemName); String deviceIP = getDeviceIP(config.getMacAddress()); if (deviceIP == null) { logger.debug("No real device for item: found.", itemName); continue; } changeValue(itemName, deviceIP, config, command); break; } }
Source:
<code>private DbParameterAccessor[] getAccessors( Parse headerCells) throws SQLException{ String givenParams = ""; Parse headerCellsAux = headerCells; if (headerCells == null) return EMPTY; DbParameterAccessor accessors[]=new DbParameterAccessor[headerCells.size()]; for (int k = 0; headerCellsAux != null; k++, headerCellsAux = headerCellsAux.more) { <START> if (! isOutput(headerCellsAux.text())) { END> if (k == 0) { givenParams += "'" + headerCellsAux.text() + "'"; } else { givenParams += ", " + "'" + headerCellsAux.text() + "'"; } } } for (int i = 0; headerCells != null; i++, headerCells = headerCells.more) { String name=headerCells.text(); accessors[i]=dbObject.getDbParameterAccessor(name, isOutput(name)? OUTPUT:INPUT, givenParams); if (accessors[i]==null) { exception (headerCells,new IllegalArgumentException("Parameter/column "+name+" not found")); return null; } } return accessors; }</code><technical_language>do skip output parameters</technical_language>

Target:
private DbParameterAccessor[] getAccessors(Parse headerCells) throws SQLException { String givenParams = ""; Parse headerCellsAux = headerCells; if (headerCells == null) return EMPTY; DbParameterAccessor accessors[] = new DbParameterAccessor[headerCells .size()]; for (int k = 0; headerCellsAux != null; k++, headerCellsAux = headerCellsAux.more) { if (k == 0) { if (headerCellsAux.text() == "?") { givenParams += "NVL('" + headerCellsAux.text() + "', 'RETURN_NAME')"; } else { givenParams += "upper('" + headerCellsAux.text() + "')"; } } else { givenParams += ", " + "upper('" + headerCellsAux.text() + "')"; } } givenParams = givenParams.replace("?", ""); for (int i = 0; headerCells != null; i++, headerCells = headerCells.more) { String name = headerCells.text(); accessors[i] = dbObject.getDbParameterAccessor(name, isOutput(name) ? OUTPUT : INPUT, givenParams); if (accessors[i] == null) { exception(headerCells, new IllegalArgumentException( "Parameter/column " + name + " not found")); return null; } } return accessors; }
Source:
<code>public Schema getDefaultSchema(FormatContext context) throws IOException { final String format = getProperties().getProperties().getOrDefault(FORMAT, "delimited"); String delimiter = getProperties().getProperties().get(DELIMITER); if (format.equals("delimited") && Strings.isNullOrEmpty(delimiter)) { throw new IllegalArgumentException("Delimiter is required when format is set to 'delimited'"); } List<Schema.Field> fields = new ArrayList<>(); String path = getProperties().getProperties().getOrDefault( "path", "" ); Job job = JobUtils.createInstance(); Configuration conf = job.getConfiguration(); final Path file = getFilePathForSchemaGeneration(path, format.equals("delimited") ? null : format, conf); final FileSystem fileSystem = FileSystem.get(file.toUri(), conf); FSDataInputStream input = fileSystem.open(file); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input)); String line = bufferedReader.readLine(); if (line == null) { return null; } <START> bufferedReader.close(); <END> String[] columns = line.split(getDefaultDelimiter()); int count = 1; for (String column : columns) { if (getSkipHeader()) { fields.add(Schema.Field.of(column, Schema.of(Schema.Type.STRING))); continue; } fields.add( Schema.Field.of( String.format("%s_%s", "body", count), Schema.of(Schema.Type.STRING) ) ); count++; } return Schema.recordOf("text", fields); }</code><technical_language>Close final</technical_language>

Target:
public Schema getDefaultSchema(FormatContext context) throws IOException { final String format = getProperties().getProperties().getOrDefault(FORMAT, "delimited"); String delimiter = getProperties().getProperties().get(DELIMITER); if (format.equals("delimited") && Strings.isNullOrEmpty(delimiter)) { throw new IllegalArgumentException("Delimiter is required when format is set to 'delimited'."); } List<Schema.Field> fields = new ArrayList<>(); String path = getProperties().getProperties().getOrDefault( "path", "" ); Job job = JobUtils.createInstance(); Configuration conf = job.getConfiguration(); for (Map.Entry<String, String> entry : getFileSystemProperties().entrySet()) { conf.set(entry.getKey(), entry.getValue()); } FSDataInputStream input = null; BufferedReader bufferedReader = null; String line = null; try { final Path file = getFilePathForSchemaGeneration(path, format.equals("delimited") ? null : format, conf); final FileSystem fileSystem = FileSystem.get(file.toUri(), conf); input = fileSystem.open(file); bufferedReader = new BufferedReader(new InputStreamReader(input)); line = bufferedReader.readLine(); if (line == null) { return null; } } finally { if (bufferedReader != null) { bufferedReader.close(); } if (input != null) { input.close(); } } String[] columns = line.split(getDefaultDelimiter()); int count = 1; for (String column : columns) { if (getSkipHeader()) { fields.add(Schema.Field.of(column, Schema.of(Schema.Type.STRING))); continue; } fields.add( Schema.Field.of( String.format("%s_%s", "body", count), Schema.of(Schema.Type.STRING) ) ); count++; } return Schema.recordOf("text", fields); }
Source:
<code><START> public void setTimer(final String version, final long timeout, final Stat currentStatOfBarrierDone) { <END> debounceTimer.scheduleAfterDebounceTime("VersionUpgradeTimeout", timeout, ()->timerOff(version, currentStatOfBarrierDone)); }</code><technical_language>public scope is necessary for this method</technical_language>

Target:
private void setTimer(final String version, final long timeout, final Stat currentStatOfBarrierDone) { debounceTimer.scheduleAfterDebounceTime(VERSION_UPGRADE_TIMEOUT_TIMER, timeout, ()->timerOff(version, currentStatOfBarrierDone)); }
Source:
<code>public AuditReplayCommand parse(Text inputLine, Function<Long, Long> relativeToAbsolute) throws IOException { Matcher m = logLineParseRegex.matcher(inputLine.toString()); if (!m.find()) { throw new IOException( "Unable to find valid message pattern from audit log line: `" + inputLine + "` using regex `" + logLineParseRegex + "`"); } long relativeTimestamp; try { relativeTimestamp = dateFormat.parse(m.group("timestamp")).getTime() - startTimestamp; } catch (ParseException p) { throw new IOException( <START> "Exception while parsing timestamp from audit log line: `" <END> + inputLine, p); } String auditMessageSanitized = m.group("message").replace("(options=", "(options:"); Map<String, String> parameterMap = new HashMap<String, String>(); String[] auditMessageSanitizedList = auditMessageSanitized.split("\t"); for (String auditMessage : auditMessageSanitizedList) { String[] splitMessage = auditMessage.split("=", 2); try { parameterMap.put(splitMessage[0], splitMessage[1]); } catch (ArrayIndexOutOfBoundsException e) { throw new IOException( "Exception while parsing a message from audit log line: " + inputLine, e); } } return new AuditReplayCommand(relativeToAbsolute.apply(relativeTimestamp), SPACE_SPLITTER.split(parameterMap.get("ugi")).iterator().next(), parameterMap.get("cmd").replace("(options:", "(options="), parameterMap.get("src"), parameterMap.get("dst"), parameterMap.get("ip")); }</code><technical_language>extra backtick here. backticks inputLine</technical_language>

Target:
public AuditReplayCommand parse(Text inputLine, Function<Long, Long> relativeToAbsolute) throws IOException { Matcher m = logLineParseRegex.matcher(inputLine.toString()); if (!m.find()) { throw new IOException( "Unable to find valid message pattern from audit log line: `" + inputLine + "` using regex `" + logLineParseRegex + "`"); } long relativeTimestamp; try { relativeTimestamp = dateFormat.parse(m.group("timestamp")).getTime() - startTimestamp; } catch (ParseException p) { throw new IOException( "Exception while parsing timestamp from audit log line: `" + inputLine + "`", p); } String auditMessageSanitized = m.group("message").replace("(options=", "(options:"); Map<String, String> parameterMap = new HashMap<String, String>(); String[] auditMessageSanitizedList = auditMessageSanitized.split("\t"); for (String auditMessage : auditMessageSanitizedList) { String[] splitMessage = auditMessage.split("=", 2); try { parameterMap.put(splitMessage[0], splitMessage[1]); } catch (ArrayIndexOutOfBoundsException e) { throw new IOException( "Exception while parsing a message from audit log line: `" + inputLine + "`", e); } } return new AuditReplayCommand(relativeToAbsolute.apply(relativeTimestamp), SPACE_SPLITTER.split(parameterMap.get("ugi")).iterator().next(), parameterMap.get("cmd").replace("(options:", "(options="), parameterMap.get("src"), parameterMap.get("dst"), parameterMap.get("ip")); }
Source:
<code>public boolean hasManagedResource(final CIString orgId) { final int orgObjectId = jdbcTemplate.queryForObject( "select object_id from organisation where organisation = ?", new Object[] { orgId }, Integer.class ); return executeStreaming( jdbcTemplate, <START> "select l.object " + <END> "from last l inner join org o on l.object_id = o.object_id " + "where o.org_id = ? " + "and o.object_type in (?, ?, ?) " + "and l.sequence_id > 0", pstmt -> { pstmt.setInt(1, orgObjectId); pstmt.setInt(2, ObjectTypeIds.getId(ObjectType.INETNUM)); pstmt.setInt(3, ObjectTypeIds.getId(ObjectType.INET6NUM)); pstmt.setInt(4, ObjectTypeIds.getId(ObjectType.AUT_NUM)); }, resultSet -> { while (resultSet.next()) { if (hasRipeNccMntner(RpslObject.parse(resultSet.getString("object")))) { return true; } } return false; } ); }</code><technical_language>Uppercase SQL keywords for readibility (and consistency)</technical_language>

Target:
public boolean hasManagedResource(final CIString orgId) { final int orgObjectId = jdbcTemplate.queryForObject( "SELECT object_id FROM organisation WHERE organisation = ?", new Object[] { orgId }, Integer.class ); return executeStreaming( jdbcTemplate, "SELECT l.object " + "FROM last l INNER JOIN org o ON l.object_id = o.object_id " + "WHERE o.org_id = ? " + "AND o.object_type in (?, ?, ?) " + "AND l.sequence_id > 0", pstmt -> { pstmt.setInt(1, orgObjectId); pstmt.setInt(2, ObjectTypeIds.getId(ObjectType.INETNUM)); pstmt.setInt(3, ObjectTypeIds.getId(ObjectType.INET6NUM)); pstmt.setInt(4, ObjectTypeIds.getId(ObjectType.AUT_NUM)); }, resultSet -> { while (resultSet.next()) { if (hasRipeNccMntner(RpslObject.parse(resultSet.getString("object")))) { return true; } } return false; } ); }
Source:
<code>@Override public boolean onOptionsItemSelected(MenuItem item) { <START> switch (item.getItemId()) { <END> case R.id.action_camera_controller_aeroplane: mSceneView.setCameraController(mOrbitAeroplaneCameraController); break; case R.id.action_camera_controller_crater: mSceneView.setCameraController(mOrbitLocationCameraController); break; case R.id.action_camera_controller_globe: mSceneView.setCameraController(new GlobeCameraController()); break; default: return super.onOptionsItemSelected(item); } return true; }</code><technical_language>This needs if statement, app modules converted library modules in sample viewer throws this error: <LINK_0></technical_language>

Target:
@Override public boolean onOptionsItemSelected(MenuItem item) { int itemid = item.getItemId(); if (itemid == R.id.action_camera_controller_plane) { mSceneView.setCameraController(mOrbitPlaneCameraController); return true; } else if (itemid == R.id.action_camera_controller_crater) { mSceneView.setCameraController(mOrbitLocationCameraController); return true; } else if (itemid == R.id.action_camera_controller_globe) { mSceneView.setCameraController(new GlobeCameraController()); return true; } return super.onOptionsItemSelected(item); }
Source:
<code>public String doBulkFateOperation(List<ByteBuffer> args, String tableName) throws AccumuloSecurityException, AccumuloException, TableNotFoundException { <START> while (true) { <END> try { return doFateOperation(FateOperation.TABLE_BULK_IMPORT2, args, Collections.emptyMap(), tableName); } catch (TableExistsException | NamespaceExistsException e) { throw new AssertionError(e); } catch (NamespaceNotFoundException ne) { throw new TableNotFoundException(null, tableName, "Namespace not found", ne); } catch (AccumuloException ae) { BulkImport.checkExceptionForMerge(ae, tableName); } } }</code><technical_language>This retry loop pushed doFateOperation implementation, get closer RPC. way, if add a new enum type TableOperationExceptionType, check is wrapped. This prevents thrift types spreading RPC code. in doFateOperation work: java boolean retry = false; do { try { // ... do fate RPC calls } catch (ThriftTableOperationException e) { switch (e.getType()) { // ... existing code case BULK_WHILE_CONCURRENTLY_MERGING_SO_RETRY: // pick a name for enum // log msg retry = true; break; // ... existing code } } } while(retry);</technical_language>

Target:
public String doBulkFateOperation(List<ByteBuffer> args, String tableName) throws AccumuloSecurityException, AccumuloException, TableNotFoundException { try { return doFateOperation(FateOperation.TABLE_BULK_IMPORT2, args, Collections.emptyMap(), tableName); } catch (TableExistsException | NamespaceExistsException e) { throw new AssertionError(e); } catch (NamespaceNotFoundException ne) { throw new TableNotFoundException(null, tableName, "Namespace not found", ne); } }
Source:
<code>public void test009_readNamesInSection() throws ConfigInvalidException { String configString = "[core]\n" + "repositoryFormatVersion = 0\n" + "filemode = false\n" + "logAllRefUpdates = true\n"; final Config c = parse(configString); Set<String> names = c.getNames("core"); assertEquals("Core section size", 3, names.size()); assertTrue("Core section should contain \"filemode\"", names .contains("filemode")); assertTrue("Core section should contain \"repositoryFormatVersion\"", names.contains("repositoryFormatVersion")); assertTrue("Core section should contain \"logallrefupdates\"", <START> names.contains("logAllRefUpdates")); <END> Iterator<String> itr = names.iterator(); assertEquals("filemode", itr.next()); assertEquals("logAllRefUpdates", itr.next()); assertEquals("repositoryFormatVersion", itr.next()); assertFalse(itr.hasNext()); }</code><technical_language>assert? relevant. Note difference in case. I of that, new getNames deal differences in case? I encountered spelling listed key</technical_language>

Target:
public void test009_readNamesInSection() throws ConfigInvalidException { String configString = "[core]\n" + "repositoryFormatVersion = 0\n" + "filemode = false\n" + "logAllRefUpdates = true\n"; final Config c = parse(configString); Set<String> names = c.getNames("core"); assertEquals("Core section size", 3, names.size()); assertTrue("Core section should contain \"filemode\"", names .contains("filemode")); assertTrue("Core section should contain \"repositoryFormatVersion\"", names.contains("repositoryFormatVersion")); assertTrue("Core section should contain \"repositoryformatversion\"", names.contains("repositoryformatversion")); Iterator<String> itr = names.iterator(); assertEquals("filemode", itr.next()); assertEquals("logAllRefUpdates", itr.next()); assertEquals("repositoryFormatVersion", itr.next()); assertFalse(itr.hasNext()); }
Source:
<code>public void etlOutputAsNtriples2Filesystem() { final FileOpener opener = new FileOpener(); final Triples2RdfModel triple2model = new Triples2RdfModel(); RdfModelFileWriter rdfModelFileWriter = new RdfModelFileWriter(); rdfModelFileWriter.setProperty("<LINK_0>"); rdfModelFileWriter.setStartIndex(2); rdfModelFileWriter.setEndIndex(7); rdfModelFileWriter.setTarget(NTRIPLES_DEBUG_FILES); triple2model.setInput(N_TRIPLE); opener.setReceiver(new TarReader()).setReceiver(new XmlDecoder()) .setReceiver(new AlephMabXmlHandler()) .setReceiver( new Metamorph("src/main/resources/morph-hbz01-to-lobid.xml")) .setReceiver(new PipeEncodeTriples()) .setReceiver(new SimpleStringSubstituter( <START> "endTime> \"\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\"", <END> "endTime> \"0001-01-01T00:00:00\"")) .setReceiver(triple2model).setReceiver(rdfModelFileWriter); opener.process(new File(TEST_FILENAME_ALEPHXMLCLOBS).getAbsolutePath()); opener.closeStream(); }</code><technical_language>maybe: "endTime> \"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\""</technical_language>

Target:
public void etlOutputAsNtriples2Filesystem() { final FileOpener opener = new FileOpener(); final Triples2RdfModel triple2model = new Triples2RdfModel(); RdfModelFileWriter rdfModelFileWriter = new RdfModelFileWriter(); rdfModelFileWriter.setProperty("<LINK_0>"); rdfModelFileWriter.setStartIndex(2); rdfModelFileWriter.setEndIndex(7); rdfModelFileWriter.setTarget(NTRIPLES_DEBUG_FILES); triple2model.setInput(N_TRIPLE); opener.setReceiver(new TarReader()).setReceiver(new XmlDecoder()) .setReceiver(new AlephMabXmlHandler()) .setReceiver( new Metamorph("src/main/resources/morph-hbz01-to-lobid.xml")) .setReceiver(new PipeEncodeTriples()) .setReceiver(new SimpleStringSubstituter( "endTime> \"\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\"", "endTime> \"0001-01-01T00:00:00\"")) .setReceiver(triple2model).setReceiver(rdfModelFileWriter); opener.process(new File(TEST_FILENAME_ALEPHXMLCLOBS).getAbsolutePath()); opener.closeStream(); }
Source:
<code>protected synchronized void setStorageService(StorageService storageService) { if (_storageServiceDoNotUseDirectly == null) { _storageServiceDoNotUseDirectly = storageService; <START> _storeDoNotUseDirectly = storageService.getStorage(STORE_NAME); <END> storageFacade = new StorageFacade(this._storeDoNotUseDirectly); } }</code><technical_language>I do "other storage variables" - prefer incompliant field naming remove underscore</technical_language>

Target:
protected synchronized void setStorageService(StorageService storageService) { Storage storage = storageService.getStorage(STORE_NAME); storageFacade = new StorageFacade(storage); }
Source:
<code>private static boolean hasNoPathVariableAnnotation(VariableTree variableTree) { <START> return variableTree.modifiers().annotations().stream().noneMatch(a -> a.symbolType().is(PATH_VARIABLE_ANNOTATION)); <END> }</code><technical_language>another API is in methods - variableTree.symbol.metadata().isAnnotatedWith , I for consistency</technical_language>

Target:
private static boolean hasNoPathVariableAnnotation(VariableTree variableTree) { return !variableTree.symbol().metadata().isAnnotatedWith(PATH_VARIABLE_ANNOTATION); }
Source:
<code>public boolean lock(K... keys) { <START> return cacheImplementation.lock(Arrays.asList(keys), flags, null); <END> }</code><technical_language>methods ClassLoader package-private, non-public API - remove parameter altogether</technical_language>

Target:
public boolean lock(K... keys) { return cacheImplementation.lock(Arrays.asList(keys), flags); }
Source:
<code>protected Event createSelectionEvent(int stateMask) { <START> int stateMaskSelection = SWT.getPlatform().equals("gtk") ? stateMask : stateMask | SWT.BUTTON1; <END> Event event = super.createSelectionEvent(stateMaskSelection); event.item = widget; return event; }</code><technical_language>coding OS-specific-ness. Is this sufficient condition for OS? 1. SWTBot users SunOS/Solaris? statemask correct if GTK Solaris ? risky test it. 2. Util.isLinux() implementation in org.eclipse.jface.util package. considers 'motif' Linux, 'gtk'. SWT supports motif. out-dated. Do need consider motif? 2-3 years discovering some differences in SWT behaviors win, linux, mac SWTBot reviews. limitations support difference. inconsistency if support difference some places. is approach for swtbot</technical_language>

Target:
protected Event createSelectionEvent(int stateMask) { int stateMaskSelection = Util.isGtk() ? stateMask : stateMask | SWT.BUTTON1; Event event = super.createSelectionEvent(stateMaskSelection); event.item = widget; return event; }
Source:
<code><START> public static boolean doesColumnExist(SQLiteDatabase db, String tableName, String columnName) { <END> try (Cursor cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 0", null)) { if (cursor != null) { return cursor.getColumnIndex(columnName) != -1; } } return false; }</code><technical_language>lots of classes provide convenience wrappers SQL queries. chance this fit in existing one? CustomSQLiteQueryBuilder? DAOs</technical_language>

Target:
public static boolean doesColumnExist(SQLiteDatabase db, String tableName, String columnName) { return getColumnNames(db, tableName).contains(columnName); }
Source:
<code>public void testAsyncTaskWithMultiplePartition() throws Exception { Map<Integer, List<KV>> input = new HashMap<>(); Map<Integer, List<Integer>> output = new HashMap<>(); List<Integer> partition = Arrays.asList(1, 2, 3, 4, 5); List<Integer> outputPartition = partition.stream().map(x -> x * 10).collect(Collectors.toList()); for (int i = 0; i < 5; i++) { List<KV> keyedPartition = new ArrayList<>(); for (Integer val : partition) { keyedPartition.add(KV.of(i, val)); } input.put(i, keyedPartition); <START> output.put(i, new ArrayList<Integer>(outputPartition)); <END> } CollectionStream<KV> inputStream = CollectionStream.of("async-test", "ints", input); CollectionStream outputStream = CollectionStream.empty("async-test", "ints-out", 5); TestRunner .of(MyAsyncStreamTask.class) .addInputStream(inputStream) .addOutputStream(outputStream) .run(Duration.ofSeconds(2)); StreamAssert.that(outputStream).contains(output, Duration.ofMillis(1000)); }</code><technical_language>I suggest more input/output partition</technical_language>

Target:
public void testAsyncTaskWithMultiplePartition() throws Exception { Map<Integer, List<KV>> inputPartitionData = new HashMap<>(); Map<Integer, List<Integer>> expectedOutputPartitionData = new HashMap<>(); List<Integer> partition = Arrays.asList(1, 2, 3, 4, 5); List<Integer> outputPartition = partition.stream().map(x -> x * 10).collect(Collectors.toList()); for (int i = 0; i < 5; i++) { List<KV> keyedPartition = new ArrayList<>(); for (Integer val : partition) { keyedPartition.add(KV.of(i, val)); } inputPartitionData.put(i, keyedPartition); expectedOutputPartitionData.put(i, new ArrayList<Integer>(outputPartition)); } CollectionStream<KV> inputStream = CollectionStream.of("async-test", "ints", inputPartitionData); CollectionStream outputStream = CollectionStream.empty("async-test", "ints-out", 5); TestRunner .of(MyAsyncStreamTask.class) .addInputStream(inputStream) .addOutputStream(outputStream) .run(Duration.ofSeconds(2)); StreamAssert.containsInOrder(outputStream, expectedOutputPartitionData, Duration.ofMillis(1000)); }
Source:
<code>public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } Key other = (Key) obj; if ( sourceType == null ) { if ( other.sourceType != null ) { return false; } } <START> else if ( !sourceType.erasure().equals( other.sourceType.erasure() ) ) { <END> return false; } if ( targetType == null ) { if ( other.targetType != null ) { return false; } } else if ( !targetType.erasure().equals( other.targetType.erasure() ) ) { return false; } return true; }</code><technical_language>is this needed</technical_language>

Target:
public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } Key other = (Key) obj; if ( sourceType == null ) { if ( other.sourceType != null ) { return false; } } else if ( !sourceType.equals( other.sourceType ) ) { return false; } if ( targetType == null ) { if ( other.targetType != null ) { return false; } } else if ( !targetType.equals( other.targetType ) ) { return false; } return true; }
Source:
<code>AesDecryptor(Mode mode, byte[] keyBytes, byte[] aad, byte[] ivPrefix) throws IllegalArgumentException, IOException { if (null == keyBytes) { throw new IllegalArgumentException("Null key bytes"); } this.aesMode = mode; aesKey = new SecretKeySpec(keyBytes, "AES"); AAD = aad; this.ivPrefix = ivPrefix; if (Mode.GCM == mode) { nonceLength = GCM_NONCE_LENGTH; tagLength = GCM_TAG_LENGTH; try { aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); } catch (GeneralSecurityException e) { throw new IOException("Failed to create decryptor", e); } } <START> else { <END> nonceLength = CTR_NONCE_LENGTH; tagLength = 0; try { aesCipher = Cipher.getInstance("AES/CTR/NoPadding"); } catch (GeneralSecurityException e) { throw new IOException("Failed to create decryptor", e); } } if (null != ivPrefix && ivPrefix.length > nonceLength) { throw new IllegalArgumentException("IV prefix length (" + ivPrefix.length + ") should be shorter than nonce length (" + nonceLength + ")"); } }</code><technical_language>Assuming else is AES_CTR correct in future</technical_language>

Target:
AesDecryptor(Mode mode, byte[] keyBytes, byte[] aad, byte[] ivPrefix) throws IllegalArgumentException, IOException { if (null == keyBytes) { throw new IllegalArgumentException("Null key bytes"); } this.aesMode = mode; aesKey = new SecretKeySpec(keyBytes, "AES"); AAD = aad; this.ivPrefix = ivPrefix; if (Mode.GCM == mode) { nonceLength = GCM_NONCE_LENGTH; tagLength = GCM_TAG_LENGTH; try { aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); } catch (GeneralSecurityException e) { throw new IOException("Failed to create GCM cipher", e); } } else { nonceLength = CTR_NONCE_LENGTH; tagLength = 0; try { aesCipher = Cipher.getInstance("AES/CTR/NoPadding"); } catch (GeneralSecurityException e) { throw new IOException("Failed to create CTR cipher", e); } } if (null != ivPrefix && ivPrefix.length > nonceLength) { throw new IllegalArgumentException("IV prefix length (" + ivPrefix.length + ") should be shorter than nonce length (" + nonceLength + ")"); } }
Source:
<code>public void showGroups(List<Group> groups) { mGroupList = groups; Collections.sort(mGroupList, new Comparator<Group>() { @Override <START> public int compare(Group o1, Group o2) { <END> return o1.getName().compareTo(o2.getName()); } }); mGroupListAdapter.setGroups(groups); }</code><technical_language>Give Groups a name</technical_language>

Target:
public void showGroups(List<Group> groups) { mGroupList = groups; Collections.sort(mGroupList, new Comparator<Group>() { @Override public int compare(Group grp1, Group grp2) { return grp1.getName().compareTo(grp2.getName()); } }); mGroupListAdapter.setGroups(groups); }
Source:
<code>public UnsavedFileAttachment(File file, String type) { this.name = file.getName(); try { this.inputStream = new FileInputStream(file); } catch (IOException ioe) { System.out.println("problem setting inputstream "+ioe); <START> inputStreamException = ioe; <END> } this.type = type; }</code><technical_language>throw here? tempted hold file ref instead, opening a stream unexpected for a consumer of API</technical_language>

Target:
public UnsavedFileAttachment(File file, String type) { this.file = file; this.name = file.getName(); this.type = type; }
Source:
<code>public void deactiveCurrentRevision() { if (fRevisionInContext == null) { return; } fRevisionInContext.eAdapters().remove(listener); deleteAllMarkers(); if (hasDrafts()) { final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); UIUtils.replyToChange(shell, fRevisionInContext, Messages.ActiveWorkspaceRevision_0 + fRevisionInContext.getChangeInfo().getSubject() + "\"\n\n", fGerritClient, false); } fRevisionInContext = null; <START> firePropertyChange("activeRevision", null, null); END> fIsQuickDiffOn = Platform.getPreferencesService().getBoolean("org.eclipse.ui.editors", "quickdiff.quickDiff", false, null); fIsAdditionIndicationInOverviewRule = Platform.getPreferencesService().getBoolean("org.eclipse.ui.editors", "additionIndicationInOverviewRule", false, null); fIsChangeIndicationInOverviewRuler = Platform.getPreferencesService().getBoolean("org.eclipse.ui.editors", "changeIndicationInOverviewRuler", false, null); fIsDeletionIndicationInOverviewRuler = Platform.getPreferencesService().getBoolean("org.eclipse.ui.editors", "deletionIndicationInOverviewRuler", false, null); Preferences preferences = InstanceScope.INSTANCE.getNode("org.eclipse.ui.editors"); preferences.put("quickdiff.quickDiff", new Boolean(fIsQuickDiffOn).toString()); preferences.put("additionIndicationInOverviewRule", new Boolean(fIsQuickDiffOn).toString()); preferences.put("changeIndicationInOverviewRuler", new Boolean(fIsChangeIndicationInOverviewRuler).toString()); preferences.put("deletionIndicationInOverviewRuler", new Boolean(fIsDeletionIndicationInOverviewRuler).toString()); try { preferences.flush(); } catch (BackingStoreException e1) { EGerritCorePlugin.logError(fGerritClient.getRepository().formatGerritVersion() + e1.getMessage()); } }</code><technical_language>Move new code is method</technical_language>

Target:
public void deactiveCurrentRevision() { if (fRevisionInContext == null) { return; } fRevisionInContext.eAdapters().remove(listener); deleteAllMarkers(); if (hasDrafts()) { final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); UIUtils.replyToChange(shell, fRevisionInContext, Messages.ActiveWorkspaceRevision_0 + fRevisionInContext.getChangeInfo().getSubject() + "\"\n\n", fGerritClient, false); } fRevisionInContext = null; firePropertyChange("activeRevision", null, null); restoreQuickDiffValues(); }
Source:
<code>public int hashCode() { <START> int result = 17; <END> result = 31 * result + Integer.hashCode(super.getBatchSize()); result = 31 * result + Objects.hashCode(span); result = 31 * result + Objects.hashCode(super.getColumn()); result = 31 * result + Objects.hashCode(super.getTask()); return result; }</code><technical_language>Objects.hash()</technical_language>

Target:
public int hashCode() { return Objects.hash(super.getBatchSize(), span, super.getColumn(), super.getTask()); }
Source:
<code>protected void onDestroy() { <START> super.onDestroy(); <END> mapView.onDestroy(); }</code><technical_language>avoid a crash orientation change in tablets add: if (handler != null && runnable != null) { handler.removeCallbacks(runnable); }</technical_language>

Target:
protected void onDestroy() { super.onDestroy(); if (handler != null && runnable != null) { handler.removeCallbacks(runnable); } mapView.onDestroy(); }
Source:
<code>public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { template = new MongoTemplate(factory); this.collectionName = (StringUtils.hasText(collectionName)) ? collectionName : DEFAULT_COLLECTION_NAME; <START> } <END></code><technical_language>This ctor invoke other similar logic I above. DRY - in other words</technical_language>

Target:
public MongoDbMetadataStore(MongoDbFactory factory, String collectionName) { this(new MongoTemplate(factory), collectionName); }
Source:
<code>public void testSetOnlineForNonQueueMode() throws Exception { Registration registration = givenASimpleClient(); <START> final CountDownLatch countDown = new CountDownLatch(2); <END> instance.addListener(new PresenceListener() { @Override public void onOnline(Registration endpoint) { countDown.countDown(); } @Override public void onOffline(Registration endpoint) { countDown.countDown(); } }); instance.setOnline(registration); assertFalse(countDown.await(2, TimeUnit.SECONDS)); }</code><technical_language>a countdownlatch of 1</technical_language>

Target:
public void testSetOnlineForNonQueueMode() throws Exception { Registration registration = givenASimpleClient(); instance.addListener(new PresenceListener() { @Override public void onOnline(Registration registration) { fail("No invocation was expected"); } @Override public void onOffline(Registration registration) { fail("No invocation was expected"); } }); instance.setOnline(registration); }
Source:
<code>public String toString() { return "creationTime=" + creationTime + ", sequence=" + sequence + ", uuid=" + uuid + ", expirationTime=" + expirationTime + ", lastAccessTime=" + lastAccessTime + ", hits=" + hits <START> + ", recordState=" + reservationId <END> + ", value=" + value; }</code><technical_language>include new fields invalidateNearCache toString method</technical_language>

Target:
public String toString() { return "AbstractNearCacheRecord{" + "creationTime=" + creationTime + ", value=" + value + ", uuid=" + uuid + ", cachedAsNull=" + cachedAsNull + ", hits=" + hits + ", partitionId=" + partitionId + ", lastAccessTime=" + lastAccessTime + ", expirationTime=" + expirationTime + ", invalidationSequence=" + invalidationSequence + ", reservationId=" + reservationId + '}'; }
Source:
<code>public List<OrganizationMembershipShowDto> findUserAdminOrganizations(String username) { User user = userRepository.findByUsernameOrEmail(username, username); if (user.getOrganizationMemberships() == null || user.getOrganizationMemberships().size() == 0) { <START> return null; <END> } return user.getOrganizationMemberships().stream().map(OrganizationMembershipShowDto::new).collect(Collectors.toList()); }</code><technical_language>null return Collections.emptyList()</technical_language>

Target:
public List<OrganizationMembershipShowDto> findUserAdminOrganizations(String username) { User user = userRepository.findByUsernameOrEmail(username, username); if (user.getOrganizationMemberships() == null) { return Collections.emptyList(); } return user.getOrganizationMemberships().stream().map(OrganizationMembershipShowDto::new).collect(Collectors.toList()); }
Source:
<code>Mono<AmqpTransaction> createTransaction() { final Message message = Proton.message(); Declare declare = new Declare(); message.setBody(new AmqpValue(declare)); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = payloadSize + MAX_AMQP_HEADER_SIZE_BYTES; final byte[] bytes = new byte[allocationSize]; final int encodedSize = message.encode(bytes, 0, allocationSize); return sendLink.send(bytes, encodedSize, DeliveryImpl.DEFAULT_MESSAGE_FORMAT, null) .handle((outcome, sink) -> { if (!(outcome instanceof Declared)) { sink.error(new IllegalArgumentException("Expected a Declared, received: " + outcome)); return; } final Declared state = (Declared) outcome; final DeliveryState.DeliveryStateType stateType = state.getType(); switch (stateType) { case Accepted: break; case Rejected: break; case Declared: Binary txnId; Declared declared = (Declared) outcome; txnId = declared.getTxnId(); logger.verbose("Created new TX started: {}", txnId); sink.next(new AmqpTransaction(txnId.asByteBuffer())); break; <START> default: <END> } }); }</code><technical_language>Add a log throw exception for default case instead of leaving blank</technical_language>

Target:
Mono<AmqpTransaction> createTransaction() { final Message message = Proton.message(); Declare declare = new Declare(); message.setBody(new AmqpValue(declare)); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = payloadSize + MAX_AMQP_HEADER_SIZE_BYTES; final byte[] bytes = new byte[allocationSize]; final int encodedSize = message.encode(bytes, 0, allocationSize); return sendLink.send(bytes, encodedSize, DeliveryImpl.DEFAULT_MESSAGE_FORMAT, null) .handle((outcome, sink) -> { final DeliveryState.DeliveryStateType stateType = outcome.getType(); switch (stateType) { case Declared: Binary transactionId; Declared declared = (Declared) outcome; transactionId = declared.getTxnId(); sink.next(new AmqpTransaction(transactionId.asByteBuffer())); break; default: sink.error(new IllegalArgumentException("Expected a Declared, received: " + outcome)); logger.warning("Unknown DeliveryState type: {}", stateType); } }); }
Source:
<code>public SubscriptionHealth getSubscriptionHealth(TopicName topicName, String subscriptionName) { Subscription subscription = getSubscriptionDetails(topicName, subscriptionName); <START> TopicMetrics topicMetrics = topicService.getTopicMetrics(topicName); <END> SubscriptionMetrics subscriptionMetrics = getSubscriptionMetrics(topicName, subscriptionName); return subscriptionHealthCalculator.calculateHealth(subscription, topicMetrics, subscriptionMetrics); }</code><technical_language>This is counter intuitive. metrics zookeeper if try get metrics for existing topic zookeeper create empty nodes for is a problem for instance listing topics is dependent zookeeper tree. origin of this check I remember if this problem exists</technical_language>

Target:
public SubscriptionHealth getSubscriptionHealth(TopicName topicName, String subscriptionName) { Subscription subscription = getSubscriptionDetails(topicName, subscriptionName); TopicMetrics topicMetrics = topicService.getTopicMetrics(topicName); SubscriptionMetrics subscriptionMetrics = getSubscriptionMetrics(topicName, subscriptionName); return subscriptionHealthChecker.checkHealth(subscription, topicMetrics, subscriptionMetrics); }
Source:
<code>private void initialize() { if (getBatchSize() <= 0) { withBatchSize(1); logger.warn("batchSize should be 1 or greater -- setting batchSize to 1"); } if (getThreadCount() <= 0) { int threadCount = clients.size(); withThreadCount(threadCount); logger.warn("threadCount should be 1 or greater -- setting threadCount to number of hosts: " + threadCount); } if (initialized.getAndSet(true)) return; threadPool = new CallingThreadPoolExecutor(this, getThreadCount()); jobStartTime = Calendar.getInstance(); started.set(true); if(callArgsGenerator != null) { Forest[] forests; String[] forestNames = null; if(forestParamName!=null) { <START> forests = super.getForestConfig().listForests(); <END> forestNames = new String[forests.length]; int j=0; for(Forest i:forests) { forestNames[j] = i.getForestName(); j++; } } for (int i=0;i<getThreadCount(); i++) { CallArgs newInput = callArgsGenerator.apply(null); if(forestNames!=null && forestNames[i]!=null) { newInput.param(forestParamName, forestNames[i]); } if(newInput != null) { if(!(newInput instanceof CallArgsImpl)) throw new MarkLogicInternalException("Unsupported implementation of call arguments."); submitCall((CallArgsImpl) newInput); } } } }</code><technical_language>minimize scope of variable initialize point of declaration removing line 495 declare forests variable line 498</technical_language>

Target:
private void initialize() { if (getBatchSize() <= 0) { withBatchSize(1); logger.warn("batchSize should be 1 or greater -- setting batchSize to 1"); } if (getThreadCount() <= 0) { int threadCount = clients.size(); withThreadCount(threadCount); logger.warn("threadCount should be 1 or greater -- setting threadCount to number of hosts: " + threadCount); } if (initialized.getAndSet(true)) return; threadPool = new CallingThreadPoolExecutor(this, getThreadCount()); jobStartTime = Calendar.getInstance(); started.set(true); if(callArgsGenerator != null) { String[] forestNames = null; if(forestParamName!=null) { Forest[] forests; forests = super.getForestConfig().listForests(); forestNames = new String[forests.length]; int j=0; for(Forest i:forests) { forestNames[j] = i.getForestName(); j++; } } for (int i=0;i<getThreadCount(); i++) { CallArgs newInput = callArgsGenerator.apply(null); if(forestNames!=null && forestNames[i]!=null) { newInput.param(forestParamName, forestNames[i]); } if(newInput != null) { if(!(newInput instanceof CallArgsImpl)) throw new MarkLogicInternalException("Unsupported implementation of call arguments."); submitCall((CallArgsImpl) newInput); } } } }
Source:
<code>private String redirectToEdit(String urlSuffix) { try { String referrer = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap() .get("referer"); String callerViewId = referrer.substring(referrer.lastIndexOf("/") + 1); if (!callerViewId.isEmpty() && callerViewId.contains("projects.jsf")) { return "/pages/rulesetEdit" + urlSuffix; } else { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } } catch (NullPointerException e) { <START> return "/pages/ProjekteBearbeiten" + urlSuffix; <END> } }</code><technical_language>This wrong. edit page for projects returned if in ruleset editing</technical_language>

Target:
private String redirectToEdit(String urlSuffix) { try { String referrer = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap() .get("referer"); String callerViewId = referrer.substring(referrer.lastIndexOf("/") + 1); if (!callerViewId.isEmpty() && callerViewId.contains("projects.jsf")) { return "/pages/rulesetEdit" + urlSuffix; } else { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } } catch (NullPointerException e) { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } }
Source:
<code>private boolean sourceIsAvailable(String sourceId){ try { final SourceInfoRequest sourceInfoRequest = new SourceInfoRequestSources(false, Collections.singleton(sourceId)); final SourceInfoResponse sourceInfoResponse = catalogFramework.getSourceInfo(sourceInfoRequest); final Set<SourceDescriptor> sourceDescriptors = sourceInfoResponse.getSourceInfo(); final SourceDescriptor sourceDescriptor = Iterables.getOnlyElement(sourceDescriptors); return sourceDescriptor.isAvailable(); } catch (Exception e){ <START> LOGGER.info("Couldn't get availability on source {}: {}", sourceId, e); <END> } return false; }</code><technical_language>LOGGER.info("Couldn't get availability of source {}", sourceId, e);</technical_language>

Target:
private int sourceIsAvailable(String sourceId) { try { final SourceInfoRequest sourceInfoRequest = new SourceInfoRequestSources(false, Collections.singleton(sourceId)); final SourceInfoResponse sourceInfoResponse = catalogFramework.getSourceInfo(sourceInfoRequest); final Set<SourceDescriptor> sourceDescriptors = sourceInfoResponse.getSourceInfo(); if (sourceDescriptors.isEmpty()) { return STATUS_PENDING; } final SourceDescriptor sourceDescriptor = Iterables.getOnlyElement(sourceDescriptors); if (sourceDescriptor.getLastAvailabilityDate() == null) { return STATUS_PENDING; } if (sourceDescriptor.isAvailable()) { return AVAILABLE; } } catch (Exception e) { LOGGER.info("Couldn't get availability on source {}", sourceId, e); } return UNAVAILABLE; }
Source:
<code>private Response<AnalyzeSentimentResultCollection> toAnalyzeSentimentResultCollectionResponse( Response<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment)); } for (DocumentError documentError : sentimentResponse.getErrors()) { <START> analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, <END> toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics()))); }</code><technical_language>Please consider this in another PR for separation of concern</technical_language>

Target:
private Response<AnalyzeSentimentResultCollection> toAnalyzeSentimentResultCollectionResponse( Response<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); final List<DocumentSentiment> documentSentiments = sentimentResponse.getDocuments(); for (DocumentSentiment documentSentiment : documentSentiments) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment, documentSentiments)); } for (DocumentError documentError : sentimentResponse.getErrors()) { analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics()))); }
Source:
<code>public URL getQueueUrl() { try { return new URL(client.url()); } catch (MalformedURLException ex) { <START> throw new RuntimeException("Queue URL is malformed"); <END> } }</code><technical_language>ClientLogger.logAndThrow exceptions. Please search for cases soon Shawn check in CheckStyle rule break build</technical_language>

Target:
public URL getQueueUrl() { try { return new URL(client.url()); } catch (MalformedURLException ex) { LOGGER.asError().log("Queue URL is malformed"); throw new RuntimeException("Queue URL is malformed"); } }
Source:
<code><START> public static boolean isKeyFrame(byte[] buf, int off, int len){ <END> if (!isValid(buf, off, len)) { return false; } if((buf[off] & P_BIT) != 0 || (buf[off] & B_BIT) == 0) { return false; } int loff = off + 1; if ((buf[off] & I_BIT) != 0) { loff += 1; if ((buf[off + 1] & (1 << 7)) != 0) { loff += 1; } } return ((buf[loff] & 0xE) >> 1) == 0 || (buf[loff] & 0x1) == 0; }</code><technical_language>Tiny nit-pick: new-line</technical_language>

Target:
public static boolean isKeyFrame(byte[] buf, int off, int len) { if (!isValid(buf, off, len)) { return false; } if((buf[off] & P_BIT) != 0 || (buf[off] & B_BIT) == 0 || (buf[off] & L_BIT) == 0 ) { return false; } int loff = off + 1; if ((buf[off] & I_BIT) != 0) { loff += 1; if ((buf[off + 1] & (1 << 7)) != 0) { loff += 1; } } return ((buf[loff] & SID_MASK) >> 1) == 0 || (buf[loff] & D_MASK) == 0; }