auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testIsMapFunctionExtension1() throws InterruptedException { log.info("RemoveFunctionExtension TestCase with test attributeExpressionExecutors length"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream " + "select symbol,price,map:create() as tmpMap" + " insert into tmpStream;" + "@info(name = 'query2') from tmpStream select symbol,price,tmpMap, map:put(tmpMap,symbol,price) as map1" + " insert into outputStream;" + "@info(name = 'query3') from outputStream " + "select map:isMap(map1) as isMap1,map:isMap(symbol,price) as isMap2" + " insert into outputStream2;" ); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); <START> InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); <END> executionPlanRuntime.start(); executionPlanRuntime.shutdown(); }</code><technical_language>lines needed. createExecutionplanRuntime throw exception</technical_language>

Target:
public void testIsMapFunctionExtension1() throws InterruptedException { log.info("RemoveFunctionExtension TestCase with test attributeExpressionExecutors length"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream " + "select symbol,price,map:create() as tmpMap" + " insert into tmpStream;" + "@info(name = 'query2') from tmpStream select symbol,price,tmpMap, map:put(tmpMap,symbol,price) "+ "as map1 insert into outputStream;" + "@info(name = 'query3') from outputStream " + "select map:isMap(map1) as isMap1,map:isMap(symbol,price) as isMap2" + " insert into outputStream2;" ); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.start(); executionPlanRuntime.shutdown(); }
Source:
<code>public static Collection<ITmfTrace> getTraceSet(@Nullable ITmfTrace trace) { if (trace == null) { return ImmutableSet.of(); } List<@NonNull ITmfTrace> traces = trace.getChildren(ITmfTrace.class); <START> if (traces.size() > 0) { <END> Iterable<ITmfTrace> iterable = checkNotNull(Iterables.concat(Iterables.transform(traces, t -> getTraceSet(t)))); return ImmutableSet.copyOf(iterable); } return ImmutableSet.of(trace); }</code><technical_language>isEmpty</technical_language>

Target:
public static Collection<ITmfTrace> getTraceSet(@Nullable ITmfTrace trace) { if (trace == null) { return ImmutableSet.of(); } List<@NonNull ITmfTrace> traces = trace.getChildren(ITmfTrace.class); if (!traces.isEmpty()) { Iterable<ITmfTrace> iterable = checkNotNull(Iterables.concat(Iterables.transform(traces, t -> getTraceSet(t)))); return ImmutableSet.copyOf(iterable); } return ImmutableSet.of(trace); }
Source:
<code>private Input retrieveInput(String key) { validate(); Set<Entry<String, LinkedList<Input>>> set = items.entrySet(); for (Entry<String, LinkedList<Input>> entry: set) { String entryKey = entry.getKey(); LinkedList<Input> entryValue = entry.getValue(); InputKind kind = entryValue.get(0).getKind(); if (InputCollection.matchesInputName(kind, key, entryKey)) { if (entryValue.size() > 1) { throw new SplunkException(SplunkException.AMBIGUOUS, <START> "Key has multiple values, specify a namespace"); <END> } else { return entryValue.get(0); } } } return null; }</code><technical_language>user is idea "Key multiple values" means</technical_language>

Target:
private Input retrieveInput(String key) { validate(); Set<Entry<String, LinkedList<Input>>> set = items.entrySet(); for (Entry<String, LinkedList<Input>> entry: set) { String entryKey = entry.getKey(); LinkedList<Input> entryValue = entry.getValue(); InputKind kind = entryValue.get(0).getKind(); if (InputCollection.matchesInputName(kind, key, entryKey)) { if (entryValue.size() > 1) { throw new SplunkException(SplunkException.AMBIGUOUS, "Multiple inputs matched " + key + "; specify a namespace to disambiguate."); } else { return entryValue.get(0); } } } return null; }
Source:
<code><START> public ShowDiffPreferencesCommand( <END> ListenableAccountDiffPreference prefs) { super(0, 's', PatchUtil.C.showSettings()); this.prefs = prefs; }</code><technical_language>need public</technical_language>

Target:
ShowDiffPreferencesCommand( ListenableAccountDiffPreference prefs) { super(0, 's', PatchUtil.C.showSettings()); this.prefs = prefs; }
Source:
<code>public <T extends RegisteredService> T findServiceBy(final long id, final Class<T> clazz) { <START> val result = this.serviceRegistry.findServiceById(id, clazz); if (result != null) { services.get(result.getId(), k -> result); } return result; } <END></code><technical_language>This right. be: result = services.get(result.getId(), -> this.serviceRegistry.findServiceById(id, clazz)); Also, forget check result correct type based clazz</technical_language>

Target:
public <T extends RegisteredService> T findServiceBy(final long id, final Class<T> clazz) { var service = getService(null, id); if (service != null && service.getClass().equals(clazz)) { return (T) service; } else { LOGGER.trace("The service with id and type is not found in the cache; trying to find it from [{}]", id, clazz, serviceRegistry.getName()); service = services.get(id, k -> this.serviceRegistry.findServiceById(id, clazz)); } return (T) validateRegisteredService(service); }
Source:
<code>public static SQLQuery parse(String sql) { Preconditions.checkNotNull(sql); SQLQuery query = new SQLQuery(); Scanner scanner = new Scanner(sql.trim()); String op = scanner.next("\\w+"); if ("SELECT".equalsIgnoreCase(op)) { query.setOperation(Operation.READ); while (! scanner.hasNext("(?i)FROM")) { scanner.next(); } scanner.next(); <START> String table = scanner.useDelimiter(",").next(); <END> query.setTableName(table.trim()); } else if ("INSERT".equalsIgnoreCase(op)){ query.setOperation(Operation.WRITE); while (! scanner.hasNext("(?i)INTO")) { scanner.next(); } scanner.next(); String table = scanner.useDelimiter("[,\\(]").next(); query.setTableName(table.trim()); } else if ("UPDATE".equalsIgnoreCase(op)) { query.setOperation(Operation.WRITE); query.setTableName(scanner.next()); } else if( "DELETE".equalsIgnoreCase(op)) { query.setOperation(Operation.WRITE); scanner.next(); String table = scanner.next(); query.setTableName(table.trim()); } else { LOGGER.error("Error during parsing query:\n{}",sql); } scanner.close(); return query; }</code><technical_language>Try this assertEquals("FooBar", SQLParser.parse("select age FooBar id = ?").getTableName()); care put SQLParser code huge impact, is core lowest level code in this component. heavily tested ;)</technical_language>

Target:
public static SQLQuery parse(String sql) { Preconditions.checkNotNull(sql); SQLQuery query = new SQLQuery(); Scanner scanner = new Scanner(sql.trim()); String op = scanner.next("\\w+"); if ("SELECT".equalsIgnoreCase(op)) { query.setOperation(Operation.READ); while (! scanner.hasNext("(?i)FROM")) { scanner.next(); } scanner.next(); String table = keepSingleValue(scanner.next()); query.setTableName(table.trim()); } else if ("INSERT".equalsIgnoreCase(op)){ query.setOperation(Operation.WRITE); while (! scanner.hasNext("(?i)INTO")) { scanner.next(); } scanner.next(); String table = scanner.useDelimiter("[,\\(\\s]").next(); query.setTableName(table.trim()); } else if ("UPDATE".equalsIgnoreCase(op)) { query.setOperation(Operation.WRITE); query.setTableName(scanner.next()); } else if( "DELETE".equalsIgnoreCase(op)) { query.setOperation(Operation.WRITE); scanner.next(); String table = scanner.next(); query.setTableName(table.trim()); } else { LOGGER.error("Error during parsing query:\n{}",sql); } scanner.close(); return query; }
Source:
<code>public void apply(OfflineCommandContext ctx) throws CommandFailedException, IOException { Map<String, Object> groovyAttributes = new HashMap<String, Object>(); groovyAttributes.put("atrConnectionName", connectionName); groovyAttributes.put("atrHandlesReferralsFor", handlesReferralsFor); groovyAttributes.put("atrInitialContextFactory", initialContextFactory); groovyAttributes.put("atrReferrals", referrals); groovyAttributes.put("atrSearchCredential", searchCredential); groovyAttributes.put("atrSearchDn", searchDn); groovyAttributes.put("atrSecurityRealm", securityRealm); groovyAttributes.put("atrUrl", url); groovyAttributes.put("atrReplaceExisting", replaceExisting); groovyAttributes.put("atrProperties", properties); ctx.client.apply(GroovyXmlTransform.of(AddLdapConnection.class) <START> .parameters(groovyAttributes) <END> .subtree("management", Subtree.management()) .build()); }</code><technical_language>parameter here, this: java ctx.client.apply(GroovyXmlTransform.of(AddLdapConnection.class) .parameter("atrConnectionName", connectionName) .parameter("atrHandlesReferralsFor", handlesReferralsFor) building a Map upfront is bad, for this straightforward case, I sense</technical_language>

Target:
public void apply(OfflineCommandContext ctx) throws Exception { ctx.client.apply(GroovyXmlTransform.of(AddLdapConnection.class) .subtree("management", Subtree.management()) .parameter("atrConnectionName", connectionName) .parameter("atrHandlesReferralsFor", handlesReferralsFor) .parameter("atrInitialContextFactory", initialContextFactory) .parameter("atrReferrals", referrals) .parameter("atrSearchCredential", searchCredential) .parameter("atrSearchDn", searchDn) .parameter("atrSecurityRealm", securityRealm) .parameter("atrUrl", url) .parameter("atrReplaceExisting", replaceExisting) .parameter("atrProperties", properties) .build()); }
Source:
<code>private static void addNoticeForMultipleValues(final RdapObject rdapObject, final AttributeType type, final List<RpslAttribute> values, final String key) { if(values.isEmpty() || values.size() == 1) { return; } <START> final String commaSeperatedValues = values.stream().map( x -> x.getCleanValue()).collect(Collectors.joining(",")); <END> final String title = String.format("Multiple %s attributes found", type.getName()); final String desc = String.format("There are multiple %s attributes %s in %s, but only the first %s %s was returned.", type.getName(), commaSeperatedValues, key, type.getName(), values.get(0).getCleanValue()); final Notice notice = new Notice(); notice.setTitle(title); notice.getDescription().add(desc); rdapObject.getNotices().add(notice); }</code><technical_language>a more descriptive variable name 'x' :)</technical_language>

Target:
private static void addNoticeForMultipleValues(final RdapObject rdapObject, final AttributeType type, final List<RpslAttribute> values, final String key) { if(values.isEmpty() || values.size() == 1) { return; } final String commaSeperatedValues = values.stream().map( value -> value.getCleanValue()).collect(Collectors.joining(", ")); final String title = String.format("Multiple %s attributes found", type.getName()); final String desc = String.format("There are multiple %s attributes %s in %s, but only the first %s %s was returned.", type.getName(), commaSeperatedValues, key, type.getName(), values.get(0).getCleanValue()); final Notice notice = new Notice(); notice.setTitle(title); notice.getDescription().add(desc); rdapObject.getNotices().add(notice); }
Source:
<code>public void filter(DocumentIndexingPackage dip) throws IndexingException { log.debug("Performing Datastream filter for object {}", dip.getPid()); ContentObject contentObj = dip.getContentObject(); FileObject fileObj = getFileObject(contentObj); if (fileObj != null) { boolean ownedByOtherObject = contentObj instanceof WorkObject; List<Datastream> datastreams = getDatastreams(fileObj, ownedByOtherObject); List<Datastream> derivatives = getDerivatives(fileObj.getPid(), ownedByOtherObject); datastreams.addAll(derivatives); IndexDocumentBean doc = dip.getDocument(); doc.setDatastream(getDatastreamStrings(datastreams)); doc.setFilesizeTotal(getFilesizeTotal(datastreams)); doc.setFilesizeSort(getFilesize(datastreams)); <START> } else if (contentObj instanceof CollectionObject) { <END> List<Datastream> derivatives = getDerivatives(contentObj.getPid(), false); List<Datastream> datastreams = new ArrayList<>(derivatives); IndexDocumentBean doc = dip.getDocument(); doc.setDatastream(getDatastreamStrings(datastreams)); } }</code><technical_language>indexing derivatives is sufficiently generic i remove collection object restriction</technical_language>

Target:
public void filter(DocumentIndexingPackage dip) throws IndexingException { log.debug("Performing Datastream filter for object {}", dip.getPid()); ContentObject contentObj = dip.getContentObject(); FileObject fileObj = getFileObject(contentObj); if (fileObj != null) { boolean ownedByOtherObject = contentObj instanceof WorkObject; List<Datastream> datastreams = getDatastreams(fileObj, ownedByOtherObject); List<Datastream> derivatives = getDerivatives(fileObj.getPid(), ownedByOtherObject); datastreams.addAll(derivatives); IndexDocumentBean doc = dip.getDocument(); doc.setDatastream(getDatastreamStrings(datastreams)); doc.setFilesizeTotal(getFilesizeTotal(datastreams)); doc.setFilesizeSort(getFilesize(datastreams)); } else { List<Datastream> derivatives = getDerivatives(contentObj.getPid(), false); IndexDocumentBean doc = dip.getDocument(); doc.setDatastream(getDatastreamStrings(derivatives)); } }
Source:
<code>public LedgerEntry getEntry(long entryId) { long firstId = entries.get(0).getEntryId(); long lastId = entries.get(entries.size() - 1).getEntryId(); if (entryId < firstId || entryId > lastId) { <START> return null; <END> } return entries.get((int)(entryId - firstId)); }</code><technical_language>follow pattern ArrayList works. throw ArrayIndexOutOfBoundsException requesting entry is out of range</technical_language>

Target:
public LedgerEntry getEntry(long entryId) { checkNotNull(entries, "entries has been recycled"); long firstId = entries.get(0).getEntryId(); long lastId = entries.get(entries.size() - 1).getEntryId(); if (entryId < firstId || entryId > lastId) { throw new IndexOutOfBoundsException("required index: " + entryId + " is out of bounds: [ " + firstId + ", " + lastId + " ]."); } return entries.get((int) (entryId - firstId)); }
Source:
<code>protected Integer[] doInBackground(Void... voids) { <START> System.out.println("doInBackground"); <END> Integer[] result = {0,0,0}; try { SmartCardController smartCardController = ((MuzimaApplication)context).getSmartCardController(); List<SmartCardRecord> smartCardRecords = smartCardController.getSmartCardRecordWithNonUploadedData(); for(SmartCardRecord smartCardRecord : smartCardRecords){ if (smartCardController.syncSmartCardRecord(smartCardRecord)) { smartCardRecord.setEncryptedPayload(null); try { smartCardController.updateSmartCardRecord(smartCardRecord); } catch (SmartCardController.SmartCardRecordSaveException e) { Log.e(TAG, "Exception thrown while updating smartcard record.", e); } result[1]++; } else { result[0] = UPLOAD_ERROR; result[2]++; } } if(result[0] != UPLOAD_ERROR){ result[0] = SUCCESS; } return result; } catch (SmartCardController.SmartCardRecordFetchException e) { Log.e(TAG, "Exception thrown while uploading smartcard record.", e); result[0] = UPLOAD_ERROR; } return result; }</code><technical_language>Logging standard output</technical_language>

Target:
protected Integer[] doInBackground(Void... voids) { Integer[] result = {0,0,0}; try { SmartCardController smartCardController = ((MuzimaApplication)context).getSmartCardController(); List<SmartCardRecord> smartCardRecords = smartCardController.getSmartCardRecordWithNonUploadedData(); for(SmartCardRecord smartCardRecord : smartCardRecords){ if (smartCardController.syncSmartCardRecord(smartCardRecord)) { smartCardRecord.setEncryptedPayload(null); try { smartCardController.updateSmartCardRecord(smartCardRecord); } catch (SmartCardController.SmartCardRecordSaveException e) { Log.e(TAG, "Exception thrown while updating smartcard record.", e); } result[1]++; } else { result[0] = UPLOAD_ERROR; result[2]++; } } if(result[0] != UPLOAD_ERROR){ result[0] = SUCCESS; } return result; } catch (SmartCardController.SmartCardRecordFetchException e) { Log.e(TAG, "Exception thrown while uploading smartcard record.", e); result[0] = UPLOAD_ERROR; } return result; }
Source:
<code>protected abstract void flush(byte[] payload) throws TTransportException; protected void handleResponse(byte[] frame) throws TException { Map<String, String> headers; headers = HeaderUtils.decodeFromFrame(frame); long opId; try { opId = Long.parseLong(headers.get(FContext.OPID_HEADER)); } catch (NumberFormatException e) { <START> throw new TException("invalid protocol frame: op id not a uint64", e); <END> } BlockingQueue<byte[]> queue; synchronized (this) { queue = queueMap.get(opId); } if (queue == null) { return; } try { queue.put(frame); } catch (InterruptedException e) { throw new TException(e); } }</code><technical_language>this a TProtocolException</technical_language>

Target:
protected abstract void flush(byte[] payload) throws TTransportException; protected void handleResponse(byte[] frame) throws TException { Map<String, String> headers; headers = HeaderUtils.decodeFromFrame(frame); long opId; try { opId = Long.parseLong(headers.get(FContext.OPID_HEADER)); } catch (NumberFormatException e) { throw new TProtocolException("invalid protocol frame: op id not a uint64", e); } BlockingQueue<byte[]> queue; synchronized (this) { queue = queueMap.get(opId); } if (queue == null) { return; } try { queue.put(frame); } catch (InterruptedException e) { throw new TException(e); } }
Source:
<code>public void startSpan() { final Tracer tracer1 = mock(Tracer.class); <START> List<Tracer> tracers = new ArrayList<>(Arrays.asList(tracer1)); <END> final TracerProvider tracerProvider = new TracerProvider(tracers); Context updatedContext = tracerProvider.startSpan(Context.NONE, ProcessKind.SEND); verify(tracer1, times(1)).start(eq("Azure.eventhubs.send"), any(), eq(ProcessKind.SEND)); }</code><technical_language>List<Tracer> tracers = Arrays.asList(tracer1); Arrays.asList returns a list, matches interface</technical_language>

Target:
public void startSpan() { tracerProvider.startSpan(Context.NONE, ProcessKind.SEND); for (Tracer t : tracers) { verify(t, times(1)) .start(eq(METHOD_NAME), any(), eq(ProcessKind.SEND)); } }
Source:
<code>public void start() { <START> if (namingContext != null) { <END> return; } this.messageSender = new MessageSender(configuration); install(); }</code><technical_language>I see, namingContext is assigned, this check is pointless</technical_language>

Target:
public void start() throws NamingException, JMSException { if (namingContext != null) { return; } namingContext = new InitialContext(); TopicConnectionFactory tcf = (TopicConnectionFactory) namingContext.lookup( configuration.getConnectionFactoryJndiName()); ConnectionContextFactory ccf = new ConnectionContextFactory(tcf); this.messageSender = new MessageSender(ccf, configuration.getInventoryChangesTopicName()); install(); }
Source:
<code>static boolean equalsVariableTime(CharSequence s1, CharSequence s2) { if (s1 instanceof AsciiString && s2 instanceof AsciiString) { return s1.equals(s2); } <START> return String.valueOf(s1).equals(String.valueOf(s2)); <END> }</code><technical_language>@carl-mastrangelo I use: java return AsciiString.contentEquals(s1, s2);</technical_language>

Target:
static boolean equalsVariableTime(CharSequence s1, CharSequence s2) { return AsciiString.contentEquals(s1, s2); }
Source:
<code>private void updateDataSourceStringValue(CorrelationDataSource eamDataSource, String column, String value) throws EamDbException { if (eamDataSource == null) { throw new EamDbException("Correlation data source is null"); } Connection conn = connect(); PreparedStatement preparedStatement = null; String sql = "UPDATE data_sources " + "SET " + column + "=? " + "WHERE id=?"; try { preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, value); preparedStatement.setInt(2, eamDataSource.getID()); preparedStatement.executeUpdate(); dataSourceCacheByDsObjectId.put(getDataSourceByDSObjectIdCacheKey(eamDataSource.getCaseID(), eamDataSource.getDataSourceObjectID()), eamDataSource); dataSourceCacheById.put(getDataSourceByIdCacheKey(eamDataSource.getCaseID(), eamDataSource.getID()), eamDataSource); } catch (SQLException ex) { <START> throw new EamDbException("Error updating data source.", ex); END> } finally { EamDbUtil.closeStatement(preparedStatement); EamDbUtil.closeConnection(conn); } }</code><technical_language>@dgrove727 @APriestman, exception messages neglect provide debug info it. E.g., provide ID of data source "Error updating data source" data source failed update</technical_language>

Target:
private void updateDataSourceStringValue(CorrelationDataSource eamDataSource, String column, String value) throws EamDbException { if (eamDataSource == null) { throw new EamDbException("Correlation data source is null"); } Connection conn = connect(); PreparedStatement preparedStatement = null; String sql = "UPDATE data_sources " + "SET " + column + "=? " + "WHERE id=?"; try { preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, value); preparedStatement.setInt(2, eamDataSource.getID()); preparedStatement.executeUpdate(); dataSourceCacheByDsObjectId.put(getDataSourceByDSObjectIdCacheKey(eamDataSource.getCaseID(), eamDataSource.getDataSourceObjectID()), eamDataSource); dataSourceCacheById.put(getDataSourceByIdCacheKey(eamDataSource.getCaseID(), eamDataSource.getID()), eamDataSource); } catch (SQLException ex) { throw new EamDbException(String.format("Error updating data source (obj_id=%d).", eamDataSource.getDataSourceObjectID()), ex); } finally { EamDbUtil.closeStatement(preparedStatement); EamDbUtil.closeConnection(conn); } }
Source:
<code>public BulkLoadingListener() { this.counter = 0L; this.isNewVertex = false; <START> ; <END> }</code><technical_language>empty code line - remove merge</technical_language>

Target:
public BulkLoadingListener() { this.counter = 0L; this.isNewVertex = false; }
Source:
<code>public void testSaveBulkNullId() throws Exception { List<Document> documents = new Vector<Document>(); documents.add(new Document(null, System.currentTimeMillis(), mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST")))); documents.add(new Document(UUID.randomUUID().toString(), System.currentTimeMillis(), mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST")))); <START> queryStore.save(TestUtils.TEST_TABLE_NAME, documents); <END> }</code><technical_language>Check for equality of error code</technical_language>

