auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected BinaryData execute( ModelControllerClient mcc, EndpointService<DMRNodeLocation, DMRSession> endpointService, String modelNodePath, BasicMessageWithExtraData<UpdateCollectionIntervalsRequest> envelope, UpdateCollectionIntervalsResponse response, CommandContext context, DMRSession dmrContext) throws Exception { UpdateCollectionIntervalsRequest request = envelope.getBasicMessage(); Map<PathAddress, String> metricTypes = filterUpdates(mcc, request.getMetricTypes(), false); Map<PathAddress, String> availTypes = filterUpdates(mcc, request.getAvailTypes(), true); if (isEmpty(metricTypes) && isEmpty(availTypes)) { log.debug("Skipping collection interval update, no valid type updates provided."); return null; } CompositeOperationBuilder<?> composite = OperationBuilder.composite(); addUpdates(composite, metricTypes); addUpdates(composite, availTypes); composite.byNameOperation("start") <START> .address(PathAddress.parseCLIStyleAddress("/subsystem=hawkular-wildfly-agent/")) <END> .attribute("restart", "true") .attribute("delay", "500") .parentBuilder(); try { OperationResult<?> opResult = composite.execute(mcc).assertSuccess(); setServerRefreshIndicator(opResult, response); } catch (DmrApiException e) { log.errorf("Failed to update collection intervals: %s", e.getMessage()); throw e; } return null; }</code><technical_language>This work EAP6, please this: [WildflyCompatibilityUtils.parseCLIStyleAddress](<LINK_0> WildflyCompatibilityUtils.parseCLIStyleAddress("/subsystem=hawkular-wildfly-agent/")</technical_language>

Target:
protected BinaryData execute( ModelControllerClient mcc, EndpointService<DMRNodeLocation, DMRSession> endpointService, String modelNodePath, BasicMessageWithExtraData<UpdateCollectionIntervalsRequest> envelope, UpdateCollectionIntervalsResponse response, CommandContext context, DMRSession dmrContext) throws Exception { PathAddress agentAddress = WildflyCompatibilityUtils.parseCLIStyleAddress(modelNodePath); UpdateCollectionIntervalsRequest request = envelope.getBasicMessage(); Map<PathAddress, String> metricTypes = filterUpdates(mcc, request.getMetricTypes(), false, agentAddress); Map<PathAddress, String> availTypes = filterUpdates(mcc, request.getAvailTypes(), true, agentAddress); if (isEmpty(metricTypes) && isEmpty(availTypes)) { log.debug("Skipping collection interval update, no valid type updates provided."); return null; } CompositeOperationBuilder<?> composite = OperationBuilder.composite(); addUpdates(composite, metricTypes); addUpdates(composite, availTypes); composite.allowResourceServiceRestart(false); composite.byNameOperation("start") .address(agentAddress) .attribute("refresh", "true") .attribute("delay", "500") .parentBuilder(); try { OperationResult<?> opResult = composite.execute(mcc).assertSuccess(); setServerRefreshIndicator(opResult, response); } catch (DmrApiException e) { log.errorf("Failed to update collection intervals: %s", e.getMessage()); throw e; } return null; }
Source:
<code>public boolean isAncestorOf(JavaScriptTree tree) { Tree parentTree = tree.getParent(); if (this.equals(parentTree)) { return true; } <START> if (parentTree instanceof JavaScriptTree) { <END> return this.isAncestorOf((JavaScriptTree) parentTree); } return false; }</code><technical_language>@inverno remove this check getParent return JSTree</technical_language>

Target:
public boolean isAncestorOf(JavaScriptTree tree) { Tree parentTree = tree.getParent(); if (this.equals(parentTree)) { return true; } if (parentTree == null) { return false; } return this.isAncestorOf((JavaScriptTree) parentTree); }
Source:
<code>public void deleteNonAdminAccess() throws Exception { ObjectMapper mapper = new ObjectMapper(); context.turnOffAuthorisationSystem(); BitstreamFormat bitstreamFormat = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateAdminAccess") .build(); EPerson user = EPersonBuilder.createEPerson(context) .withNameInMetadata("first", "last") .withEmail("testaze@gmail.com") .withPassword(password) .withLanguage(I18nUtil.getDefaultLocale().getLanguage()) .build(); context.restoreAuthSystemState(); String token = getAuthToken(user.getEmail(), password); getClient(token).perform(delete("/api/core/bitstreamformats/" + bitstreamFormat.getID())) <START> .andExpect(status().isForbidden()); <END> }</code><technical_language>please check bitstreamformat is</technical_language>

Target:
public void deleteNonAdminAccess() throws Exception { ObjectMapper mapper = new ObjectMapper(); context.turnOffAuthorisationSystem(); BitstreamFormat bitstreamFormat = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateAdminAccess") .build(); EPerson user = EPersonBuilder.createEPerson(context) .withNameInMetadata("first", "last") .withEmail("testaze@gmail.com") .withPassword(password) .withLanguage(I18nUtil.getDefaultLocale().getLanguage()) .build(); context.restoreAuthSystemState(); String token = getAuthToken(user.getEmail(), password); getClient(token).perform(delete("/api/core/bitstreamformats/" + bitstreamFormat.getID())) .andExpect(status().isForbidden()); getClient().perform(get("/api/core/bitstreamformats/" + bitstreamFormat.getID())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", Matchers.is( BitstreamFormatMatcher .matchBitstreamFormat(bitstreamFormat.getID(), bitstreamFormat.getMIMEType(), bitstreamFormat.getDescription(), bitstreamFormat.getShortDescription()) ))); }
Source:
<code>public int getLineAtOffset(int offset) { try { return getLineOfOffset(offset); } catch (BadLocationException e) { ConsolePlugin.log(e); return <START> -1; <END> } }</code><technical_language>I prefer "old" style, this a long time clients got. Honestly I prefer throw IllegalArgumentException, I fear this a breaking change. try compatible add a TODO check if safely change "usual" of handling illegal arguments</technical_language>

