auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testConnectUnknownMode() throws Exception { PowerMockito.doReturn(XBeeMode.UNKNOWN).when(xbeeDevice, "determineConnectionMode"); <START> <END> try { xbeeDevice.connect(); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } catch (InvalidOperatingModeException e) { } assertEquals(xbeeDevice.getOperatingMode(), XBeeMode.UNKNOWN); }</code><technical_language>check dataReader is running in XBee Device</technical_language>

Target:
public void testConnectUnknownMode() throws Exception { PowerMockito.doReturn(OperatingMode.UNKNOWN).when(xbeeDevice, "determineConnectionMode"); try { xbeeDevice.open(); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } catch (InvalidOperatingModeException e) { } assertFalse(xbeeDevice.isOpen()); assertFalse(dataReader.isRunning()); assertEquals(xbeeDevice.getOperatingMode(), OperatingMode.UNKNOWN); }
Source:
<code>private void updateTrigger(Trigger t, EncodingType encType) throws TriggerLoaderException { String json = JSONUtils.toJSON(t.toJson()); byte[] data = null; try { byte[] stringData = json.getBytes("UTF-8"); data = stringData; if (encType == EncodingType.GZIP) { data = GZIPUtils.gzipBytes(stringData); } logger.debug("NumChars: " + json.length() + " UTF-8:" + stringData.length + " Gzip:" + data.length); } catch (IOException e) { logger.error("Trigger encoding fails", e); throw new TriggerLoaderException("Error encoding the trigger " + t.toString()); } try { int updates = dbOperator.update(UPDATE_TRIGGER, t.getSource(), t.getLastModifyTime(), encType.getNumVal(), data, t.getTriggerId()); if (updates == 0) { throw new TriggerLoaderException("No trigger has been updated."); } } catch (SQLException ex) { <START> throw new TriggerLoaderException("DB Trigger update failed. "); <END> } }</code><technical_language>consider including ex well? in previous methods</technical_language>

Target:
private void updateTrigger(Trigger t, EncodingType encType) throws TriggerLoaderException { String json = JSONUtils.toJSON(t.toJson()); byte[] data = null; try { byte[] stringData = json.getBytes("UTF-8"); data = stringData; if (encType == EncodingType.GZIP) { data = GZIPUtils.gzipBytes(stringData); } logger.debug("NumChars: " + json.length() + " UTF-8:" + stringData.length + " Gzip:" + data.length); } catch (IOException e) { logger.error("Trigger encoding fails", e); throw new TriggerLoaderException("Error encoding the trigger " + t.toString(), e); } try { int updates = dbOperator.update(UPDATE_TRIGGER, t.getSource(), t.getLastModifyTime(), encType.getNumVal(), data, t.getTriggerId()); if (updates == 0) { throw new TriggerLoaderException("No trigger has been updated."); } } catch (SQLException ex) { logger.error("Updating Trigger " + t.getTriggerId() + " failed." ); throw new TriggerLoaderException("DB Trigger update failed. ", ex); } }
Source:
<code>private static ImmutableSet<String> readFile(String sourceFileName) throws <START> UnsupportedEncodingException, FileNotFoundException, IOException <END> { Builder<String> builder = ImmutableSet.builder(); BufferedReader input = new BufferedReader(new InputStreamReader( new FileInputStream(sourceFileName), "utf-8")); String line = input.readLine(); while (line != null) { if (!line.startsWith("#")) { String title = line.trim(); title = title.replace("_", " "); if (title.startsWith(":")) title = line.substring(1); if (title.length() > 0) builder.add(title); } line = input.readLine(); } input.close(); return builder.build(); }</code><technical_language>IOException covers</technical_language>

Target:
private static ImmutableSet<String> readFile(String sourceFileName) throws IOException { Builder<String> builder = ImmutableSet.builder(); BufferedReader input = new BufferedReader(new InputStreamReader( new FileInputStream(sourceFileName), "utf-8")); String line = input.readLine(); while (line != null) { if (!line.startsWith("#")) { String title = line.trim(); title = title.replace("_", " "); if (title.startsWith(":")) title = line.substring(1); if (title.length() > 0) builder.add(title); } line = input.readLine(); } input.close(); return builder.build(); }
Source:
<code>protected ImmutableValue<Set<String>> constructImmutableValue(Set<String> value) { <START> return ImmutableSpongeSetValue.cachedOf(Keys.TAGS, Collections.<String>emptySet(), value); <END> }</code><technical_language>Collections.emptySet() is required here, generic</technical_language>

Target:
protected ImmutableValue<Set<String>> constructImmutableValue(Set<String> value) { return ImmutableSpongeSetValue.cachedOf(Keys.TAGS, Collections.emptySet(), value); }
Source:
<code>public void onCreate(final MediaSessionService2 service) { MediaSession2 session; synchronized (mLock) { session = mSession; } if (session == null) { session = service.onCreateSession(); if (session == null) { throw new <START> RuntimeException("Session is null"); <END> } synchronized (mLock) { mSession = session; } } mNotificationHandler = new MediaNotificationHandler(service); }</code><technical_language>Session null</technical_language>

Target:
public void onCreate(final MediaSessionService2 service) { MediaSession2 session; synchronized (mLock) { session = mSession; } if (session == null) { session = service.onCreateSession(); if (session == null) { throw new RuntimeException("Session shouldn't be null"); } synchronized (mLock) { mSession = session; } } mNotificationHandler = new MediaNotificationHandler(service); }
Source:
<code>public DrawableLocatorMutation(final DefaultNode node, final double width, final double maxRefPosition) { this.maxRefPosition = maxRefPosition; this.width = width; setStroke(Paint.valueOf("blue")); setStartX(getXPosition(node.getRefStartPosition())); setEndX(node.getRefStartPosition() / maxRefPosition * width); <START> setStartY(0); <END> setEndY(LOCATOR_HEIGHT); }</code><technical_language>locator starts 2 (if set this 2, align): locatorIndicator.setTranslateY(2);</technical_language>