Target:
public void testSaveBulkNullId() throws Exception { List<Document> documents = new Vector<Document>(); documents.add(new Document(null, System.currentTimeMillis(), mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST")))); documents.add(new Document(UUID.randomUUID().toString(), System.currentTimeMillis(), mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST")))); try { queryStore.save(TestUtils.TEST_TABLE_NAME, documents); } catch (QueryStoreException e) { assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, e.getErrorCode()); throw e; } }
Source:
<code>long getSlice(String jobType, String jobId, long usedSinceLastCall) <START> throws InterruptedException { <END> Throttler throttler = throttlers.get(jobType); if (throttler != null) { throttler.maybeThrottle(usedSinceLastCall); } return Long.MAX_VALUE; }</code><technical_language>a good idea throw InterruptedException sense for getSlice(). convert thrown throttler IllegalStateException</technical_language>

Target:
long getSlice(String jobType, String jobId, long usedSinceLastCall) { Throttler throttler = throttlers.get(jobType); if (throttler != null) { try { throttler.maybeThrottle(usedSinceLastCall); } catch (InterruptedException e) { throw new IllegalStateException("Throttler call interrupted", e); } } return Long.MAX_VALUE; }
Source:
<code>public DocumentModel createEntryWithoutReferences(Map<String, Object> fieldMap) { checkClose(); Object rawId = fieldMap.get(getIdField()); if (rawId == null) { throw new DirectoryException("Missing id"); } String id = String.valueOf(rawId); Map<String, Object> map = data.get(id); if (map != null) { throw new DirectoryException( <START> String.format("Entry with id %s already exists on directory '%s'", id, directory.getName())); <END> } map = new HashMap<>(); data.put(id, map); for (Entry<String, Object> e : fieldMap.entrySet()) { String fieldName = e.getKey(); if (!getDirectory().schemaSet.contains(fieldName)) { continue; } map.put(fieldName, e.getValue()); } return getEntry(id); }</code><technical_language>suggestion String.format("Entry id %s exists in directory '%s'", id, directory.getName()));</technical_language>