Target:
public int getLineAtOffset(int offset) { try { return getLineOfOffset(offset); } catch (BadLocationException e) { ConsolePlugin.log(e); return offset < 0 ? 0 : widgetLines - 1; } }
Source:
<code>public MapConfiguration() { <START> this.configMap = new ConcurrentHashMap<String, String>(); <END> }</code><technical_language>1 this. a deal breaker. do in other places, consistently. stands out in file do configMap.containsKey..</technical_language>

Target:
public MapConfiguration() { configMap = new ConcurrentHashMap<String, String>(); }
Source:
<code>public ConnectionProviderUI(IConfigurationElement element) { super(element); editable = Boolean.parseBoolean(element.getAttribute(EDITABLE)); IConfigurationElement[] children = element.getChildren(); ArrayList<IConfigurationElement> wizardPageList = new ArrayList<IConfigurationElement>(); <START> wizardPageList.addAll(Arrays.asList(children)); <END> labelProviderElement = null; for( int i = 0; i < children.length; i++ ) { if( children[i].getName().equals("connectionLabelProvider")) { wizardPageList.remove(children[i]); labelProviderElement = children[i]; } } wizardPages = (IConfigurationElement[]) wizardPageList.toArray(new IConfigurationElement[wizardPageList.size()]); }</code><technical_language>is saing wizardPageList ? bad copy/paste</technical_language>

Target:
public ConnectionProviderUI(IConfigurationElement element) { super(element); editable = Boolean.parseBoolean(element.getAttribute(EDITABLE)); IConfigurationElement[] children = element.getChildren(); ArrayList<IConfigurationElement> wizardPageList = new ArrayList<IConfigurationElement>(); labelProviderElement = null; for( int i = 0; i < children.length; i++ ) { if( children[i].getName().equals("wizardPage")) { wizardPageList.add(children[i]); } else if( children[i].getName().equals("connectionLabelProvider")) { labelProviderElement = children[i]; } } wizardPages = (IConfigurationElement[]) wizardPageList.toArray(new IConfigurationElement[wizardPageList.size()]); }
Source:
<code>public static List<String> normalize(List<URL> urls) throws IOException { HashMap<String, String> inoToFile = new HashMap<String, String>(); List<String> normalized = new ArrayList<String>(); for (URL url: urls) { Path path = Paths.get(url.toString()); BasicFileAttributes attr = null; <START> attr = Files.readAttributes(path, BasicFileAttributes.class); <END> Object fileKey = attr.fileKey(); String s = fileKey.toString(); String inode = s.substring(s.indexOf("ino=") + 4, s.indexOf(")")); inoToFile.put(inode, url.toString()); } for(String key : inoToFile.keySet()) { normalized.add(inoToFile.get(key)); } return normalized; }</code><technical_language>understanding is API's java 7 APIs. Right supporting java 6 in project. This a hard stop, deprecate remove 6 7 support older hadoop versions removed, happen master API's used</technical_language>

Target:
public static Set<String> normalize(List<URL> urls) throws IOException { Set<String> normalized = new LinkedHashSet<String>(); for (URL url : urls) { File file = new File(url.toString()); paths.add(file.getCanonicalPath()); } return normalized; }
Source:
<code>public void before() throws TmfTraceException { <START> SWTWorkbenchBot bot = <END> new SWTWorkbenchBot(); bot.closeAllEditors(); for (SWTBotView viewBot : bot.views()) { viewBot.close(); } SWTBotUtils.openView(TimeGraphViewStub.ID); fViewBot = bot.viewById(TimeGraphViewStub.ID); fViewBot.show(); fTrace = new TmfTraceStub() { @Override public @NonNull String getName() { return "Stub"; } @Override public TmfContext seekEvent(ITmfLocation location) { return new TmfContext(); } }; fTrace.setStartTime(TmfTimestamp.fromNanos(0)); fTrace.setEndTime(TmfTimestamp.fromNanos(180)); TmfTraceStub trace = fTrace; trace.initialize(null, "", ITmfEvent.class); assertNotNull(trace); SWTBotTimeGraph tgBot = new SWTBotTimeGraph(fViewBot.bot()); fViewBot.bot().waitUntil(new TgConditionHelper(t -> tgBot.getEntries().length == 0)); fBounds = getBounds(); UIThreadRunnable.syncExec(() -> TmfSignalManager.dispatchSignal(new TmfTraceOpenedSignal(this, trace, null))); fViewBot.bot().waitUntil(new TgConditionHelper(t -> tgBot.getEntries().length >= 2)); resetTimeRange(bot); bot.waitUntil(new TgConditionHelper(t -> fViewBot.bot().slider().getThumb() > 1)); fBot = bot; }</code><technical_language>fBot =</technical_language>

Target:
public void before() throws TmfTraceException { fBot = new SWTWorkbenchBot(); fBot.closeAllEditors(); for (SWTBotView viewBot : fBot.views()) { viewBot.close(); } SWTBotUtils.openView(TimeGraphViewStub.ID); fViewBot = fBot.viewById(TimeGraphViewStub.ID); fViewBot.show(); fTrace = new TmfTraceStub() { @Override public @NonNull String getName() { return "Stub"; } @Override public TmfContext seekEvent(ITmfLocation location) { return new TmfContext(); } }; fTrace.setStartTime(TmfTimestamp.fromNanos(0)); fTrace.setEndTime(TmfTimestamp.fromNanos(180)); TmfTraceStub trace = fTrace; trace.initialize(null, "", ITmfEvent.class); assertNotNull(trace); SWTBotTimeGraph tgBot = new SWTBotTimeGraph(fViewBot.bot()); fViewBot.bot().waitUntil(new TgConditionHelper(t -> tgBot.getEntries().length == 0)); fBounds = getBounds(); UIThreadRunnable.syncExec(() -> TmfSignalManager.dispatchSignal(new TmfTraceOpenedSignal(this, trace, null))); fViewBot.bot().waitUntil(new TgConditionHelper(t -> tgBot.getEntries().length >= 2)); resetTimeRange(); fBot.waitUntil(new TgConditionHelper(t -> fViewBot.bot().slider().getThumb() > 1)); }
Source:
<code>public long getFilePointer() { try { return currentPageId * pageSize + currentPageOffset - startPosition; } <START> catch ( NullPointerException npe ) <END> { throw new AlreadyClosedException( "Already closed: " + this ); } }</code><technical_language>null here</technical_language>