Target:
public DrawableLocatorMutation(final DefaultNode node, final double width, final double maxRefPosition) { this.maxRefPosition = maxRefPosition; this.width = width; setStroke(Paint.valueOf("blue")); setStartX(getXPosition(node.getRefStartPosition())); setEndX(getXPosition(node.getRefStartPosition())); setStartY(2); setEndY(LOCATOR_HEIGHT); }
Source:
<code>public String getNewQuestionSpecificEditFormHtml() { this.numOfRubricChoices = 4; this.rubricChoices.add("Strongly Disagree"); this.rubricChoices.add("Disagree"); this.rubricChoices.add("Agree"); this.rubricChoices.add("Strongly Agree"); this.rubricWeights.add(0); this.rubricWeights.add(0); this.rubricWeights.add(0); <START> this.rubricWeights.add(0); <END> this.numOfRubricSubQuestions = 2; this.rubricSubQuestions.add("This student participates well in online discussions."); this.rubricSubQuestions.add("This student completes assigned tasks on time."); this.initializeRubricDescriptions(); setDescription(0, 0, "Rarely or never responds."); setDescription(0, 1, "Occasionally responds, but never initiates discussions."); setDescription(0, 2, "Takes part in discussions and sometimes initiates discussions."); setDescription(0, 3, "Initiates discussions frequently, and engages the team."); setDescription(1, 0, "Rarely or never completes tasks."); setDescription(1, 1, "Often misses deadlines."); setDescription(1, 2, "Occasionally misses deadlines."); setDescription(1, 3, "Tasks are always completed before the deadline."); return "<div id=\"rubricForm\">" + this.getQuestionSpecificEditFormHtml(-1) + "</div>"; }</code><technical_language>@damithc, check, if instructor assign weights, do want give rubrics choices default weights, display weights (done in this pr)</technical_language>