Target:
public DocumentModel createEntryWithoutReferences(Map<String, Object> fieldMap) { checkClose(); Object rawId = fieldMap.get(getIdField()); if (rawId == null) { throw new DirectoryException("Missing id"); } String id = String.valueOf(rawId); Map<String, Object> map = data.get(id); if (map != null) { throw new DirectoryException( String.format("Entry with id %s already exists in directory %s", id, directory.getName())); } map = new HashMap<>(); data.put(id, map); for (Entry<String, Object> e : fieldMap.entrySet()) { String fieldName = e.getKey(); if (!getDirectory().schemaSet.contains(fieldName)) { continue; } map.put(fieldName, e.getValue()); } return getEntry(id); }
Source:
<code>private Fix createCheckArgumentOrStateCall( MethodInvocationTree methodInvocationTree, VisitorState state, ExpressionTree arg1) { SuggestedFix.Builder fix = SuggestedFix.builder(); String replacementMethod = "checkState"; if (hasMethodParameter(state.getPath(), arg1)) { replacementMethod = "checkArgument"; } StringBuilder replacement = new StringBuilder(); if (methodInvocationTree.getMethodSelect().getKind() == Kind.IDENTIFIER) { <START> replacement.append(replacementMethod).append("("); <END> fix.addStaticImport("com.google.common.base.Preconditions." + replacementMethod); } else { replacement.append("Preconditions.").append(replacementMethod).append("("); } Joiner.on(", ").appendTo(replacement, methodInvocationTree.getArguments()); replacement.append(")"); fix.replace(methodInvocationTree, replacement.toString()); return fix.build(); }</code><technical_language>pulling this out of if/else entirely? else append("Preconditions") .append(replacementMethod).append('(') for cases</technical_language>