Target:
public long getFilePointer() { return currentPageId * pageSize + currentPageOffset - startPosition; }
Source:
<code>private QName getQName(String name) { final int colon = name == null ? -1 : name.indexOf(':'); <START> final String prefix = name != null && colon > 0 ? name.substring(0, colon) : ""; <END> final String local = name != null && colon > 0 ? (colon + 1 < name.length() ? name.substring(colon + 1) : "") : name; final String namespace = getNamespace(prefix); return new QName(namespace, local, prefix); }</code><technical_language>sense for helper methods getPrefix getLocal. local processing is a bit involved for line</technical_language>

Target:
private QName getQName(String name) { final int colon = name == null ? -1 : name.indexOf(':'); final String prefix = getPrefix(name, colon); final String local = getLocal(name, colon); final String namespace = getNamespace(prefix); return new QName(namespace, local, prefix); }
Source:
<code>public void addRow(final String rowText) { if (insertedRows.contains(rowText)) { return; } final int row = getRowCount(); insertRow(row); setText(row, 0, rowText); <START> insertedRows.add(rowText); <END> final Image upImage = new Image(Gerrit.RESOURCES.removeSelectedProject()); final PushButton removeSelecteProjectButton = new PushButton(upImage); removeSelecteProjectButton.setStylePrimaryName(Gerrit.RESOURCES.css().buttonTrash()); removeSelecteProjectButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { deleteRow(rowText); if (deleteListener != null) { deleteListener.onDeleteRow(rowText); } } }); setWidget(row, 1, removeSelecteProjectButton); final FlexCellFormatter fmt = getFlexCellFormatter(); fmt.addStyleName(row, 0, Gerrit.RESOURCES.css().selectedProjectsDataCell()); fmt.addStyleName(row, 0, Gerrit.RESOURCES.css().leftMostCell()); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().selectedProjectsDataCell()); fmt.setAlignment(row, 1, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE); }</code><technical_language>for project selected a new row is appended SelectedItemsTable. This means projects in SelectedItemsTable sorted in order in selected. I find more convinient if sorted name</technical_language>

Target:
public void addRow(final String rowText) { if (insertedRows.contains(rowText)) { return; } insertedRows.add(rowText); if (insertedRows.size() > 1) { Collections.sort(insertedRows, new Comparator<String>() { public int compare(final String a, final String b) { return a.compareTo(b); } }); } while (1 < getRowCount()) removeRow(getRowCount() - 1); for (final String k : insertedRows) { final int row = getRowCount(); insertRow(row); setText(row, 0, k); final Image upImage = new Image(Gerrit.RESOURCES.removeSelectedProject()); final PushButton removeSelecteProjectButton = new PushButton(upImage); removeSelecteProjectButton.setStylePrimaryName(Gerrit.RESOURCES.css() .buttonTrash()); removeSelecteProjectButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { deleteRow(k); handlerManager.fireEvent(new TableDeleteEvent(k)); } }); setWidget(row, 1, removeSelecteProjectButton); final FlexCellFormatter fmt = getFlexCellFormatter(); fmt.addStyleName(row, 0, Gerrit.RESOURCES.css() .selectedProjectsDataCell()); fmt.addStyleName(row, 0, Gerrit.RESOURCES.css().leftMostCell()); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css() .selectedProjectsDataCell()); fmt.setAlignment(row, 1, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE); } }
Source:
<code>public FirebaseListAdapter(Activity activity, Class<T> modelClass, int modelLayout, Query ref) { mModelClass = modelClass; mLayout = modelLayout; mActivity = activity; mSnapshots = new FirebaseArray(ref); mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() { @Override public void onChanged(EventType type, int index, int oldIndex) { notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { <START> FirebaseRecyclerAdapter.this.onCancelled(databaseError); <END> } }); }</code><technical_language>I FirebaseListAdapter.this here, (rather FirebaseRecyclerAdapter.this)</technical_language>