Target:
public String getNewQuestionSpecificEditFormHtml() { this.numOfRubricChoices = 4; this.rubricChoices.add("Strongly Disagree"); this.rubricChoices.add("Disagree"); this.rubricChoices.add("Agree"); this.rubricChoices.add("Strongly Agree"); this.hasAssignedWeights = false; this.numOfRubricSubQuestions = 2; this.rubricSubQuestions.add("This student participates well in online discussions."); this.rubricSubQuestions.add("This student completes assigned tasks on time."); this.initializeRubricDescriptions(); setDescription(0, 0, "Rarely or never responds."); setDescription(0, 1, "Occasionally responds, but never initiates discussions."); setDescription(0, 2, "Takes part in discussions and sometimes initiates discussions."); setDescription(0, 3, "Initiates discussions frequently, and engages the team."); setDescription(1, 0, "Rarely or never completes tasks."); setDescription(1, 1, "Often misses deadlines."); setDescription(1, 2, "Occasionally misses deadlines."); setDescription(1, 3, "Tasks are always completed before the deadline."); return "<div id=\"rubricForm\">" + this.getQuestionSpecificEditFormHtml(-1) + "</div>"; }
Source:
<code>public void setup() { setupHelper.start( BACKEND_1_NAME ) <START> .withBackendProperty( BACKEND_1_NAME, "directory.type", directoryType ) <END> .withIndex( INDEX_NAME_1_1, ctx -> this.indexMapping_1_1 = new IndexMapping_1_1( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_1 = indexMapping ) .withIndex( INDEX_NAME_1_2, ctx -> this.indexMapping_1_2 = new IndexMapping_1_2( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_2 = indexMapping ) .setup(); initData(); }</code><technical_language>longer need define pass a backend name. call start() withBackendProperty( "directory.type", directoryType )</technical_language>

Target:
public void setup() { setupHelper.start() .withBackendProperty( "directory.type", directoryType ) .withIndex( INDEX_NAME_1_1, ctx -> this.indexMapping_1_1 = new IndexMapping_1_1( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_1 = indexMapping ) .withIndex( INDEX_NAME_1_2, ctx -> this.indexMapping_1_2 = new IndexMapping_1_2( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_2 = indexMapping ) .setup(); initData(); }
Source:
<code>public void test(TestHarness th) { this.th = th; InputStream is = getClass().getResourceAsStream("/midlets/MediaSampler/res/laser.wav"); try { Player player = Manager.createPlayer(is, "audio/x-wav"); testPlay(player); } catch (Exception e) { e.printStackTrace(); th.fail("Unexpected exception: " + e); } try { String url = "file:/ <START> FileConnection file = (FileConnection)Connector.open(url, Connector.READ_WRITE); <END> if (!file.exists()) { file.create(); } OutputStream os = file.openDataOutputStream(); os.write(read(is)); os.close(); Player player = Manager.createPlayer(url); testPlay(player); } catch (Exception e) { e.printStackTrace(); th.todo(false, "Unexpected exception: " + e); } }</code><technical_language>delete file end of test, strictly needed check for existence, deleting end is more robust</technical_language>

Target:
public void test(TestHarness th) { this.th = th; InputStream is = getClass().getResourceAsStream("/midlets/MediaSampler/res/laser.wav"); try { Player player = Manager.createPlayer(is, "audio/x-wav"); testPlay(player); } catch (Exception e) { e.printStackTrace(); th.fail("Unexpected exception: " + e); } try { String url = "file:/ FileConnection file = (FileConnection)Connector.open(url, Connector.READ_WRITE); if (!file.exists()) { file.create(); } OutputStream os = file.openDataOutputStream(); os.write(read(is)); os.close(); Player player = Manager.createPlayer(url); testPlay(player); file.delete(); file.close(); } catch (Exception e) { e.printStackTrace(); th.todo(false, "Unexpected exception: " + e); } }
Source:
<code>public Object[] transform(InputRow inputRow) { final String originalValue = inputRow.getValue(column); if (originalValue == null) { if (lookUpEveryToken) { <START> return new String[3]; <END> } else { return new String[1]; } } if (lookUpEveryToken) { final SynonymCatalogConnection.Replacement replacement = synonymCatalogConnection.replaceInline(originalValue); if (replacedSynonymsType == ReplacedSynonymsType.STRING) { return new Object[] { replacement.getReplacedString(), Joiner.on(' ').join(replacement.getSynonyms()), Joiner.on(' ').join(replacement.getMasterTerms()) }; } else { return new Object[] { replacement.getReplacedString(), replacement.getSynonyms(), replacement.getMasterTerms() }; } } else { final String replacedValue = lookup(originalValue); return new String[] { replacedValue }; } }</code><technical_language>related, this reminds a demo, a bit of a pain synonyms masterterm column "token" (I guess word is wrong in some cases now). drawbacks returning them</technical_language>

Target:
public Object[] transform(InputRow inputRow) { final String originalValue = inputRow.getValue(column); if (originalValue == null) { return new String[3]; } if (lookUpEveryToken) { final SynonymCatalogConnection.Replacement replacement = synonymCatalogConnection.replaceInline( originalValue); if (replacedSynonymsType == ReplacedSynonymsType.STRING) { return new Object[] { replacement.getReplacedString(), Joiner.on(' ').join(replacement.getSynonyms()), Joiner.on(' ').join(replacement.getMasterTerms()) }; } else { return new Object[] { replacement.getReplacedString(), replacement.getSynonyms(), replacement .getMasterTerms() }; } } else { final String masterTerm = synonymCatalogConnection.getMasterTerm(originalValue); final Object lookupResult = masterTerm != null ? masterTerm : (retainOriginalValue ? originalValue : null); final Object synonym = masterTerm != null ? originalValue : null; return new Object[] { lookupResult, synonym, masterTerm }; } }
Source:
<code>public TFM_Admin(UUID uuid, ConfigurationSection section) { this.uuid = uuid; this.lastLoginName = section.getString("last_login_name"); this.ips = section.getStringList("ips"); this.lastLogin = TFM_Util.stringToDate(section.getString("last_login", TFM_Util.dateToString(new Date(0L)))); this.loginMessage = section.getString("custom_login_message", ""); this.isSeniorAdmin = section.getBoolean("is_senior_admin", false); this.isTelnetAdmin = section.getBoolean("is_telnet_admin", false); this.consoleAliases = section.getStringList("console_aliases"); <START> this.cmdSpyEnabled = section.getBoolean("cmdspy_is_on", false); <END> this.isActivated = section.getBoolean("is_activated", true); for (Iterator<?> it = TFM_MainConfig.getList(TFM_ConfigEntry.NOADMIN_IPS).iterator(); it.hasNext();) { ips.remove((String) it.next()); } }</code><technical_language>cmdspy? Additionally, I this true default</technical_language>

Target:
public TFM_Admin(UUID uuid, ConfigurationSection section) { this.uuid = uuid; this.lastLoginName = section.getString("last_login_name"); this.ips = section.getStringList("ips"); this.lastLogin = TFM_Util.stringToDate(section.getString("last_login", TFM_Util.dateToString(new Date(0L)))); this.loginMessage = section.getString("custom_login_message", ""); this.isSeniorAdmin = section.getBoolean("is_senior_admin", false); this.isTelnetAdmin = section.getBoolean("is_telnet_admin", false); this.consoleAliases = section.getStringList("console_aliases"); this.cmdSpyEnabled = section.getBoolean("cmdspy", true); this.isActivated = section.getBoolean("is_activated", true); for (Iterator<?> it = TFM_MainConfig.getList(TFM_ConfigEntry.NOADMIN_IPS).iterator(); it.hasNext();) { ips.remove((String) it.next()); } }
Source:
<code>private static File verifyFileExistsAndCanRead(File file) { <START> if (!file.exists() || !file.canRead() || !file.isFile()) { <END> throw new IllegalArgumentException("Unable to read specified resource: " + file); } return file; }</code><technical_language>safely remove file.exists()(implicitly done isFile</technical_language>

Target:
private static File verifyFileExistsAndCanRead(File file) { if (!file.isFile() || !file.canRead()) { throw new IllegalArgumentException("Unable to read specified resource: " + file); } return file; }
Source:
<code>public ToggleDebuggingCommand(IServerWorkingCopy server, Button useImageDevmodeKeyButton, Text devmodeKeyText, SelectionListener toggleListener, ModifyListener textListener) { super(server, "Enable Debugging"); this.wc = server; this.useImageDevmodeKeyButton = useImageDevmodeKeyButton; this.devmodeKeyText = devmodeKeyText; preSelected = !useImageDevmodeKeyButton.getSelection(); <START> preText = devmodeKeyText.getText(); <END> this.toggleListener = toggleListener; this.textListener = textListener; }</code><technical_language>preText? speaking variable name imho</technical_language>

Target:
public ToggleDebuggingCommand(IServerWorkingCopy server, Button useImageDevmodeKeyButton, Text devmodeKeyText, SelectionListener toggleListener, ModifyListener textListener) { super(server, "Enable Debugging"); this.wc = server; this.useImageDevmodeKeyButton = useImageDevmodeKeyButton; this.devmodeKeyText = devmodeKeyText; this.preSelected = !useImageDevmodeKeyButton.getSelection(); this.preText = devmodeKeyText.getText(); this.toggleListener = toggleListener; this.textListener = textListener; }
Source:
<code>public Value getDateTimeValues( Value request ) throws FaultException { SimpleDateFormat sdf; Value v = Value.create(); try { String format; if ( request.getFirstChild( "format" ).strValue().isEmpty() ) { format = "dd/MM/yyyy hh:ss:mm"; } else { format = request.getFirstChild( "format" ).strValue(); } if ( request.hasChildren( "language" ) ) { String language = request.getFirstChild( "language" ).strValue(); <START> if ( language.equals( "uk" ) ) { <END> sdf = new SimpleDateFormat( format, Locale.ENGLISH ); } else if ( language.equals( "it" ) ) { sdf = new SimpleDateFormat( format, Locale.ITALIAN ); } else { sdf = new SimpleDateFormat( format, Locale.US ); } } else { sdf = new SimpleDateFormat( format, Locale.US ); } GregorianCalendar cal = new GregorianCalendar(); final Date dt = sdf.parse( request.strValue() ); cal.setTimeInMillis( dt.getTime() ); v.getFirstChild( "day" ).setValue( cal.get( Calendar.DAY_OF_MONTH ) ); v.getFirstChild( "month" ).setValue( cal.get( Calendar.MONTH ) + 1 ); v.getFirstChild( "year" ).setValue( cal.get( Calendar.YEAR ) ); v.getFirstChild( "hour" ).setValue( cal.get( Calendar.HOUR ) ); v.getFirstChild( "minute" ).setValue( cal.get( Calendar.MINUTE ) ); v.getFirstChild( "second" ).setValue( cal.get( Calendar.SECOND ) ); } catch( ParseException pe ) { throw new FaultException( "InvalidDate", pe ); } return v; }</code><technical_language>Huh? is this in commit</technical_language>

Target:
public Value getDateTimeValues( Value request ) throws FaultException { SimpleDateFormat sdf; Value v = Value.create(); try { String format; if ( request.getFirstChild( "format" ).strValue().isEmpty() ) { format = "dd/MM/yyyy hh:ss:mm"; } else { format = request.getFirstChild( "format" ).strValue(); } if ( request.hasChildren( "language" ) ) { String language = request.getFirstChild( "language" ).strValue(); if ( language.equals( "us" ) ) { sdf = new SimpleDateFormat( format, Locale.ENGLISH ); } else if ( language.equals( "it" ) ) { sdf = new SimpleDateFormat( format, Locale.ITALIAN ); } else { sdf = new SimpleDateFormat( format, Locale.US ); } } else { sdf = new SimpleDateFormat( format, Locale.US ); } GregorianCalendar cal = new GregorianCalendar(); final Date dt = sdf.parse( request.strValue() ); cal.setTimeInMillis( dt.getTime() ); v.getFirstChild( "day" ).setValue( cal.get( Calendar.DAY_OF_MONTH ) ); v.getFirstChild( "month" ).setValue( cal.get( Calendar.MONTH ) + 1 ); v.getFirstChild( "year" ).setValue( cal.get( Calendar.YEAR ) ); v.getFirstChild( "hour" ).setValue( cal.get( Calendar.HOUR ) ); v.getFirstChild( "minute" ).setValue( cal.get( Calendar.MINUTE ) ); v.getFirstChild( "second" ).setValue( cal.get( Calendar.SECOND ) ); } catch( ParseException pe ) { throw new FaultException( "InvalidDate", pe ); } return v; }
Source:
<code>public static int getSignalFromUrl(String url) { if ("signal:typefocus".equals(url)) { return TYPE_FOCUS; <START> } else if ("signal:relinquishFocus".equals(url)) { <END> return RELINQUISH_FOCUS; } return SIGNAL_NONE; }</code><technical_language>suggestion for defensive programming logging alternatively here, some notice nice In addition, if short-circuit returns, else if statements if statements I require a tiny bit cognitive work reason about. a thought</technical_language>

Target:
public static int getSignalFromUrl(String url) { switch (url) { case "signal:typefocus": return TYPE_FOCUS; case "signal:relinquishFocus": return RELINQUISH_FOCUS; case "signal:show_answer": return SHOW_ANSWER; case "signal:answer_ease1": return ANSWER_ORDINAL_1; case "signal:answer_ease2": return ANSWER_ORDINAL_2; case "signal:answer_ease3": return ANSWER_ORDINAL_3; case "signal:answer_ease4": return ANSWER_ORDINAL_4; default: break; } if (url.startsWith("signal:answer_ease")) { Timber.w("Unhandled signal: ease value: %s", url); return SIGNAL_NOOP; } return SIGNAL_UNHANDLED; }
Source:
<code>private ListenableFuture<VersionMessage> getVersionMessage(Peer peer) { SettableFuture<VersionMessage> peerVersionMessageFuture = SettableFuture.create(); var versionHandshakeDone = peer.getVersionHandshakeFuture(); FutureCallback<Peer> fetchPeerVersionMessage = new FutureCallback<Peer>() { public void onSuccess(Peer peer) { peerVersionMessageFuture.set(peer.getPeerVersionMessage()); } public void onFailure(Throwable thr) { <START> ; <END> } }; Futures.addCallback( versionHandshakeDone, fetchPeerVersionMessage ); PeerDisconnectedEventListener cancelIfConnectionFails = new PeerDisconnectedEventListener() { public void onPeerDisconnected(Peer peer, int peerCount) { var peerVersionMessageAlreadyReceived = peerVersionMessageFuture.isDone(); if (peerVersionMessageAlreadyReceived) { return; } var peerVersionMessage = peer.getPeerVersionMessage(); if (peerVersionMessage != null) { log.info("Handshake attempt was interrupted;" + " however, the local node's version message was coerced."); peerVersionMessageFuture.set(peerVersionMessage); } else { log.info("Handshake attempt did not result in a version message exchange."); var mayInterruptWhileRunning = true; peerVersionMessageFuture.cancel(mayInterruptWhileRunning); } } }; peer.addDisconnectedEventListener(cancelIfConnectionFails); return peerVersionMessageFuture; }</code><technical_language>suggestion // action</technical_language>

Target:
private ListenableFuture<VersionMessage> getVersionMessage(Peer peer) { SettableFuture<VersionMessage> peerVersionMessageFuture = SettableFuture.create(); var versionHandshakeDone = peer.getVersionHandshakeFuture(); FutureCallback<Peer> fetchPeerVersionMessage = new FutureCallback<>() { public void onSuccess(Peer peer) { peerVersionMessageFuture.set(peer.getPeerVersionMessage()); } public void onFailure(@NotNull Throwable thr) { } }; Futures.addCallback(versionHandshakeDone, fetchPeerVersionMessage); PeerDisconnectedEventListener cancelIfConnectionFails = (Peer disconnectedPeer, int peerCount) -> { var peerVersionMessageAlreadyReceived = peerVersionMessageFuture.isDone(); if (peerVersionMessageAlreadyReceived) { return; } var peerVersionMessage = disconnectedPeer.getPeerVersionMessage(); if (peerVersionMessage != null) { log.info("Handshake attempt was interrupted; " + "however, the local node's version message was coerced."); peerVersionMessageFuture.set(peerVersionMessage); } else { log.info("Handshake attempt did not result in a version message exchange."); peerVersionMessageFuture.cancel(true); } }; peer.addDisconnectedEventListener(cancelIfConnectionFails); return peerVersionMessageFuture; }
Source:
<code>public synchronized int registerEvaluator(final String contextId, final int numInitialEvals) { if (evalIdToPartitionIds.containsKey(contextId)) { throw new RuntimeException("This evaluator is already registered. Its context Id is " + contextId); } final int memoryStoreId = numEvalCounter.getAndIncrement(); LOG.log(Level.FINE, "MemoryStore({0}) is registered to {1}", new Object[]{memoryStoreId, contextId}); <START> if (memoryStoreId < numPartitions) { <END> evalIdToPartitionIds.put(contextId, new HashSet<Integer>()); for (int partitionId = memoryStoreId; partitionId < numPartitions; partitionId += numInitialEvals) { evalIdToPartitionIds.get(contextId).add(partitionId); } } return memoryStoreId; }</code><technical_language>if (memoryStore < numInitialEvals)</technical_language>

Target:
public synchronized int registerEvaluator(final String contextId, final int numInitialEvals) { if (evalIdToPartitionIds.containsKey(contextId)) { throw new RuntimeException("This evaluator is already registered. Its context Id is " + contextId); } final int memoryStoreId = numEvalCounter.getAndIncrement(); LOG.log(Level.FINE, "MemoryStore({0}) is registered to {1}", new Object[]{memoryStoreId, contextId}); if (memoryStoreId < numInitialEvals) { evalIdToPartitionIds.put(contextId, new HashSet<Integer>()); for (int partitionId = memoryStoreId; partitionId < numPartitions; partitionId += numInitialEvals) { evalIdToPartitionIds.get(contextId).add(partitionId); } } return memoryStoreId; }
Source:
<code>public void shouldLoadPredictableRecipesFromValidJson() throws Exception { recipeLoader = new PredefinedRecipeLoader("recipes.json", recipeDao); List<RecipeImpl> result = new ArrayList<>(); Mockito.doAnswer(r -> result.add((RecipeImpl)r.getArguments()[0])).when(recipeDao).create(any()); recipeLoader.start(); <START> Assert.assertEquals(result.size(), 2); <END> }</code><technical_language>I in this case is <code>verify</code> + <code>times()</code></technical_language>

Target:
public void shouldLoadPredictableRecipesFromValidJson() throws Exception { recipeLoader = new PredefinedRecipeLoader("recipes.json", recipeDao); recipeLoader.start(); verify(recipeDao, times(2)).create(any()); }
Source:
<code>public final Single<T> doOnEach(final Action1<Notification<? extends T>> onNotification) { if (onNotification == null) { throw new IllegalArgumentException("onNotification is null"); } <START> Observer<T> observer = new Observer<T>() { <END> @Override public void onCompleted() { } @Override public void onError(Throwable e) { onNotification.call(Notification.<T>createOnError(e)); } @Override public void onNext(T t) { onNotification.call(Notification.<T>createOnNext(t)); } }; return Observable.create(new OnSubscribeDoOnEach<T>(this.toObservable(), observer)).toSingle(); }</code><technical_language>natively subscribe a subscriber forwards action</technical_language>

Target:
public final Single<T> doOnEach(final Action1<Notification<? extends T>> onNotification) { if (onNotification == null) { throw new IllegalArgumentException("onNotification is null"); } return Single.create(new SingleDoOnEvent<T>(this, new Action1<T>() { @Override public void call(final T t) { onNotification.call(Notification.<T>createOnNext(t)); } }, new Action1<Throwable>() { @Override public void call(final Throwable throwable) { onNotification.call(Notification.<T>createOnError(throwable)); } })); }
Source:
<code>public static boolean isSamtoolsAvailable() { final String binPath = getSamtoolsBin(); if (binPath == null) { LOG.warn(String.format( "No samtools binary found. Set property %s to enable testing with samtools.", SAMTOOLS_BIN_PROPERTY)); return false; } final Path binFile = Paths.get(binPath); if (!Files.exists(binFile)) { throw new IllegalArgumentException( String.format( <START> "%s property is set to non-existent file: %s", SAMTOOLS_BIN_PROPERTY, binFile)); <END> } return true; }</code><technical_language>this error is confusing if set property maybe</technical_language>

Target:
public static boolean isSamtoolsAvailable() { final String binPath = getSamtoolsBin(); final Path binFile = Paths.get(binPath); return Files.exists(binFile); }
Source:
<code>private static <T extends ExecutorService> T notShutdown(final T executorService) { if (executorService.isShutdown()) { <START> throw new IllegalArgumentException("executorService may not be shutdown"); <END> } return executorService; }</code><technical_language>("executorService shutdown");</technical_language>

Target:
private static <T extends ExecutorService> T notShutdown(final T executorService) { if (executorService.isShutdown()) { final String message = "executorService may not be shutdown"; LOGGER.debug(message); throw new IllegalArgumentException(message); } return executorService; }
Source:
<code>public void showDeleteAlertDialog(final int index) { AlertDialog.Builder openDialog = new AlertDialog.Builder(this); openDialog.setTitle(R.string.action_delete_claim_confirm); openDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { <START> if(checkFilteredTags()) { END> ExpenseClaim removedClaim = filteredListModel.getItems().get(index); filteredListModel.remove(index); listModel.remove(removedClaim); } else { listModel.remove(index); } } }); openDialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); openDialog.show(); }</code><technical_language>Style inconsistency: space if</technical_language>

Target:
public void showDeleteAlertDialog(final int index) { AlertDialog.Builder openDialog = new AlertDialog.Builder(this); openDialog.setTitle(R.string.action_delete_claim_confirm); openDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!filteredTagsList.isEmpty()) { ExpenseClaim removedClaim = filteredListModel.getItems().get(index); filteredListModel.remove(index); listModel.remove(removedClaim); } else { listModel.remove(index); } } }); openDialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); openDialog.show(); }
Source:
<code>public String getHttp(String urlToRead, String username, String password) throws Exception { URL url = new URL(urlToRead); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if(username != null) { String userpass = username + ":" + password; <START> String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()); <END> conn.setRequestProperty ("Authorization", basicAuth); } conn.setRequestMethod("GET"); return IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8.name()); }</code><technical_language>![MAJOR](<LINK_1> Remove this of "getBytes" [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public String getHttp(String urlToRead, String username, String password) throws Exception { URL url = new URL(urlToRead); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (username != null) { String userpass; if (StringUtils.isEmpty(password)) { userpass = username; } else { userpass = username + ":" + password; } String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes()); conn.setRequestProperty("Authorization", basicAuth); } conn.setRequestMethod("GET"); return IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8.name()); }
Source:
<code>private boolean isInSubnet(RedisURI redisURI) { if (LettuceStrings.isEmpty(redisURI.getHost())) { return false; } <START> InetSocketAddress address = SocketUtils.socketAddress(redisURI.getHost(), redisURI.getPort()); <END> for (IpSubnetFilterRule rule : rules) { if (rule.matches(address)) { return true; } } return false; }</code><technical_language>This line lead a DNS lookup (blocking call). createUnresolved work well</technical_language>