Target:
private Fix createCheckArgumentOrStateCall( MethodInvocationTree methodInvocationTree, VisitorState state, ExpressionTree arg1) { SuggestedFix.Builder fix = SuggestedFix.builder(); String replacementMethod = "checkState"; if (hasMethodParameter(state.getPath(), arg1)) { replacementMethod = "checkArgument"; } StringBuilder replacement = new StringBuilder(); if (methodInvocationTree.getMethodSelect().getKind() == Kind.IDENTIFIER) { fix.addStaticImport("com.google.common.base.Preconditions." + replacementMethod); } else { replacement.append("Preconditions."); } replacement.append(replacementMethod).append('('); Joiner.on(", ").appendTo(replacement, methodInvocationTree.getArguments()); replacement.append(")"); fix.replace(methodInvocationTree, replacement.toString()); return fix.build(); }
Source:
<code>default void register(SystemStreamPartition systemStreamPartition, Startpoint startpoint) { <START> throw new UnsupportedOperationException("This operation is not supported."); <END> }</code><technical_language>please exception message more descriptive</technical_language>

Target:
default void register(SystemStreamPartition systemStreamPartition, Startpoint startpoint) { throw new UnsupportedOperationException(String.format("Registering the ssp: %s with startpoint: %s is not supported.", systemStreamPartition, startpoint)); }
Source:
<code>public void testComponentActionManager() { setupActionList(); setupActionGetViewId(); ComponentActionManager actionManager = new ComponentActionManager(actionList); <START> assertNotNull(actionManager); <END> }</code><technical_language>is tested here. create multiple actions of a trigger type in test create that. is output of create a Manager that</technical_language>