Target:
public FirebaseListAdapter(Activity activity, Class<T> modelClass, int modelLayout, Query ref) { mModelClass = modelClass; mLayout = modelLayout; mActivity = activity; mSnapshots = new FirebaseArray(ref); mSnapshots.setOnChangedListener(new FirebaseArray.OnChangedListener() { @Override public void onChanged(EventType type, int index, int oldIndex) { notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { FirebaseListAdapter.this.onCancelled(databaseError); } }); }
Source:
<code>private static RequestMappingContext getMappingForSite(RequestMappingContext mapping, Site site) { Map<String, Object> mappingsConfig = site.getTheme().getConfigMap("mappings"); <START> if (!mapping.isAnnotated(site.isJournalSpecific() ? JOURNAL_SPECIFIC : JOURNAL_NEUTRAL)) { <END> return null; } Map<String, Object> override = (Map<String, Object>) mappingsConfig.get(mapping.getAnnotation().name()); if (override != null) { Boolean disabled = (Boolean) override.get("disabled"); if (disabled != null && disabled) { return null; } String overridePattern = (String) override.get("pattern"); if (overridePattern != null) { mapping = mapping.override(overridePattern); } } if (site.getRequestScheme().hasPathToken()) { mapping = mapping.addSiteToken(); } return mapping; }</code><technical_language>if plans ultimately this check in other places in future, lose this boolean site instanceof JournalSite instead do elsewhere</technical_language>

Target:
private static RequestMappingContext getMappingForSite(RequestMappingContext mapping, Site site) { Map<String, Object> mappingsConfig = site.getTheme().getConfigMap("mappings"); if (!mapping.hasScope((site instanceof JournalSite) ? JOURNAL_SPECIFIC : JOURNAL_NEUTRAL)) { return null; } Map<String, Object> override = (Map<String, Object>) mappingsConfig.get(mapping.getAnnotation().name()); if (override != null) { Boolean disabled = (Boolean) override.get("disabled"); if (disabled != null && disabled) { return null; } String overridePattern = (String) override.get("pattern"); if (overridePattern != null) { mapping = mapping.override(overridePattern); } } if (site.getRequestScheme().hasPathToken()) { mapping = mapping.addSiteToken(); } return mapping; }
Source:
<code>public Element toElement(ElasticSearchDatastore datastore) { final Element ds = getDocument().createElement("elasticsearch-datastore"); ds.setAttribute("name", datastore.getName()); if (!StringUtils.isNullOrEmpty(datastore.getDescription())) { ds.setAttribute("description", datastore.getDescription()); } appendElement(ds, "hostname", datastore.getHostname()); appendElement(ds, "port", datastore.getPort()); appendElement(ds, "cluster-name", datastore.getClusterName()); appendElement(ds, "index-name", datastore.getIndexName()); appendElement(ds, "username", datastore.getUsername()); appendElement(ds, "password", encodePassword(datastore.getPassword())); appendElement(ds, "ssl", datastore.getSsl()); <START> appendElement(ds, "keystorePath", datastore.getKeystorePath()); <END> appendElement(ds, "keystorePassword", encodePassword(datastore.getKeystorePassword())); return ds; }</code><technical_language>xsd is updated, this string updated of course</technical_language>

Target:
public Element toElement(ElasticSearchDatastore datastore) { final Element ds = getDocument().createElement("elasticsearch-datastore"); ds.setAttribute("name", datastore.getName()); if (!StringUtils.isNullOrEmpty(datastore.getDescription())) { ds.setAttribute("description", datastore.getDescription()); } appendElement(ds, "hostname", datastore.getHostname()); appendElement(ds, "port", datastore.getPort()); appendElement(ds, "cluster-name", datastore.getClusterName()); appendElement(ds, "index-name", datastore.getIndexName()); appendElement(ds, "username", datastore.getUsername()); appendElement(ds, "password", encodePassword(datastore.getPassword())); appendElement(ds, "ssl", datastore.getSsl()); if (datastore.getSsl()) { appendElement(ds, "keystore-path", datastore.getKeystorePath()); appendElement(ds, "keystore-password", encodePassword(datastore.getKeystorePassword())); } return ds; }
Source:
<code>protected int getDeviceID(SimpleBinaryByteBuffer inBuffer) { try { inBuffer.flip(); int receivedID = inBuffer.get(); inBuffer.rewind(); return receivedID; } catch (ModeChangeException ex) { <START> <END> } finally { try { inBuffer.compact(); } catch (ModeChangeException e) { } } return -1; }</code><technical_language>Need handle this exception</technical_language>

Target:
protected int getDeviceID(SimpleBinaryByteBuffer inBuffer) { try { inBuffer.flip(); int receivedID = inBuffer.get(); inBuffer.rewind(); return receivedID; } catch (ModeChangeException ex) { logger.error("{} - Bad operation: {}", this.toString(), ex.getMessage()); } finally { try { inBuffer.compact(); } catch (ModeChangeException ex) { logger.error("{} - Bad operation: {}", this.toString(), ex.getMessage()); } } return -1; }
Source:
<code>public void commitChanges() throws RemoteException { <START> <END> mVold.commitChanges(); }</code><technical_language>Please delete this blank line. This guarded permissions, non-ideal. caller system process, a check similar verifyEncryptionPassword earlier in file</technical_language>

Target:
public void commitChanges() throws RemoteException { if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) { throw new SecurityException("no permission to commit checkpoint changes"); } mVold.commitChanges(); }
Source:
<code>public ThingTypeConverter() { <START> super(ThingTypeXmlResult.class, "thing-type"); <END> this.attributeMapValidator = new ConverterAttributeMapValidator( new String[][] { { "id", "true" }, { "listed", "false" } }); }</code><technical_language>simpler call: <code>this(ThingTypeXmlResult.class, "thing-type");</code> So, do need add new lines constructors</technical_language>