Target:
private boolean isInSubnet(RedisURI redisURI) { String host = redisURI.getHost(); if (LettuceStrings.isEmpty(host)) { return false; } LettuceAssert.isTrue(NetUtil.isValidIpV4Address(host) || NetUtil.isValidIpV6Address(host), "ReadFromSubnet supports only IP address-style redisURI. host=" + host); InetSocketAddress address; try { address = new InetSocketAddress(InetAddress.getByName(host), redisURI.getPort()); } catch (UnknownHostException e) { throw new IllegalStateException("Should not reach here. host=" + host, e); } for (IpSubnetFilterRule rule : rules) { if (rule.matches(address)) { return true; } } return false; }
Source:
<code>public PartitionStatistics getTableStatistics(String databaseName, String tableName) { try { Table table = getTable(databaseName, tableName) .orElseThrow(() -> new PrestoException(HIVE_METASTORE_ERROR, String.format("Could not retrieve table %s.%s", databaseName, tableName))); HiveBasicStatistics basicStats = <START> ThriftMetastoreUtil.getHiveBasicStatistics(table.getParameters()); <END> return new PartitionStatistics(basicStats, Collections.emptyMap()); } catch (Exception e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }</code><technical_language>nit: put previous line</technical_language>

Target:
public PartitionStatistics getTableStatistics(String databaseName, String tableName) { try { Table table = getTable(databaseName, tableName).orElseThrow(() -> new PrestoException( HIVE_METASTORE_ERROR, String.format("Could not retrieve table %s.%s", databaseName, tableName))); HiveBasicStatistics basicStats = ThriftMetastoreUtil.getHiveBasicStatistics(table.getParameters()); return new PartitionStatistics(basicStats, ImmutableMap.of()); } catch (Exception e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }
Source:
<code>private boolean isInsideSelection(ICPPASTCompositeTypeSpecifier node) { IASTFileLocation location = node.getFileLocation(); if (location == null) { return false; } if (fSelection == null) { String elName = new String(node.getName().getSimpleID()); <START> if (elName.equals(fElementName)) <END> return true; return false; } if (location.getNodeOffset() <= fSelection.getOffset() && fSelection.getOffset() <= location.getNodeOffset() + location.getNodeLength() && location.getFileName().contains(fFileName)) { return true; } else { return false; } }</code><technical_language>I need qualified name here, otherwise, a class/struct name in another namespace match. is example this is problematic: namespace { class Base { public: virtual ~Base() virtual void baseFunc(Base* ptr) const = 0; virtual void baseFunc2(Base* ptr) const = 0; }; } namespace { class X: public FIRST::Base { public: X(); virtual void baseFunc(Base* ptr) const }; } namespace { class X: public FIRST::Base { public: X(); virtual void baseFunc2(Base* ptr) const }; } In outline view, if I select class SECOND::X do Override Methods, suggests override baseFunc thought is implemented. This is this logic picked THIRD::X selected class (fClassNode, etc)</technical_language>

Target:
private boolean isInsideSelection(ICPPASTCompositeTypeSpecifier node) { IASTFileLocation location = node.getFileLocation(); if (location == null) { return false; } if (fSelection == null) { IBinding binding = node.getName().resolveBinding(); if (!(binding instanceof ICPPBinding)) return false; try { String elName = String.join(IQualifiedTypeName.QUALIFIER, ((ICPPBinding) binding).getQualifiedName()); if (elName.equals(fElementName)) return true; } catch (DOMException e) { CUIPlugin.log(e); } return false; } if (location.getNodeOffset() <= fSelection.getOffset() && fSelection.getOffset() <= location.getNodeOffset() + location.getNodeLength() && location.getFileName().contains(fFileName)) { return true; } else { return false; } }
Source:
<code>private List<Circuit> getCircuits(long timeoutValue, TimeUnit timeoutUnit, Set<Router> routers) throws InterruptedException { createThreadPool(routers.size()); try { List<ListenableFuture<Circuit>> circuitFutures = Lists.newArrayList(); final CountDownLatch doneSignal = new CountDownLatch(routers.size()); for (final Router router : routers) { ListenableFuture<Circuit> openCircuit = threadPool.submit(new Callable<Circuit>() { @Override public Circuit call() throws Exception { return torClient.getCircuitManager().openInternalCircuitTo(Lists.newArrayList(router)); } }); Futures.addCallback(openCircuit, new FutureCallback<Circuit>() { public void onSuccess(Circuit circuit) { doneSignal.countDown(); } public void onFailure(Throwable thrown) { doneSignal.countDown(); } }); circuitFutures.add(openCircuit); } boolean countedDown = <START> doneSignal.await(torClient.getConfig().getCircuitBuildTimeout(), TimeUnit.MILLISECONDS); <END> try { List<Circuit> circuits = new ArrayList<Circuit>(Futures.successfulAsList(circuitFutures).get()); circuits.removeAll(singleton(null)); int failures = routers.size() - circuits.size(); if (failures > 0) log.warn("{} failures " + (countedDown ? "" : "(including timeout) ") + "opening DNS lookup circuits", failures); return circuits; } catch (ExecutionException e) { throw new RuntimeException(e); } } finally { shutdownThreadPool(); } }</code><technical_language>timeoutValue, timeoutUnit longer referenced. pass in values removed</technical_language>

Target:
private List<Circuit> getCircuits(long timeoutValue, TimeUnit timeoutUnit, Set<Router> routers) throws InterruptedException { checkArgument(routers.size() >= MINIMUM_ROUTER_LOOKUP_COUNT, "Set of routers is smaller than required minimum {}", routers.size(), MINIMUM_ROUTER_LOOKUP_COUNT); createThreadPool(routers.size()); try { List<ListenableFuture<Circuit>> circuitFutures = Lists.newArrayList(); final CountDownLatch doneSignal = new CountDownLatch(MINIMUM_ROUTER_LOOKUP_COUNT); for (final Router router : routers) { ListenableFuture<Circuit> openCircuit = threadPool.submit(new Callable<Circuit>() { @Override public Circuit call() throws Exception { return torClient.getCircuitManager().openInternalCircuitTo(Lists.newArrayList(router)); } }); Futures.addCallback(openCircuit, new FutureCallback<Circuit>() { public void onSuccess(Circuit circuit) { doneSignal.countDown(); } public void onFailure(Throwable thrown) { doneSignal.countDown(); } }); circuitFutures.add(openCircuit); } boolean countedDown = doneSignal.await(timeoutValue, timeoutUnit); try { List<Circuit> circuits = new ArrayList<Circuit>(Futures.successfulAsList(circuitFutures).get()); circuits.removeAll(singleton(null)); int failures = routers.size() - circuits.size(); if (failures > 0) log.warn("{} failures " + (countedDown ? "" : "(including timeout) ") + "opening DNS lookup circuits", failures); return circuits; } catch (ExecutionException e) { throw new RuntimeException(e); } } finally { shutdownThreadPool(); } }
Source:
<code><START> private static float absSP(float f) { <END> return Math.abs(f); }</code><technical_language>Prevent inlining. do want this inlined constant folded</technical_language>

Target:
private static float $opt$noinline$absSP(float f) { if (doThrow) { throw new Error("Something to prevent inlining"); } return Math.abs(f); }
Source:
<code>public static ProtoGrade getGrade(final Authenticator authenticator, final DB dbs, final String requesterId, final String userId, final String courseId, final String assignmentId, final String problemId) throws AuthenticationException, DatabaseAccessException { final Authenticator.AuthType auth = new Authenticator.AuthType(); if (requesterId.equals(userId)) { auth.setCheckUser(true); } else { auth.setCheckAdminOrMod(true); } if (!authenticator.isAuthenticated(COURSE_COLLECTION, courseId, requesterId, 0, auth)) { throw new AuthenticationException(AuthenticationException.INVALID_PERMISSION); } final DBCollection gradeCollection = dbs.getCollection(GRADE_COLLECTION); final BasicDBObject query = new BasicDBObject(COURSE_ID, courseId).append(USER_ID, userId); <START> if (assignmentId == null) { <END> query.append(ASSIGNMENT_ID, new BasicDBObject(EXISTS, false)); } else { query.append(ASSIGNMENT_ID, assignmentId); } if (problemId == null) { query.append(COURSE_PROBLEM_ID, new BasicDBObject(EXISTS, false)); } else { query.append(COURSE_PROBLEM_ID, problemId); } final DBCursor cursor = gradeCollection.find(query); if (!cursor.hasNext()) { throw new DatabaseAccessException("Did not find a grade matching those parameters for that student in course " + courseId); } return buildProtoGrade(cursor.next()); }</code><technical_language>I do a != null check reverse order. I feel flows</technical_language>

Target:
static ProtoGrade getGrade(final Authenticator authenticator, final DB dbs, final String requesterId, final String userId, final String courseId, final String assignmentId, final String problemId) throws AuthenticationException, DatabaseAccessException { final Authenticator.AuthType auth = new Authenticator.AuthType(); if (requesterId.equals(userId)) { auth.setCheckUser(true); } else { auth.setCheckAdminOrMod(true); } if (!authenticator.isAuthenticated(COURSE_COLLECTION, courseId, requesterId, 0, auth)) { throw new AuthenticationException(AuthenticationException.INVALID_PERMISSION); } final DBCollection gradeCollection = dbs.getCollection(GRADE_COLLECTION); final BasicDBObject query = new BasicDBObject(COURSE_ID, courseId).append(USER_ID, userId); if (assignmentId != null) { query.append(ASSIGNMENT_ID, assignmentId); } else { query.append(ASSIGNMENT_ID, new BasicDBObject(EXISTS, false)); } if (problemId != null) { query.append(COURSE_PROBLEM_ID, problemId); } else { query.append(COURSE_PROBLEM_ID, new BasicDBObject(EXISTS, false)); } final DBCursor cursor = gradeCollection.find(query); if (!cursor.hasNext()) { throw new DatabaseAccessException("Did not find a grade matching those parameters for that student in course: " + courseId); } return buildProtoGrade(cursor.next()); }
Source:
<code>public void updateInstanceAssignment(String instance, List<DatastreamTask> assignments) { LOG.info("Updating datastream tasks assigned for instance: " + instance + ", new assignments are: " + tasksToString(assignments)); Set<String> assignmentsNames = new HashSet<>(); Map<String, DatastreamTask> assignmentsMap = new HashMap<>(); assignments.forEach(task -> { String name = task.getDatastreamTaskName(); assignmentsNames.add(name); assignmentsMap.put(name, task); }); Set<String> oldAssignmentNames = new HashSet<>(_zkclient.getChildren(KeyBuilder.instance(_cluster, instance))); Set<String> removed = new HashSet<>(oldAssignmentNames); removed.removeAll(assignmentsNames); <START> if (removed.size() > 0) { <END> removed.forEach(name -> { String path = KeyBuilder.datastreamTask(_cluster, instance, name); _zkclient.delete(path); }); } Set<String> added = new HashSet<>(assignmentsNames); added.removeAll(oldAssignmentNames); if (added.size() > 0) { added.forEach(name -> { DatastreamTask task = assignmentsMap.get(name); String path = KeyBuilder.datastreamTask(_cluster, instance, name); try { _zkclient.create(path, task.toJson(), CreateMode.PERSISTENT); } catch (IOException e) { LOG.error("Failed to assign task [" + name + "] to instance " + instance + ", error: " + e.getMessage()); } }); } }</code><technical_language>necessary</technical_language>

Target:
public void updateInstanceAssignment(String instance, List<DatastreamTask> assignments) { LOG.info("Updating datastream tasks assigned for instance: " + instance + ", new assignments are: " + tasksToString(assignments)); Set<String> assignmentsNames = new HashSet<>(); Map<String, DatastreamTask> assignmentsMap = new HashMap<>(); assignments.forEach(task -> { String name = task.getDatastreamTaskName(); assignmentsNames.add(name); assignmentsMap.put(name, task); }); Set<String> oldAssignmentNames = new HashSet<>(_zkclient.getChildren(KeyBuilder.instance(_cluster, instance))); Set<String> removed = new HashSet<>(oldAssignmentNames); removed.removeAll(assignmentsNames); if (removed.size() > 0) { LOG.info("Instance: " + instance + ", removing assignments: " + setToString(removed)); removed.forEach(name -> { String path = KeyBuilder.datastreamTask(_cluster, instance, name); _zkclient.delete(path); }); } Set<String> added = new HashSet<>(assignmentsNames); added.removeAll(oldAssignmentNames); if (added.size() > 0) { LOG.info("Instance: " + instance + ", adding assignments: " + setToString(added)); added.forEach(name -> { DatastreamTask task = assignmentsMap.get(name); String path = KeyBuilder.datastreamTask(_cluster, instance, name); try { _zkclient.create(path, task.toJson(), CreateMode.PERSISTENT); } catch (IOException e) { LOG.error("Failed to assign task [" + name + "] to instance " + instance + ", error: " + e.getMessage()); } }); } }
Source:
<code>public double fxRate(Currency baseCurrency, Currency counterCurrency, int scenarioIndex) { if (baseCurrency.equals(counterCurrency)) { return 1d; } if (baseCurrency.equals(pair.getBase()) && counterCurrency.equals(pair.getCounter())) { return rates.get(scenarioIndex); } if (counterCurrency.equals(pair.getBase()) && baseCurrency.equals(pair.getCounter())) { return 1d / rates.get(scenarioIndex); } throw new IllegalArgumentException("Unknown rate: " + baseCurrency + "/" + counterCurrency); <START> } <END></code><technical_language>I imagine bulk conversion methods eventually, add needed</technical_language>

Target:
public double fxRate(Currency baseCurrency, Currency counterCurrency, int scenarioIndex) { if (baseCurrency.equals(pair.getBase()) && counterCurrency.equals(pair.getCounter())) { return rates.get(scenarioIndex); } if (counterCurrency.equals(pair.getBase()) && baseCurrency.equals(pair.getCounter())) { return 1d / rates.get(scenarioIndex); } throw new IllegalArgumentException("Unknown rate: " + baseCurrency + "/" + counterCurrency); }
Source:
<code>public TenantIdentityMgtClient(String cookie, String backendServerURL, ConfigurationContext configContext) throws Exception { try { stub = new UserIdentityManagementAdminServiceStub(configContext, backendServerURL + "UserIdentityManagementAdminService"); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (Exception e) { <START> log.error(e.getMessage(), e); <END> throw new Exception("Error occurred while creating TenantIdentityMgtClient Object"); } }</code><technical_language>log e.getMessage(). Check doc above. need log throw here. anti pattern</technical_language>

Target:
public TenantIdentityMgtClient(String cookie, String backendServerURL, ConfigurationContext configContext) throws Exception { try { stub = new UserIdentityManagementAdminServiceStub(configContext, backendServerURL + "UserIdentityManagementAdminService"); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } catch (Exception e) { throw new Exception("Error occurred while creating TenantIdentityMgtClient Object"); } }
Source:
<code>private Set<DistributedEvent> mapDistributedEvents(Set<DefinitionsEvent> notification) { if (notification == null) { return null; } Set<DistributedEvent> events = new HashSet<>(); for (DefinitionsEvent definitionsEvent : notification) { DistributedEvent.Operation op = null; String tenantId = definitionsEvent.getTargetTenantId(); String triggerId = definitionsEvent.getTargetId(); switch (definitionsEvent.getType()) { case TRIGGER_CREATE: op = DistributedEvent.Operation.ADD; break; case TRIGGER_UPDATE: op = DistributedEvent.Operation.UPDATE; break; case TRIGGER_REMOVE: op = DistributedEvent.Operation.REMOVE; break; case TRIGGER_CONDITION_CHANGE: op = DistributedEvent.Operation.UPDATE; break; } if (op != null) { events.add(new DistributedEvent(op, tenantId, triggerId)); } } return events; <START> } <END></code><technical_language>consider merging DefinitionsEvent DistributedEvent thing</technical_language>

Target:
private Set<DistributedEvent> mapDistributedEvents(Set<DefinitionsEvent> notification) { if (notification == null) { return null; } Set<DistributedEvent> events = new LinkedHashSet<>(); for (DefinitionsEvent definitionsEvent : notification) { DistributedEvent.Operation op = null; String tenantId = definitionsEvent.getTargetTenantId(); String triggerId = definitionsEvent.getTargetId(); switch (definitionsEvent.getType()) { case TRIGGER_CREATE: op = DistributedEvent.Operation.ADD; break; case TRIGGER_UPDATE: op = DistributedEvent.Operation.UPDATE; break; case TRIGGER_REMOVE: op = DistributedEvent.Operation.REMOVE; break; case TRIGGER_CONDITION_CHANGE: op = DistributedEvent.Operation.UPDATE; break; } if (op != null) { events.add(new DistributedEvent(op, tenantId, triggerId)); } } return events; }
Source:
<code>private void updateTreeViewerToLevel() { <START> fTreeViewer.refresh(); <END> fTreeViewer.expandToLevel(getIndex()); }</code><technical_language>remember expanded elements, refresh tree, restore expansion level</technical_language>

Target:
private void updateTreeViewerToLevel() { final Object[] elements = fTreeViewer.getExpandedElements(); fTreeViewer.refresh(); fTreeViewer.setExpandedElements(elements); }