Target:
public void testComponentActionManager() { setupActionList(); ComponentActionManager actionManager = new ComponentActionManager(actionList); assertNotNull(actionManager); }
Source:
<code>protected List<DiskImage> manualAggregateSnapshots() { List<DiskImage> diskImageWithAggregatedSnapshots = new ArrayList<>(); <START> DiskImage diskWithSnaps = diskWithSnapshots; <END> diskWithSnaps.getSnapshots().addAll(snapshotsList); diskImageWithAggregatedSnapshots.add(diskWithSnapshots); return diskImageWithAggregatedSnapshots; }</code><technical_language>Do need this</technical_language>

Target:
protected List<DiskImage> manualAggregateSnapshots() { diskWithSnapshots.getSnapshots().addAll(snapshotsList); return Collections.singletonList(diskWithSnapshots); }
Source:
<code>public String getMail(Model model, HttpSession session, @RequestParam(value = "inbox", required = false) String inbox, @RequestParam(value = "sentmail", required = false) String sentmail, @RequestParam(value = "drafts", required = false) String drafts) { if (session.getAttribute("member") == null) return "redirect:denied"; Member member = (Member) session.getAttribute("member"); Set<Message> messages; <START> if (inbox != null) <END> messages = member.getMail().getMessages(); else if (sentmail != null) messages = member.getMail().getSentMail(); else if (drafts != null) messages = member.getMail().getDrafts(); else messages = member.getMail().getMessages(); List<Message> reversedMessages = new ArrayList<>(messages); Collections.reverse(reversedMessages); model.addAttribute("messages", reversedMessages); session.setAttribute("message", null); return "mail"; }</code><technical_language>I this if statement is necessary perform action in else</technical_language>