Target:
public ThingTypeConverter() { this(ThingTypeXmlResult.class, "thing-type"); }
Source:
<code>public char getFirstChar() { final String nameOrNumber = getNameOrNumber(); <START> return Util.isNullOrEmpty(nameOrNumber) ? ' ' : Character.toUpperCase(nameOrNumber.charAt(0)); <END> }</code><technical_language>Character.toTitleCase() of [What is titlecase? is uppercase?](<LINK_0></technical_language>

Target:
public char getFirstChar() { final String nameOrNumber = getNameOrNumber(); return Util.isNullOrEmpty(nameOrNumber) ? ' ' : Character.toTitleCase(nameOrNumber.charAt(0)); }
Source:
<code>public @Nullable Integer getThreadOnCpuAtTime(int cpu, long time) { ITmfStateSystem stateSystem = getStateSystem(); if (stateSystem == null) { return null; } Integer tid = null; try { int cpuQuark = stateSystem.getQuarkAbsolute(Integer.toString(cpu)); ITmfStateValue value = stateSystem.querySingleState(time, cpuQuark).getStateValue(); if (value.getType().equals(Type.INTEGER)) { tid = value.unboxInt(); } } catch (AttributeNotFoundException | StateSystemDisposedException e) { Activator.getDefault().logError(NonNullUtils.nullToEmptyString(e.getMessage()), e); } <START> if (tid != null) { <END> return tid; } return null; }</code><technical_language>simply return tid</technical_language>

Target:
public @Nullable Integer getThreadOnCpuAtTime(int cpu, long time) { ITmfStateSystem stateSystem = getStateSystem(); if (stateSystem == null) { return null; } Integer tid = null; try { int cpuQuark = stateSystem.getQuarkAbsolute(Integer.toString(cpu)); ITmfStateValue value = stateSystem.querySingleState(time, cpuQuark).getStateValue(); if (value.getType().equals(Type.INTEGER)) { tid = value.unboxInt(); } } catch (AttributeNotFoundException | StateSystemDisposedException e) { Activator.getDefault().logError(NonNullUtils.nullToEmptyString(e.getMessage()), e); } return tid; }
Source:
<code>public ValidationResult initialize(RuntimeContainer container, ComponentProperties properties) { <START> CouchbaseInputProperties inputProperties = (CouchbaseInputProperties) properties; <END> this.bootstrapNodes = inputProperties.bootstrapNodes.getStringValue(); this.bucket = inputProperties.bucket.getStringValue(); this.password = inputProperties.password.getStringValue(); this.schema = inputProperties.schema.schema.getValue(); return ValidationResult.OK; }</code><technical_language>instanceof</technical_language>

Target:
public ValidationResult initialize(RuntimeContainer container, ComponentProperties properties) { if (properties instanceof CouchbaseInputProperties) { CouchbaseInputProperties inputProperties = (CouchbaseInputProperties) properties; this.bootstrapNodes = inputProperties.bootstrapNodes.getStringValue(); this.bucket = inputProperties.bucket.getStringValue(); this.password = inputProperties.password.getStringValue(); this.schema = inputProperties.schema.schema.getValue(); return ValidationResult.OK; } return new ValidationResult(Result.ERROR, "Wrong component properties, must be instanceof CouchbaseInputProperties class"); }
Source:
<code><START> public final ExecutionContext context() { <END> return context; }</code><technical_language>this need public</technical_language>

Target:
final ExecutionContext context() { return context; }
Source:
<code>public edu.gemini.itc.base.Disperser disperser(final int order) { return new GnirsGratingOptics( <START> getDirectory() + "/" + getPrefix(), _grating.get(), <END> _centralWavelength, _detector.getDetectorPixels(), order, isLongCamera() ? LONG_CAMERA_SCALE_FACTOR : 1, 1); }</code><technical_language>Calls get() fail runtime, getOrElse is recommended return Option<Disperser></technical_language>

Target:
public edu.gemini.itc.base.Disperser disperser(final int order) { return new GnirsGratingOptics( getDirectory() + "/" + getPrefix(), getGrating(), _centralWavelength, _detector.getDetectorPixels(), order, isLongCamera() ? LONG_CAMERA_SCALE_FACTOR : 1, 1); }
Source:
<code>public void scanFile(XmlFile file) { int lineNumber = 1; for (String line : Utils.splitLines(file.getContents())) { String trimLine = trimEndOfLine(line); int length = trimLine.length(); if (length > maximumLineLength) { XmlTextRange textRange = new XmlTextRange(lineNumber, 0, lineNumber, trimLine.length()); reportIssue(textRange, <START> "Split this " + length + " characters long line (which is greater than " + maximumLineLength + " authorized).", <END> Collections.emptyList()); } lineNumber++; } }</code><technical_language>I prefer formatter, message easily readable reviewing: java String.format("Split this %d characters long line (which is greater %d authorized).", length, maximumLineLength)</technical_language>

Target:
public void scanFile(XmlFile file) { int lineNumber = 1; for (String line : Utils.splitLines(file.getContents())) { String trimLine = trimEndOfLine(line); int length = trimLine.length(); if (length > maximumLineLength) { XmlTextRange textRange = new XmlTextRange(lineNumber, 0, lineNumber, trimLine.length()); reportIssue(textRange, String.format("Split this %d characters long line (which is greater than %d authorized).", length, maximumLineLength), Collections.emptyList()); } lineNumber++; } }
Source:
<code>public boolean apply(Game game, Ability source) { int numOfCardsToReveal = 5; boolean tapped = true; Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { <START> Players allPlayers = game.getPlayers(); <END> for (Player player : allPlayers.values()) { if (player != null) { Library library = player.getLibrary(); Cards cardsToReveal = new CardsImpl(); for (int i = 0; i < numOfCardsToReveal; i++) { if (!library.hasCards()) { break; } Card card = library.getFromTop(game); cardsToReveal.add(card); if (card.isLand()) { player.moveCards(card, Zone.BATTLEFIELD, source, game, tapped, false, true, null); } else { player.moveCards(card, Zone.EXILED, source, game); } } player.revealCards(source, "Revealed cards for " + player.getName(), cardsToReveal, game); } } return true; } return false; }</code><technical_language>players in range, players: game.getState().getPlayersInRange(controller.getId(), game)</technical_language>

Target:
public boolean apply(Game game, Ability source) { boolean tapped = true; Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { Player player = game.getPlayer(playerId); if (player != null) { Library library = player.getLibrary(); Cards cardsToReveal = new CardsImpl(); cardsToReveal.addAll(library.getTopCards(game, 5)); if (!cardsToReveal.isEmpty()) { player.revealCards(source, "Revealed cards for " + player.getName(), cardsToReveal, game); Cards cardsToPutOnBattlefield = new CardsImpl(); Cards cardsToExile = new CardsImpl(); for (Card card : cardsToReveal.getCards(game)) { if (card.isLand()) { cardsToPutOnBattlefield.add(card); } else { cardsToExile.add(card); } } player.moveCards(cardsToPutOnBattlefield.getCards(game), Zone.BATTLEFIELD, source, game, tapped, false, true, null); player.moveCards(cardsToExile.getCards(game), Zone.EXILED, source, game); } } } return true; } return false; }
Source:
<code>public void should_include_default_browserTimezoneOffsetMins_for_Gmt_when_timezone_offset_provided_is_invalid (@Nullable String timeZoneOffsetMins) { <START> Clock gmtClock = Clock.fixed(ZonedDateTime.parse("2020-01-01T10:10:10.100Z").toInstant(), ZoneId.of("Europe/London")); <END> var epdqPayloadDefinitionFor3ds2NewOrder = new EpdqPayloadDefinitionForNew3ds2Order(FRONTEND_URL, SupportedLanguage.ENGLISH, gmtClock); authCardDetails.setJsTimezoneOffsetMins(timeZoneOffsetMins); List<NameValuePair> result = epdqPayloadDefinitionFor3ds2NewOrder.extract(epdqTemplateData); assertThat(result, is(aParameterBuilder().withBrowserTimezoneOffsetMins("0").build())); }</code><technical_language>This clock a constant other (or other a local variable; I mind long consistent)</technical_language>