Target:
public String getMail( Model model, HttpSession session, @RequestParam(value = "inbox", required = false) String inbox, @RequestParam(value = "sentmail", required = false) String sentmail, @RequestParam(value = "drafts", required = false) String drafts) { Member member = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); member = memberDao.getMemberById(member.getId()); if (member == null) { return "redirect:/denied"; } Set<Message> messages; if (sentmail != null) messages = member.getMail().getSentMail(); else if (drafts != null) messages = member.getMail().getDrafts(); else messages = member.getMail().getMessages(); List<Message> reversedMessages = new ArrayList<>(messages); Collections.reverse(reversedMessages); model.addAttribute("messages", reversedMessages); session.setAttribute("message", null); Set<Team> teams = member.getTeams(); model.addAttribute("teams", teams); TournamentDao tournamentDao = new TournamentDao(); List<Tournament> tournaments = tournamentDao.getLastXTournaments(5); model.addAttribute("tournaments", tournaments); return "mail"; }
Source:
<code>public ValueDerivatives(double value, double[] derivatives) { this._value = value; <START> this._derivatives = derivatives; <END> }</code><technical_language>clone Arrays.copyOf</technical_language>

Target:
public ValueDerivatives(double value, double[] derivatives) { this._value = value; this._derivatives = derivatives.clone(); }
Source:
<code>public boolean register(String target, String xp, Descriptor descriptor) { <START> log.trace("Register to {}/{}", descriptor.getId(), target, xp); <END> return descriptors.computeIfAbsent(target, k -> new HashMap<>()) .computeIfAbsent(xp, k -> new LinkedHashMap<>()) .computeIfAbsent(descriptor.getId(), k -> new ArrayList<>()) .add(descriptor); }</code><technical_language>prefer debug for these. reserve trace logging low-level expensive stuff, traffic to/from a database huge outputs</technical_language>

Target:
public boolean register(String target, String xp, Descriptor descriptor) { log.debug("Register to {}/{}", descriptor.getId(), target, xp); return descriptors.computeIfAbsent(target, k -> new HashMap<>()) .computeIfAbsent(xp, k -> new LinkedHashMap<>()) .computeIfAbsent(descriptor.getId(), k -> new ArrayList<>()) .add(descriptor); }
Source:
<code>static int getPriority(TableName tableName) { <START> if (tableName.isSystemTable() && !tableName.equals(SlowLogTableAccessor.SLOW_LOG_TABLE_NAME)) { <END> return HConstants.SYSTEMTABLE_QOS; } else { return HConstants.NORMAL_QOS; } }</code><technical_language>Good. This is set priority</technical_language>

Target:
static int getPriority(TableName tableName) { if (tableName.isSystemTable()) { return HConstants.SYSTEMTABLE_QOS; } else { return HConstants.NORMAL_QOS; } }
Source:
<code>public void getElementTest() throws Exception { String craigsUrl = "<LINK_0>"; String expH2 = "san francisco"; iface.go(craigsUrl); <START> WebDriverElement header = ((WebDriverElement) iface.getWebDriverElement(Strategy.ID, "topban")); <END> ((WebDriverElement) header.getElement(new Hook(Strategy.TAG, "a"), 1)).click(); header = ((WebDriverElement) iface.getWebDriverElement(Strategy.ID, "topban")); WebDriverElement h2Control = ((WebDriverElement) header.getElement(new Hook(Strategy.TAG, "h2"), 0)); String actH2 = h2Control.getText().trim(); Assert.assertEquals(expH2, actH2); }</code><technical_language>is casting necessary anymore</technical_language>

Target:
public void getElementTest() throws Exception { String craigsUrl = "<LINK_0>"; String expH2 = "san francisco"; iface.go(craigsUrl); WebDriverElement header = iface.getWebDriverElement(Strategy.ID, "topban"); ((WebDriverElement) header.getElement(new Hook(Strategy.TAG, "a"), 1)).click(); header = iface.getWebDriverElement(Strategy.ID, "topban"); WebDriverElement h2Control = ((WebDriverElement) header.getElement(new Hook(Strategy.TAG, "h2"), 0)); String actH2 = h2Control.getText().trim(); Assert.assertEquals(expH2, actH2); }
Source:
<code>public Mono<ServiceBusReceiverAsyncClient> acceptNextSession() { <START> return unNamedSessionManager.getActiveLink().flatMap(receiveLink -> receiveLink.getSessionId() <END> .map(sessionId -> { ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), sessionId, null, receiverOptions.getMaxLockRenewDuration()); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions, receiveLink); return new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, onClientClose, sessionSpecificManager); })); }</code><technical_language>client calls acceptNextSession : service bus get a lock session if client do do receiveMessages() it, session is locked, else get it. try ? getActiveLink() returns a Mono a user subscribe it, create link</technical_language>

Target:
public Mono<ServiceBusReceiverAsyncClient> acceptNextSession() { return unNamedSessionManager.getActiveLink().flatMap(receiveLink -> receiveLink.getSessionId() .map(sessionId -> { final ReceiverOptions newReceiverOptions = new ReceiverOptions(receiverOptions.getReceiveMode(), receiverOptions.getPrefetchCount(), receiverOptions.getMaxLockRenewDuration(), receiverOptions.isAutoLockRenewEnabled(), sessionId, null); final ServiceBusSessionManager sessionSpecificManager = new ServiceBusSessionManager(entityPath, entityType, connectionProcessor, tracerProvider, messageSerializer, newReceiverOptions, receiveLink); return new ServiceBusReceiverAsyncClient(fullyQualifiedNamespace, entityPath, entityType, newReceiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT, tracerProvider, messageSerializer, () -> { }, sessionSpecificManager); })); }
Source:
<code>private String visitSyntheticModuleTypes(ObjectType type) { <START> Node source = type.getConstructor().getSource(); <END> InputId id = source.getInputId(); while (id == null) { source = source.getParent(); id = source.getInputId(); } try { String code = compiler.getInput(id).getCode(); for (String line : Splitter.on('\n').split(code)) { Matcher matcher = GOOG_MODULE_EXTRACT.matcher(line); if (matcher.find()) { return Constants.INTERNAL_NAMESPACE + "." + matcher.group(1); } } } catch (IOException e) { throw new RuntimeException("Failed to read input while processing type for " + type.getDisplayName(), e); } throw new RuntimeException("Did not find a matching goog.module while processing type " + type.getDisplayName()); }</code><technical_language>extract a getSourceCode(JSType) method</technical_language>

Target:
private String visitSyntheticModuleTypes(ObjectType type) { String code = getSource(type.getConstructor()); for (String line : Splitter.on('\n').split(code)) { Matcher matcher = GOOG_MODULE_EXTRACT.matcher(line); if (matcher.find()) { return Constants.INTERNAL_NAMESPACE + "." + matcher.group(1); } } throw new RuntimeException("Did not find a matching goog.module while processing type " + type.getDisplayName()); }
Source:
<code>@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RequestCodes.SITE_PICKER && resultCode == Activity.RESULT_OK) { <START> int siteLocalId = data.getIntExtra(SitePickerActivity.KEY_LOCAL_ID, -1); <END> SiteModel site = mSiteStore.getSiteByLocalId(siteLocalId); ActivityLauncher.openEditorForReblog(getActivity(), site, this.mPostToReblog); } }</code><technical_language>a ReaderPostListVIewModel a part reblog onActivityResult hooks, I consider move logic (also multi-site scenario state machine mPostToReblog management) view model (that possibly unit tested). AFAIU work, wdyt</technical_language>

Target:
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RequestCodes.SITE_PICKER && resultCode == Activity.RESULT_OK) { int siteLocalId = data.getIntExtra(SitePickerActivity.KEY_LOCAL_ID, -1); mViewModel.onReblogSiteSelected(siteLocalId); } }
Source:
<code>public Set<EngineError> getExpectedEngineErrors() { <START> return expectedEngineErrors.orElse(Collections.EMPTY_SET); <END> }</code><technical_language>generalized convenience method - Collections.emptySet()</technical_language>

Target:
public Set<EngineError> getExpectedEngineErrors() { return expectedEngineErrors.orElse(Collections.<EngineError>emptySet()); }
Source:
<code>protected MixpanelNotificationData.PushTapAction buildOnTap(String onTapStr) { MixpanelNotificationData.PushTapAction onTap = null; if (null != onTapStr) { try { final JSONObject onTapJSON = new JSONObject(onTapStr); final String typeFromJSON = onTapJSON.getString("type"); if (!typeFromJSON.equals(MixpanelNotificationData.PushTapTarget.HOMESCREEN.getTarget())) { final String uriFromJSON = onTapJSON.getString("uri"); onTap = new MixpanelNotificationData.PushTapAction(MixpanelNotificationData.PushTapTarget.fromString(typeFromJSON), uriFromJSON); } else { onTap = new MixpanelNotificationData.PushTapAction(MixpanelNotificationData.PushTapTarget.fromString(typeFromJSON)); } if (onTap.getActionType().getTarget().equals(MixpanelNotificationData.PushTapTarget.ERROR.getTarget())) { <START> hasOnTapError = true; <END> } } catch (JSONException e){ MPLog.d(LOGTAG, "Exception occurred while parsing ontap"); onTap = null; } } return onTap; }</code><technical_language>If unknown target is passed, I default open HOMESCREEN (ie OS handle tap) display it. log error / warning in console, too. wdyt</technical_language>

Target:
protected MixpanelNotificationData.PushTapAction buildOnTap(String onTapStr) { MixpanelNotificationData.PushTapAction onTap = null; if (null != onTapStr) { try { final JSONObject onTapJSON = new JSONObject(onTapStr); final String typeFromJSON = onTapJSON.getString("type"); if (!typeFromJSON.equals(MixpanelNotificationData.PushTapTarget.HOMESCREEN.getTarget())) { final String uriFromJSON = onTapJSON.getString("uri"); onTap = new MixpanelNotificationData.PushTapAction(MixpanelNotificationData.PushTapTarget.fromString(typeFromJSON), uriFromJSON); } else { onTap = new MixpanelNotificationData.PushTapAction(MixpanelNotificationData.PushTapTarget.fromString(typeFromJSON)); } if (onTap.getActionType().getTarget().equals(MixpanelNotificationData.PushTapTarget.ERROR.getTarget())) { hasOnTapError = true; onTap = new MixpanelNotificationData.PushTapAction(MixpanelNotificationData.PushTapTarget.HOMESCREEN); } } catch (JSONException e){ MPLog.d(LOGTAG, "Exception occurred while parsing ontap"); onTap = null; } } return onTap; }
Source:
<code>public Condition getCondition() throws AppException { <START> Condition preCondition = super.getCondition(); <END> Condition condition = new Condition(); List<Condition.Entry> entries = preCondition.getEntries(); for(int i = 0; i < entries.size(); i++) { Condition.Entry entry =entries.get(i); if(entry.getValue() instanceof Enum) { Enum tmpValue = (Enum)entry.getValue(); condition.addEntry(entry.getFieldName(), entry.getConditionType(), tmpValue.ordinal()); } else { condition.addEntry(entry); } } if (contestId != null) { if (contestId == -1) { condition.addEntry("contestId", Condition.ConditionType.IS_NULL, null); } else { condition.addEntry("contestId", Condition.ConditionType.EQUALS, contestId); } } if (!StringUtil.isNullOrWhiteSpace(userName)) { condition.addEntry("userByUserId.userName", ConditionType.LIKE, userName); } if (!isForAdmin) { condition.addEntry("userByUserId.type", ConditionType.NOT_EQUALS, AuthenticationType.ADMIN.ordinal()); } if (result != null) { results.add(result); } if (!results.contains(OnlineJudgeResultType.OJ_ALL)) { Condition typeCondition = new Condition(JoinedType.OR); Set<Integer> affectedResults = new HashSet<>(); for (OnlineJudgeResultType result : results) { affectedResults.addAll(result.getResults()); } for (Integer result : affectedResults) { typeCondition.addEntry("result", ConditionType.EQUALS, result); } condition.addEntry(typeCondition); } return condition; }</code><technical_language>expose a common util share this part ProblemCondition</technical_language>