Target:
public void should_include_default_browserTimezoneOffsetMins_for_Gmt_when_timezone_offset_provided_is_invalid (@Nullable String timeZoneOffsetMins) { var epdqPayloadDefinitionFor3ds2NewOrder = new EpdqPayloadDefinitionForNew3ds2Order(FRONTEND_URL, SupportedLanguage.ENGLISH, GREENWICH_MERIDIAN_TIME_OFFSET_CLOCK); authCardDetails.setJsTimezoneOffsetMins(timeZoneOffsetMins); List<NameValuePair> result = epdqPayloadDefinitionFor3ds2NewOrder.extract(epdqTemplateData); assertThat(result, is(aParameterBuilder().withBrowserTimezoneOffsetMins("0").build())); }
Source:
<code>public boolean isCancelled() { synchronized (mCallTrackers) { if (mCallTrackers.isEmpty()) { <START> throw new IllegalStateException("No tracker registered."); <END> } for (CallTracker callTracker : mCallTrackers) { if (callTracker.isCancelled()) { return true; } } return false; } }</code><technical_language>this throw Exception, return false</technical_language>

Target:
public boolean isCancelled() { return mCallTracker.isCancelled(); }
Source:
<code>String getCookie(URL url){ try { <START> StringBuilder sb = new StringBuilder(); <END> sb.append(url.getProtocol()); sb.append("://"); sb.append(url.getHost()); sb.append(":"); sb.append(url.getPort()); sb.append("/_session"); URL sessionURL = new URL(sb.toString()); HttpConnection conn = Http.POST(sessionURL, "application/json"); conn.responseFilters.clear(); conn.requestFilters.clear(); conn.setRequestBody(cookieRequestBody.getBytes("UTF-8")); String cookieHeader = conn.execute().getConnection().getHeaderField("Set-Cookie"); return cookieHeader.substring(0,cookieHeader.indexOf(";")); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }</code><technical_language>I this URL mangling is ugly necessary. string.format instead</technical_language>

Target:
private String getCookie(URL url){ try { URL sessionURL = new URL(String.format("%s://%s:%d/_session", url.getProtocol(), url.getHost(), url.getPort())); HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded"); conn.setRequestBody(sessionRequestBody); HttpURLConnection connection = conn.execute().getConnection(); String cookieHeader = connection.getHeaderField("Set-Cookie"); int responseCode = connection.getResponseCode(); if(responseCode / 100 == 2){ if(sessionHasStarted(connection.getInputStream())) { return cookieHeader.substring(0, cookieHeader.indexOf(";")); } else { return null; } } else if(responseCode == 401){ shouldAttemptCookieRequest = false; logger.severe("Credentials are incorrect, cookie authentication will not be" + " attempted again by this filter object"); } else if (responseCode / 100 == 5){ logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, cookie auth", responseCode); } else { logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, " + "cookie authentication will not be attempted again", responseCode); shouldAttemptCookieRequest = false; } } catch (MalformedURLException e) { logger.log(Level.SEVERE,"Failed to create URL for _session endpoint",e); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Failed to encode cookieRequest body", e); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read cookie response header", e); } return null; }
Source:
<code>private <T> List<T> testReflectDatumRead(String testType, byte[] bytes, T... entityObjs) throws IOException { ReflectDatumReader<T> datumReader = new ReflectDatumReader<>(); SeekableByteArrayInput avroInputStream = new SeekableByteArrayInput(bytes); DataFileReader<T> fileReader = new DataFileReader<>(avroInputStream, datumReader); Schema schema = fileReader.getSchema(); T record = null; List<T> records = new ArrayList<>(); while (fileReader.hasNext()) { records.add(fileReader.next(record)); } <START> fileReader.close(); <END> return records; }</code><technical_language>a try-with-resource pattern here</technical_language>

Target:
private <T> List<T> testReflectDatumRead(String testType, byte[] bytes, T... entityObjs) throws IOException { ReflectDatumReader<T> datumReader = new ReflectDatumReader<>(); SeekableByteArrayInput avroInputStream = new SeekableByteArrayInput(bytes); List<T> records = new ArrayList<>(); try (DataFileReader<T> fileReader = new DataFileReader<>(avroInputStream, datumReader)) { Schema schema = fileReader.getSchema(); T record = null; while (fileReader.hasNext()) { records.add(fileReader.next(record)); } } return records; }
Source:
<code><START> public void testAllDataProviders() throws URISyntaxException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { <END> int i = 0; for (Class testClass : getClasses("picard")) { if (Modifier.isAbstract(testClass.getModifiers())) continue; for (final Method method : testClass.getMethods()) { if (method.isAnnotationPresent(DataProvider.class)) { System.err.println("Method: " + method.getName()); method.invoke(testClass.newInstance()); i++; } } } Assert.assertNotSame(i,0); System.err.println("Found: "+ i + " @DataProviders."); }</code><technical_language>is purpose of this test? a test all. if asserted signatures of provider methods correct, a useful test</technical_language>

Target:
public void testAllDataProviders() throws IllegalAccessException, InstantiationException, InvocationTargetException { int i = 0; final ClassFinder classFinder = new ClassFinder(); classFinder.find("picard", Object.class); for (Class testClass : classFinder.getClasses()) { if (Modifier.isAbstract(testClass.getModifiers())) continue; for (final Method method : testClass.getMethods()) { if (method.isAnnotationPresent(DataProvider.class)) { System.err.println("Method: " + testClass.getName() + ":" + method.getName()); method.invoke(testClass.newInstance()); i++; } } } Assert.assertNotSame(i,0); System.err.println("Found: "+ i + " @DataProviders."); }
Source:
<code>public static void run() { try { while(true) { <START> flushAllChannels(); <END> Thread.sleep(50); } } catch(InterruptedException e) { } }</code><technical_language>Is for this happen main server thread in actual tick loop, flushing expensive there? Vanilla achieve this</technical_language>

Target:
public static void run() { try { while(true) { flushAllChannels(); Thread.sleep(flushDelay); } } catch(InterruptedException e) { } }
Source:
<code>private boolean isClobCompatibleCastTarget(String castTargetType) { for (int i = 0; i < clobCompatibleCastTargetTypes.length; i++) { <START> if (castTargetType.equalsIgnoreCase(clobCompatibleCastTargetTypes[i]) || castTargetType.toLowerCase().startsWith(clobCompatibleCastTargetTypes[i] + "(")) { <END> return true; } } return false; }</code><technical_language>suggestion if (castTargetType.toLowerCase().indexOf(clobCompatibleCastTargetTypes[i]) == 0 && (castTargetType.length() == clobCompatibleCastTargetTypes[i].length() || castTargetType.charAt(clobCompatibleCastTargetTypes[i].length()) == ')')) {</technical_language>

Target:
private static boolean isClobCompatibleCastTarget(String castTargetType) { for (int i = 0; i < CLOB_COMPATIBLE_CAST_TARGET_TYPES.length; i++) { if (castTargetType.toLowerCase().indexOf(CLOB_COMPATIBLE_CAST_TARGET_TYPES[i]) == 0 && (castTargetType.length() == CLOB_COMPATIBLE_CAST_TARGET_TYPES[i].length() || castTargetType.charAt(CLOB_COMPATIBLE_CAST_TARGET_TYPES[i].length()) == '(') ) { return true; } } return false; }
Source:
<code>public void testNSAndTableQuotaRemoveTableQuotaTableInViolation() throws Exception { final String ns = testName.getMethodName(); NamespaceDescriptor nd = NamespaceDescriptor.create(ns).build(); TEST_UTIL.getAdmin().createNamespace(nd); TableName table1 = helper.createTableInNamespace(nd); TableName table2 = helper.createTableInNamespace(nd); TableName table3 = helper.createTableInNamespace(nd); Put put = new Put(Bytes.toBytes(("to_reject"))); put.addColumn(Bytes.toBytes(SpaceQuotaHelperForTests.F1), Bytes.toBytes("to"), Bytes.toBytes("reject")); helper.setQuotaLimit(nd.getName(), SpaceViolationPolicy.NO_WRITES_COMPACTIONS, 4L); helper.setQuotaLimit(table2, SpaceViolationPolicy.NO_WRITES, 2L); helper.writeData(table2, 2L * SpaceQuotaHelperForTests.ONE_MEGABYTE); helper.verifyViolation(SpaceViolationPolicy.NO_WRITES, table2, put); helper.removeQuotaFromtable(table2); helper.writeData(table1, 1L * SpaceQuotaHelperForTests.ONE_MEGABYTE); helper.writeData(table3, 1L * SpaceQuotaHelperForTests.ONE_MEGABYTE); Put put1 = new Put(Bytes.toBytes(("to_reject1"))); put1.addColumn(Bytes.toBytes(SpaceQuotaHelperForTests.F1), Bytes.toBytes("to"), Bytes.toBytes("reject")); helper.verifyViolation(SpaceViolationPolicy.NO_WRITES_COMPACTIONS, table2, put1); try { TEST_UTIL.getAdmin().majorCompact(table2); fail("Expected that invoking the compaction should throw an Exception"); <START> } catch (DoNotRetryIOException e) { <END> } }</code><technical_language>Is a more specific exception, i.e., QuotaViolatedException, unwrap DNRIOE? good assert presence</technical_language>

Target:
public void testNSAndTableQuotaRemoveTableQuotaTableInViolation() throws Exception { final String ns = testName.getMethodName(); NamespaceDescriptor nd = NamespaceDescriptor.create(ns).build(); TEST_UTIL.getAdmin().createNamespace(nd); TableName table1 = helper.createTableInNamespace(nd); TableName table2 = helper.createTableInNamespace(nd); TableName table3 = helper.createTableInNamespace(nd); Put put = new Put(Bytes.toBytes(("to_reject"))); put.addColumn(Bytes.toBytes(SpaceQuotaHelperForTests.F1), Bytes.toBytes("to"), Bytes.toBytes("reject")); helper.setQuotaLimit(nd.getName(), SpaceViolationPolicy.NO_WRITES_COMPACTIONS, 4L); helper.setQuotaLimit(table2, SpaceViolationPolicy.NO_WRITES, 2L); helper.writeData(table2, 2L * SpaceQuotaHelperForTests.ONE_MEGABYTE); helper.verifyViolation(SpaceViolationPolicy.NO_WRITES, table2, put); helper.removeQuotaFromtable(table2); helper.writeData(table1, 1L * SpaceQuotaHelperForTests.ONE_MEGABYTE); helper.writeData(table3, 1L * SpaceQuotaHelperForTests.ONE_MEGABYTE); Put put1 = new Put(Bytes.toBytes(("to_reject1"))); put1.addColumn(Bytes.toBytes(SpaceQuotaHelperForTests.F1), Bytes.toBytes("to"), Bytes.toBytes("reject")); helper.verifyViolation(SpaceViolationPolicy.NO_WRITES_COMPACTIONS, table2, put1); try { TEST_UTIL.getAdmin().majorCompact(table2); fail("Expected that invoking the compaction should throw an Exception"); } catch (DoNotRetryIOException e) { assertTrue(e.getMessage() .contains("Compactions on this region are disabled due to a space quota violation")); } }
Source:
<code>Optional<BufferAndAvailability> getNextBuffer() throws IOException { checkError(); <START> checkState(partitionRequestClient != null, "Queried for a buffer before requesting a queue."); <END> final Buffer next; final boolean moreAvailable; synchronized (receivedBuffers) { next = receivedBuffers.poll(); moreAvailable = !receivedBuffers.isEmpty(); } if (next == null) { if (isReleased.get()) { throw new CancelTaskException("Queried for a buffer after channel has been released."); } else { throw new IllegalStateException("There should always have queued buffers for unreleased channel."); } } numBytesIn.inc(next.getSize()); numBuffersIn.inc(); return Optional.of(new BufferAndAvailability(next, moreAvailable, 0)); }</code><technical_language>I fine. If want, message updated to: > Queried for a buffer requesting a subpartition</technical_language>

Target:
Optional<BufferAndAvailability> getNextBuffer() throws IOException { checkPartitionRequestQueueInitialized(); final Buffer next; final boolean moreAvailable; synchronized (receivedBuffers) { next = receivedBuffers.poll(); moreAvailable = !receivedBuffers.isEmpty(); } if (next == null) { if (isReleased.get()) { throw new CancelTaskException("Queried for a buffer after channel has been released."); } else { throw new IllegalStateException("There should always have queued buffers for unreleased channel."); } } numBytesIn.inc(next.getSize()); numBuffersIn.inc(); return Optional.of(new BufferAndAvailability(next, moreAvailable, 0)); }
Source:
<code>public void run() { if (!node.isMaster()) { return; } partitionServiceLock.lock(); try { if (!node.getClusterService().getClusterState().isMigrationAllowed()) { <START> triggerRepartitioningWhenClusterStateAllowsMigration = true; <END> if (logger.isFineEnabled()) { logger.fine("Migrations are not allowed yet, " + "repartitioning will be triggered when cluster state allows migrations."); } assignCompletelyLostPartitions(); return; } Address[][] newState = repartition(); if (newState == null) { return; } lastRepartitionTime.set(Clock.currentTimeMillis()); processNewPartitionState(newState); if (ASSERTION_ENABLED) { migrationQueue.add(new AssertPartitionTableTask(partitionService.getMaxAllowedBackupCount())); } migrationQueue.add(new ProcessShutdownRequestsTask()); } finally { partitionServiceLock.unlock(); partitionService.syncPartitionRuntimeState(); } }</code><technical_language>Do need reset this false manage trigger repartitioning cluster state change</technical_language>

Target:
public void run() { if (!node.isMaster()) { return; } partitionServiceLock.lock(); try { triggerRepartitioningWhenClusterStateAllowsMigration = !node.getClusterService().getClusterState().isMigrationAllowed(); if (triggerRepartitioningWhenClusterStateAllowsMigration) { if (logger.isFineEnabled()) { logger.fine("Migrations are not allowed yet, " + "repartitioning will be triggered when cluster state allows migrations."); } assignCompletelyLostPartitions(); return; } Address[][] newState = repartition(); if (newState == null) { return; } lastRepartitionTime.set(Clock.currentTimeMillis()); processNewPartitionState(newState); if (ASSERTION_ENABLED) { migrationQueue.add(new AssertPartitionTableTask(partitionService.getMaxAllowedBackupCount())); } migrationQueue.add(new ProcessShutdownRequestsTask()); } finally { partitionServiceLock.unlock(); partitionService.syncPartitionRuntimeState(); } }
Source:
<code>public boolean deployAPI(String apiId, String gatewayLabel) throws ArtifactSynchronizerException { if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled() && gatewayArtifactSynchronizerProperties.getGatewayLabels().contains(gatewayLabel)) { if (artifactRetriever != null) { try { String gatewayRuntimeArtifact = artifactRetriever.retrieveArtifact(apiId, gatewayLabel, APIConstants.GatewayArtifactSynchronizer.GATEWAY_INSTRUCTION_PUBLISH); <START> if (!StringUtils.isEmpty(gatewayRuntimeArtifact)) { <END> GatewayAPIDTO gatewayAPIDTO = new Gson().fromJson(gatewayRuntimeArtifact, GatewayAPIDTO.class); APIGatewayAdminClient apiGatewayAdminClient = new APIGatewayAdminClient(); apiGatewayAdminClient.deployAPI(gatewayAPIDTO); if (debugEnabled) { log.debug("API with " + apiId + " is deployed in gateway with the label of " + gatewayLabel); } return true; } else { String msg = "Error retrieving artifacts for API " + apiId + ". Storage returned null"; log.error(msg); throw new ArtifactSynchronizerException(msg); } } catch (IOException | ArtifactSynchronizerException e) { String msg = "Error deploying" + apiId + "in Gateway"; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } } else { String msg = "Artifact retriever not found"; log.error(msg); throw new ArtifactSynchronizerException(msg); } } return false; }</code><technical_language>StringUtils.isnotempty</technical_language>

Target:
public boolean deployAPI(String apiId, String gatewayLabel) throws ArtifactSynchronizerException { if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled() && gatewayArtifactSynchronizerProperties.getGatewayLabels().contains(gatewayLabel)) { if (artifactRetriever != null) { try { String gatewayRuntimeArtifact = artifactRetriever.retrieveArtifact(apiId, gatewayLabel, APIConstants.GatewayArtifactSynchronizer.GATEWAY_INSTRUCTION_PUBLISH); if (StringUtils.isNotEmpty(gatewayRuntimeArtifact)) { GatewayAPIDTO gatewayAPIDTO = new Gson().fromJson(gatewayRuntimeArtifact, GatewayAPIDTO.class); APIGatewayAdminClient apiGatewayAdminClient = new APIGatewayAdminClient(); apiGatewayAdminClient.deployAPI(gatewayAPIDTO); if (debugEnabled) { log.debug("API with " + apiId + " is deployed in gateway with the label of " + gatewayLabel); } return true; } else { String msg = "Error retrieving artifacts for API " + apiId + ". Storage returned null"; log.error(msg); throw new ArtifactSynchronizerException(msg); } } catch (IOException | ArtifactSynchronizerException e) { String msg = "Error deploying" + apiId + "in Gateway"; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } } else { String msg = "Artifact retriever not found"; log.error(msg); throw new ArtifactSynchronizerException(msg); } } return false; }
Source:
<code>private static Set<List<JavaFileScannerContext.Location>> collectFlow(Collection<ExplodedGraph.Node> nodes, boolean conditionIsAlwaysTrue) { return nodes.stream() .map(node -> flowFromNode(node, conditionIsAlwaysTrue)) <START> .collect(HashSet::new, Set::addAll, Set::addAll); <END> }</code><technical_language>a testcase for this</technical_language>

Target:
private static Set<List<JavaFileScannerContext.Location>> collectFlow(Collection<ExplodedGraph.Node> nodes, boolean conditionIsAlwaysTrue) { return nodes.stream() .map(node -> flowFromNode(node, conditionIsAlwaysTrue)) .flatMap(Set::stream) .collect(Collectors.toSet()); }