Target:
public Condition getCondition() throws AppException { Condition condition = EnumTypeUtil.toOrdinalCondition(super.getCondition()); if (contestId != null) { if (contestId == -1) { condition.addEntry("contestId", Condition.ConditionType.IS_NULL, null); } else { condition.addEntry("contestId", Condition.ConditionType.EQUALS, contestId); } } if (!StringUtil.isNullOrWhiteSpace(userName)) { condition.addEntry("userByUserId.userName", ConditionType.LIKE, userName); } if (!isForAdmin) { condition.addEntry("userByUserId.type", ConditionType.NOT_EQUALS, AuthenticationType.ADMIN.ordinal()); } if (result != null) { results.add(result); } if (!results.contains(OnlineJudgeResultType.OJ_ALL)) { Condition typeCondition = new Condition(JoinedType.OR); Set<Integer> affectedResults = new HashSet<>(); for (OnlineJudgeResultType result : results) { affectedResults.addAll(result.getResults()); } for (Integer result : affectedResults) { typeCondition.addEntry("result", ConditionType.EQUALS, result); } condition.addEntry(typeCondition); } return condition; }
Source:
<code>public void onEventMainThread(UploadService.UploadMediaRetryEvent event) { if (!isAdded()) { return; } if (event.mediaModelList != null && !event.mediaModelList.isEmpty()) { Set<PostModel> postsToRefresh = PostUtils.getPostsThatIncludeThisMedia(mPostStore, event.mediaModelList); for (PostModel post : postsToRefresh) { <START> if (post != null) { <END> getPostListAdapter().notifyItemChanged(getPostListAdapter().getPositionForPost(post)); } } } }</code><technical_language>I post null here, is getPositionForPost() return -1. this rewritten as: for (PostModel post : postsToRefresh) { int position = getPostListAdapter().getPositionForPost(post); if (position > -1) { getPostListAdapter().notifyItemChanged(position); } }</technical_language>

Target:
public void onEventMainThread(UploadService.UploadMediaRetryEvent event) { if (!isAdded()) { return; } if (event.mediaModelList != null && !event.mediaModelList.isEmpty()) { Set<PostModel> postsToRefresh = PostUtils.getPostsThatIncludeThisMedia(mPostStore, event.mediaModelList); for (PostModel post : postsToRefresh) { int position = getPostListAdapter().getPositionForPost(post); if (position > -1) { getPostListAdapter().notifyItemChanged(position); } } } }
Source:
<code>static void casLeaders( HazelcastInstance hazelcastInstance, LeaderInfo leaderInfo, String dbName ) { IAtomicReference<LeaderInfo> leaderRef = hazelcastInstance.getAtomicReference( DB_NAME_LEADER_TERM_PREFIX + dbName ); LeaderInfo expected = leaderRef.get(); boolean noUpdate = Optional.ofNullable( expected ).map( LeaderInfo::memberId ).equals( Optional.ofNullable( leaderInfo.memberId() ) ); boolean greaterOrEqualTermExists = Optional.ofNullable( expected ).map(l -> l.term() >= leaderInfo.term() ).orElse( false ); <START> if ( (greaterOrEqualTermExists || noUpdate) && !leaderInfo.isStepDown() ) <END> { return; } leaderRef.compareAndSet( expected, leaderInfo ); }</code><technical_language>extract (greaterOrEqualTermExists || noUpdate) appropriately named variable</technical_language>

Target:
static void casLeaders( HazelcastInstance hazelcastInstance, LeaderInfo leaderInfo, String dbName ) { IAtomicReference<LeaderInfo> leaderRef = hazelcastInstance.getAtomicReference( DB_NAME_LEADER_TERM_PREFIX + dbName ); LeaderInfo current = leaderRef.get(); Optional<LeaderInfo> currentOpt = Optional.ofNullable( current ); boolean noUpdate = currentOpt.map( LeaderInfo::memberId ).equals( Optional.ofNullable( leaderInfo.memberId() ) ); int termComparison = currentOpt.map( l -> Long.compare( l.term(), leaderInfo.term() ) ).orElse( -1 ); boolean greaterTermExists = termComparison > 0; boolean invalidTerm = greaterTermExists || ( termComparison == 0 && !leaderInfo.isSteppingDown() ); boolean success = !( invalidTerm || noUpdate); if ( !success ) { return; } leaderRef.compareAndSet( current, leaderInfo ); }
Source:
<code>public static <R> Single<R> zip(Iterable<? extends Single<?>> singles, FuncN<? extends R> zipFunction) { <START> List<Observable<?>> listOfSingles = new ArrayList<Observable<?>>(); <END> for (Single<?> single : singles) { listOfSingles.add(asObservable(single)); } return just(listOfSingles.toArray(new Observable<?>[listOfSingles.size()])).lift(new OperatorZip<R>(zipFunction)); }</code><technical_language>required, I prefer iterating sources child subscribes sequence is assembled</technical_language>

Target:
public static <R> Single<R> zip(Iterable<? extends Single<?>> singles, FuncN<? extends R> zipFunction) { return SingleOperatorZip.zip(iterableToArray(singles), zipFunction); }