auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onIncreaseViewDistance(IncreaseViewDistanceButton button, EntityRef entity) { int viewDistance = config.getRendering().getViewDistance().getIndex(); int maxViewDistance = ViewDistance.values().length - 1; if (viewDistance != maxViewDistance) { ViewDistance greaterViewDistance = ViewDistance.forIndex(viewDistance + 1); <START> config.getRendering().setViewDistance(greaterViewDistance); <END> fireChangeEvent("View distance increased to " + greaterViewDistance.toString() + ".", Arrays.asList(entity)); if (greaterViewDistance == ViewDistance.MEGA || greaterViewDistance == ViewDistance.EXTREME) { fireChangeEvent("Warning: Setting view distance to " + greaterViewDistance.toString() + " may result in performance issues.", Arrays.asList(entity)); } } button.consume(); }</code><technical_language>move actual setting of view distance logging? if fails view distance change chat panel show happen, if briefly (for case a player hit key accidentally realize crashed game) tweak notification message slightly "Increasing view distance to:"</technical_language>

Target:
public void onIncreaseViewDistance(IncreaseViewDistanceButton button, EntityRef entity) { int viewDistance = config.getRendering().getViewDistance().getIndex(); int maxViewDistance = ViewDistance.values().length - 1; if (viewDistance != maxViewDistance) { ViewDistance greaterViewDistance = ViewDistance.forIndex(viewDistance + 1); String greaterViewDistanceStr = translationSystem.translate(greaterViewDistance.toString()); fireChangeEvent("Increasing view distance to " + greaterViewDistanceStr + ".", Arrays.asList(entity)); if (greaterViewDistance == ViewDistance.MEGA || greaterViewDistance == ViewDistance.EXTREME) { fireChangeEvent("Warning: Increasing view distance to " + greaterViewDistanceStr + " may result in performance issues.", Arrays.asList(entity)); } config.getRendering().setViewDistance(greaterViewDistance); } button.consume(); }
Source:
<code>public void invalidateVisualState() { try { this.valueType.setText(this.expr.findType().prettyPrint()); } catch (HaskellTypeError e) { this.valueType.setText("???"); } super.invalidateVisualState(); <START> } <END></code><technical_language>four-space indents, tabs</technical_language>

Target:
public void invalidateVisualState() { try { this.valueType.setText(this.expr.findType().prettyPrint()); } catch (HaskellTypeError e) { this.valueType.setText("???"); } }
Source:
<code>public int getProgress(InterpreterContext context) { <START> return this.sparkInterpreter.getProgress(context); <END> }</code><technical_language>is check sparkInterpreter is null in case</technical_language>

Target:
public int getProgress(InterpreterContext context) { if (this.sparkInterpreter != null) { return this.sparkInterpreter.getProgress(context); } else { return 0; } }
Source:
<code>public int hashCode() { return ((null == mIfaceName) ? 0 : mIfaceName.hashCode() + mLinkAddresses.size() * 31 + mDnses.size() * 37 + mValidatedPrivateDnses.size() * 61 + ((null == mDomains) ? 0 : mDomains.hashCode()) + mRoutes.size() * 41 + ((null == mHttpProxy) ? 0 : mHttpProxy.hashCode()) + mStackedLinks.hashCode() * 47) + mMtu * 51 + ((null == mTcpBufferSizes) ? 0 : mTcpBufferSizes.hashCode()) + (mUsePrivateDns ? 57 : 0) <START> + mPcscfs.size() * 61 + ((null == mPrivateDnsServerName) ? 0 : mPrivateDnsServerName.hashCode()); <END> }</code><technical_language>61 is in line 1389. Suggest 67</technical_language>

Target:
public int hashCode() { return ((null == mIfaceName) ? 0 : mIfaceName.hashCode() + mLinkAddresses.size() * 31 + mDnses.size() * 37 + mValidatedPrivateDnses.size() * 61 + ((null == mDomains) ? 0 : mDomains.hashCode()) + mRoutes.size() * 41 + ((null == mHttpProxy) ? 0 : mHttpProxy.hashCode()) + mStackedLinks.hashCode() * 47) + mMtu * 51 + ((null == mTcpBufferSizes) ? 0 : mTcpBufferSizes.hashCode()) + (mUsePrivateDns ? 57 : 0) + mPcscfs.size() * 67 + ((null == mPrivateDnsServerName) ? 0 : mPrivateDnsServerName.hashCode()); }
Source:
<code>public static boolean isMac() { <START> String osType = System.getenv("_system_name"); <END> if (osType == null || osType.isEmpty() || !osType.equalsIgnoreCase("OSX")) { return false; } return true; }</code><technical_language>Is a reason chose _system_name environment variable instead of os.name system property in [Java properties](<LINK_0> tutorial</technical_language>

Target:
public static boolean isMac() { String osType = System.getProperty("os.name"); if (osType == null || osType.isEmpty() || !osType.toLowerCase(Locale.ENGLISH).contains("mac os x")) { return false; } return true; }
Source:
<code>public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("source"); description.addProperty("identifier"); description.addProperty("comment"); description.addProperty("generatedBy"); description.addProperty("dateGenerated"); description.addSelfLink(); } <START> if (rep instanceof DefaultRepresentation || rep instanceof FullRepresentation) { <END> description = new DelegatingResourceDescription(); description.addProperty("source"); description.addProperty("identifier"); description.addProperty("comment"); description.addProperty("generatedBy"); description.addProperty("dateGenerated"); description.addSelfLink(); if (rep instanceof DefaultRepresentation) { description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } } return description; }</code><technical_language>else if remove empty line</technical_language>

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = null; if (rep instanceof RefRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("display"); description.addProperty("identifier"); description.addSelfLink(); } else if (rep instanceof DefaultRepresentation || rep instanceof FullRepresentation) { description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("source"); description.addProperty("identifier"); description.addProperty("comment"); description.addProperty("generatedBy"); description.addProperty("dateGenerated"); description.addSelfLink(); if (rep instanceof DefaultRepresentation) { description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); } } return description; }
Source:
<code>protected Histogram<Integer> getHighQualityDepthHistogram() { <START> return getHistogram(highQualityDepthHistogramArray,"coverage", "count"); <END> }</code><technical_language>if do include multiple depth histograms x axis is recycled, means put enough information in count label clear is. "HighQualityDepthCount" etc</technical_language>

Target:
protected Histogram<Integer> getHighQualityDepthHistogram() { return getHistogram(highQualityDepthHistogramArray, "coverage", "high_quality_coverage_count"); }
Source:
<code>public static PersistenceObjectStore newPersistenceObjectStore(ManagementContext managementContext, String locationSpec, String locationContainer, PersistMode persistMode, HighAvailabilityMode highAvailabilityMode) { PersistenceObjectStore destinationObjectStore; locationContainer = BrooklynServerPaths.newMainPersistencePathResolver(managementContext).location(locationSpec).dir(locationContainer).resolve(); Location location = null; try { if (Strings.isBlank(locationSpec)) { location = managementContext.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)); } else { location = managementContext.getLocationRegistry().resolve(locationSpec); if (!(location instanceof LocationWithObjectStore)) { throw new IllegalArgumentException("Destination location "+location+" does not offer a persistent store"); } } } finally { <START> if (location!=null) managementContext.getLocationManager().unmanage(location); <END> } destinationObjectStore = ((LocationWithObjectStore)location).newPersistenceObjectStore(locationContainer); destinationObjectStore.injectManagementContext(managementContext); destinationObjectStore.prepareForSharedUse(persistMode, highAvailabilityMode); return destinationObjectStore; }</code><technical_language>unmanage clears config subsequent calls getIdentity & fail. request unmanaged location explicitly instead</technical_language>

Target:
public static PersistenceObjectStore newPersistenceObjectStore(ManagementContext managementContext, String locationSpec, String locationContainer, PersistMode persistMode, HighAvailabilityMode highAvailabilityMode) { PersistenceObjectStore destinationObjectStore; locationContainer = BrooklynServerPaths.newMainPersistencePathResolver(managementContext).location(locationSpec).dir(locationContainer).resolve(); Location location = null; if (Strings.isBlank(locationSpec)) { location = managementContext.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class) .configure(LocalLocationManager.CREATE_UNMANAGED, true)); } else { location = managementContext.getLocationRegistry().resolve(locationSpec, false, null).get(); if (!(location instanceof LocationWithObjectStore)) { throw new IllegalArgumentException("Destination location "+location+" does not offer a persistent store"); } } destinationObjectStore = ((LocationWithObjectStore)location).newPersistenceObjectStore(locationContainer); destinationObjectStore.injectManagementContext(managementContext); destinationObjectStore.prepareForSharedUse(persistMode, highAvailabilityMode); return destinationObjectStore; }
Source:
<code>public void startRecording(final File toFile) { if (isRecording()) { throw new IllegalStateException("Already recording"); } recordedVideo = toFile; try { recordedVideo.createNewFile(); } catch (IOException ex) { throw new RuntimeException("Unable to create file to which video will be saved: " + recordedVideo.getAbsolutePath()); } running = true; thread = new Thread(new Runnable() { @Override public void run() { Webcam webcam = Webcam.getDefault(); webcam.setViewSize(screenBounds); webcam.open(); try { SequenceEncoder enc = new SequenceEncoder(recordedVideo); timer = new Timer(); timer.schedule(new TestTimeoutTask(), TimeUnit.SECONDS.toMillis(configuration.getTestTimeout())); while (running) { BufferedImage bgrScreen = webcam.getImage(); enc.encodeImage(bgrScreen); try { <START> Thread.sleep(500 / frameRate); <END> } catch (InterruptedException ex) { logger.log(Level.WARNING, "Exception occured during video recording", ex); } if (!running) { enc.finish(); } } } catch (IOException ex) { logger.log(Level.WARNING, "Exception occured during video recording", ex); } } }); thread.start(); }</code><technical_language>is 500 for? I dont understand (500 / framerate) ..</technical_language>

Target:
public void startRecording(final File toFile) { if (isRecording()) { throw new IllegalStateException("Already recording"); } recordedVideo = toFile; try { recordedVideo.createNewFile(); } catch (IOException ex) { throw new RuntimeException("Unable to create file to which video will be saved: " + recordedVideo.getAbsolutePath()); } running = true; thread = new Thread(new Runnable() { @Override public void run() { Webcam webcam = Webcam.getDefault(); if (screenBounds != null) { webcam.setViewSize(screenBounds); } else { final Dimension[] viewSizes = webcam.getViewSizes(); if (viewSizes.length == 0) { throw new IllegalArgumentException("No valid dimensions to record webcam and no default values in driver."); } screenBounds = viewSizes[0]; } webcam.open(); try { SequenceEncoder enc = new SequenceEncoder(recordedVideo); timer = new Timer(); timer.schedule(new TestTimeoutTask(), TimeUnit.SECONDS.toMillis(configuration.getTestTimeout())); while (running) { BufferedImage bgrScreen = webcam.getImage(); enc.encodeImage(bgrScreen); try { Thread.sleep(ONE_SECOND / frameRate); } catch (InterruptedException ex) { logger.log(Level.WARNING, "Exception occured during video recording", ex); } if (!running) { enc.finish(); } } } catch (IOException ex) { logger.log(Level.WARNING, "Exception occured during video recording", ex); } } }); thread.start(); }
Source:
<code>public void testActivationSonarLint() { PHPRulesDefinition rulesDefinition = new PHPRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository("php"); List<Rule> activated = repository.rules().stream().filter(Rule::activatedByDefault).collect(Collectors.toList()); assertThat(activated).isNotEmpty(); assertThat(activated.size()).isLessThan(CheckList.getAllChecks().size()); <START> } <END></code><technical_language>do drop that</technical_language>

Target:
public void testActivationSonarLint() { PHPRulesDefinition rulesDefinition = new PHPRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository("php"); assertThat(repository.name()).isEqualTo("SonarAnalyzer"); assertThat(repository.language()).isEqualTo("php"); assertThat(repository.rules()).hasSize(CheckList.getAllChecks().size()); List<Rule> activated = repository.rules().stream().filter(Rule::activatedByDefault).collect(Collectors.toList()); assertThat(activated).isNotEmpty(); assertThat(activated.size()).isLessThan(CheckList.getAllChecks().size()); }
Source:
<code>private List<Class<?>> findClassesForUri(URI baseUri, String basePackageName, ClassFilter classFilter) { try (CloseablePath closeablePath = CloseablePath.create(baseUri)) { Path baseDir = closeablePath.getPath(); return findClassesForPath(baseDir, basePackageName, classFilter); } <START> catch (org.junit.platform.commons.PreconditionViolationException ex) { <END> throw ex; } catch (Exception ex) { logger.warn(ex, () -> "Error scanning files for URI " + baseUri); return emptyList(); } }</code><technical_language>replace this import well</technical_language>

Target:
private List<Class<?>> findClassesForUri(URI baseUri, String basePackageName, ClassFilter classFilter) { try (CloseablePath closeablePath = CloseablePath.create(baseUri)) { Path baseDir = closeablePath.getPath(); return findClassesForPath(baseDir, basePackageName, classFilter); } catch (PreconditionViolationException ex) { throw ex; } catch (Exception ex) { logger.warn(ex, () -> "Error scanning files for URI " + baseUri); return emptyList(); } }
Source:
<code>public void prepare(Object o) { executor = getExecutor(); running.set(true); try { lock.writeLock().lock(); providerQueue = constructQueue(); } finally { lock.writeLock().unlock(); } Preconditions.checkNotNull(providerQueue); Preconditions.checkNotNull(this.klass); Preconditions.checkNotNull(config.getOauth().getConsumerKey()); Preconditions.checkNotNull(config.getOauth().getConsumerSecret()); Preconditions.checkNotNull(config.getOauth().getAccessToken()); Preconditions.checkNotNull(config.getOauth().getAccessTokenSecret()); Preconditions.checkNotNull(config.getInfo()); List<String> screenNames = new ArrayList<String>(); List<String[]> screenNameBatches = new ArrayList<String[]>(); List<Long> ids = new ArrayList<Long>(); List<Long[]> idsBatches = new ArrayList<Long[]>(); for(String s : config.getInfo()) { if(s != null) { String potentialScreenName = s.replaceAll("@", "").trim().toLowerCase(); try { ids.add(Long.parseLong(potentialScreenName)); <START> } catch (Exception e) { <END> screenNames.add(potentialScreenName); } if(ids.size() >= 100) { idsBatches.add(ids.toArray(new Long[ids.size()])); ids = new ArrayList<Long>(); } if(screenNames.size() >= 100) { screenNameBatches.add(screenNames.toArray(new String[ids.size()])); screenNames = new ArrayList<String>(); } } } if(ids.size() > 0) idsBatches.add(ids.toArray(new Long[ids.size()])); if(screenNames.size() > 0) screenNameBatches.add(screenNames.toArray(new String[ids.size()])); this.idsBatches = idsBatches.iterator(); this.screenNameBatches = screenNameBatches.iterator(); }</code><technical_language>Exception NumberFormatException</technical_language>

Target:
public void prepare(Object o) { executor = getExecutor(); try { lock.writeLock().lock(); providerQueue = constructQueue(); } finally { lock.writeLock().unlock(); } Preconditions.checkNotNull(providerQueue); Preconditions.checkNotNull(this.klass); Preconditions.checkNotNull(config.getOauth().getConsumerKey()); Preconditions.checkNotNull(config.getOauth().getConsumerSecret()); Preconditions.checkNotNull(config.getOauth().getAccessToken()); Preconditions.checkNotNull(config.getOauth().getAccessTokenSecret()); Preconditions.checkNotNull(config.getInfo()); consolidateToIDs(); }
Source:
<code>CommentBox(CodeMirror cm, CommentInfo info) { this.cm = cm; CommentRange range = info.range(); if (range != null) { fromTo = FromTo.fromCommentRange(range); rangeMarker = cm.markText( fromTo.getFrom(), fromTo.getTo(), <START> Configuration.create().set("className", <END> DiffTable.style.range())); } }</code><technical_language>nit: line break ( ".set" here</technical_language>

Target:
CommentBox(CodeMirror cm, CommentInfo info) { this.cm = cm; CommentRange range = info.range(); if (range != null) { fromTo = FromTo.create(range); rangeMarker = cm.markText( fromTo.getFrom(), fromTo.getTo(), Configuration.create() .set("className", DiffTable.style.range())); } }
Source:
<code>public void stop(long maxWaitTime) { ArrayList<PluginProgress> matches = new ArrayList<PluginProgress>(); synchronized(this) { stopping = true; for(Iterator<PluginProgress> i = startingPlugins.iterator();i.hasNext();) { PluginProgress progress = i.next(); matches.add(progress); i.remove(); } } for(PluginProgress progress : matches) { progress.kill(); } <START> for(PluginInfoWrapper pi : pluginWrappers) <END> pi.startShutdownPlugin(this, false); long now = System.currentTimeMillis(); long deadline = now + maxWaitTime; while(true) { int delta = (int) (deadline - now); if(delta <= 0) { String list = pluginList(pluginWrappers); Logger.error(this, "Plugins still shutting down at timeout:\n"+list); System.err.println("Plugins still shutting down at timeout:\n"+list); } else { for (PluginInfoWrapper pluginInfoWrapper : pluginWrappers) { System.out.println("Waiting for plugin to finish shutting down: " + pluginInfoWrapper.getFilename()); if (pluginInfoWrapper.finishShutdownPlugin(this, delta, false)) { pluginWrappers.remove(pluginInfoWrapper); } } if (pluginWrappers.isEmpty()) { Logger.normal(this, "All plugins unloaded"); System.out.println("All plugins unloaded"); return; } String list = pluginList(pluginWrappers); Logger.error(this, "Plugins still shutting down:\n"+list); System.err.println("Plugins still shutting down:\n"+list); } } }</code><technical_language>This braces. Oh, a space for</technical_language>

Target:
public void stop(long maxWaitTime) { if(!enabled) return; synchronized (loadedPlugins) { stopping = true; } for (PluginProgress progress : loadedPlugins.getStartingPlugins()) { progress.kill(); } for (PluginInfoWrapper pi : loadedPlugins.getLoadedPlugins()) { pi.startShutdownPlugin(this, false); } long now = System.currentTimeMillis(); long deadline = now + maxWaitTime; while(true) { int delta = (int) (deadline - now); if(delta <= 0) { String list = pluginList(loadedPlugins.getLoadedPlugins()); Logger.error(this, "Plugins still shutting down at timeout:\n"+list); System.err.println("Plugins still shutting down at timeout:\n"+list); } else { for (PluginInfoWrapper pluginInfoWrapper : loadedPlugins.getLoadedPlugins()) { System.out.println("Waiting for plugin to finish shutting down: " + pluginInfoWrapper.getFilename()); if (pluginInfoWrapper.finishShutdownPlugin(this, delta, false)) { loadedPlugins.removeLoadedPlugin(pluginInfoWrapper); } } if (!loadedPlugins.hasLoadedPlugins()) { Logger.normal(this, "All plugins unloaded"); System.out.println("All plugins unloaded"); return; } String list = pluginList(loadedPlugins.getLoadedPlugins()); Logger.error(this, "Plugins still shutting down:\n"+list); System.err.println("Plugins still shutting down:\n"+list); } } }
Source:
<code>private static Format determineFileFormat(InputSplit split, Configuration conf) throws IOException { FileSplit fileSplit = (FileSplit)split; Path file = fileSplit.getPath(); CompressionCodec codec = new CompressionCodecFactory(conf).getCodec(file); if (codec == null) { throw new IOException("No codec for file " + file + " found"); } InputStream in = file.getFileSystem(conf).open(file); InputStream lzoIn = null; try { lzoIn = codec.createInputStream(in); for(byte magic : Protobufs.KNOWN_GOOD_POSITION_MARKER) { int b = lzoIn.read(); if (b < 0 || (byte)b != magic) { return Format.LZO_B64LINE; } } } finally { if (lzoIn != null) { <START> lzoIn.close(); <END> } in.close(); } return Format.LZO_BLOCK; }</code><technical_language>if this throws exception "in" get closed. 2 nested try{}finally{}</technical_language>

Target:
private static Format determineFileFormat(InputSplit split, Configuration conf) throws IOException { FileSplit fileSplit = (FileSplit)split; Path file = fileSplit.getPath(); CompressionCodec codec = new CompressionCodecFactory(conf).getCodec(file); if (codec == null) { throw new IOException("No codec for file " + file + " found"); } InputStream in = file.getFileSystem(conf).open(file); InputStream lzoIn = null; try { lzoIn = codec.createInputStream(in); for(byte magic : Protobufs.KNOWN_GOOD_POSITION_MARKER) { int b = lzoIn.read(); if (b < 0 || (byte)b != magic) { return Format.LZO_B64LINE; } } } finally { IOUtils.closeStream(lzoIn); IOUtils.closeStream(in); } return Format.LZO_BLOCK; }
Source:
<code>private boolean canLiquidsMix(FluidStack resource) { FluidEvent event = new FluidEvent.FluidMixingEvent(resource, tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, this); FluidEvent.fireEvent(event); <START> return event.getResult() == FluidEvent.Result.ALLOW; <END> }</code><technical_language>a result if care is allow? Cancelable exists for boolean things</technical_language>

Target:
private boolean canLiquidsMix(FluidStack resource) { return FluidEvent.fireEvent(new FluidEvent.TankMixingEvent(resource, tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, this)); }
Source:
<code>public boolean isFulfilled(@NonNull ITmfTrace trace) { <START> if ((trace instanceof ITmfTraceWithPreDefinedEvents) && fEventNames.iterator().hasNext()) { <END> Multimap<@NonNull String, @NonNull String> traceEvents = TmfEventTypeCollectionHelper.getEventFieldNames((((ITmfTraceWithPreDefinedEvents) trace).getContainedEventTypes())); Set<String> mandatoryValues = getValues(ValuePriorityLevel.MANDATORY); for (String eventType : fEventNames) { Collection<@NonNull String> fields = traceEvents.get(eventType); return fields.containsAll(mandatoryValues); } return false; } return true; }</code><technical_language>do iterators? I base class does, in place</technical_language>

Target:
public boolean isFulfilled(@NonNull ITmfTrace trace) { if ((trace instanceof ITmfTraceWithPreDefinedEvents)) { Set<String> mandatoryValues = getValues(ValuePriorityLevel.MANDATORY); if (mandatoryValues.isEmpty()) { return true; } Multimap<@NonNull String, @NonNull String> traceEvents = TmfEventTypeCollectionHelper.getEventFieldNames((((ITmfTraceWithPreDefinedEvents) trace).getContainedEventTypes())); Predicate<String> predicate = new Predicate<String>() { @Override public boolean test(@NonNull String eventName) { Collection<@NonNull String> fields = traceEvents.get(eventName); return fields.containsAll(mandatoryValues); } }; if (fEventNames.isEmpty()) { return traceEvents.keys().stream().allMatch(predicate); } return fEventNames.stream().anyMatch(predicate); } return true; }
Source:
<code>TemplateMetadata(@NotNull Document document) { myDocument = document; NodeList parameters = myDocument.getElementsByTagName(TAG_PARAMETER); myParameterMap = new LinkedHashMap<String, Parameter>(parameters.getLength()); for (int index = 0, max = parameters.getLength(); index < max; index++) { Element element = (Element) parameters.item(index); Parameter parameter = new Parameter(this, element); if (parameter.id != null) { myParameterMap.put(parameter.id, parameter); } } NodeList icons = myDocument.getElementsByTagName(TAG_ICONS); if (icons.getLength() > 0) { Element element = (Element) icons.item(0); if (element.hasAttribute(Template.ATTR_TYPE)) { <START> String iconTypeName = element.getAttribute(Template.ATTR_TYPE).toUpperCase(); <END> myIconType = AssetStudioAssetGenerator.AssetType.valueOf(iconTypeName); } else { myIconType = null; } myIconName = element.getAttribute(Template.ATTR_NAME); } else { myIconType = null; myIconName = null; } }</code><technical_language>toUpperCase(Locale.US)</technical_language>

Target:
public TemplateMetadata(@NotNull Document document) { myDocument = document; NodeList parameters = myDocument.getElementsByTagName(TAG_PARAMETER); myParameterMap = new LinkedHashMap<String, Parameter>(parameters.getLength()); for (int index = 0, max = parameters.getLength(); index < max; index++) { Element element = (Element) parameters.item(index); Parameter parameter = new Parameter(this, element); if (parameter.id != null) { myParameterMap.put(parameter.id, parameter); } } NodeList icons = myDocument.getElementsByTagName(TAG_ICONS); if (icons.getLength() > 0) { Element element = (Element) icons.item(0); if (element.hasAttribute(Template.ATTR_TYPE)) { String iconTypeName = element.getAttribute(Template.ATTR_TYPE).toUpperCase(Locale.US); myIconType = AssetStudioAssetGenerator.AssetType.valueOf(iconTypeName); } else { myIconType = null; } myIconName = element.getAttribute(Template.ATTR_NAME); } else { myIconType = null; myIconName = null; } }
Source:
<code>public void test2aNegate() throws IOException { Text colf = new Text("a"); Text colq = new Text("b"); Value dv = new Value(); TreeMap<Key,Value> tm = new TreeMap<Key,Value>(); IteratorSetting is = new IteratorSetting(1, ColumnAgeOffFilter.class); ColumnAgeOffFilter.addTTL(is, new IteratorSetting.Column("a"), 901l); ColumnAgeOffFilter.setNegate(is, true); long ts = System.currentTimeMillis(); for (long i = 0; i < 1000; i++) { Key k = new Key(new Text(String.format("%03d", i)), colf, colq, ts - i); tm.put(k, dv); } <START> assertTrue(tm.size() == 1000); <END> ColumnAgeOffFilter a = new ColumnAgeOffFilter(); assertTrue(a.validateOptions(is.getOptions())); a.init(new SortedMapIterator(tm), is.getOptions(), new DefaultIteratorEnvironment()); a.overrideCurrentTime(ts); a.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(98, size(a)); ColumnAgeOffFilter.addTTL(is, new IteratorSetting.Column("a", "b"), 101l); a.init(new SortedMapIterator(tm), is.getOptions(), new DefaultIteratorEnvironment()); a.overrideCurrentTime(ts); a.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(898, size(a)); ColumnAgeOffFilter.removeTTL(is, new IteratorSetting.Column("a", "b")); a.init(new SortedMapIterator(tm), is.getOptions(), new DefaultIteratorEnvironment()); a = (ColumnAgeOffFilter) a.deepCopy(null); a.overrideCurrentTime(ts); a.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(98, size(a)); }</code><technical_language>Nit, assertEquals give a error message failure</technical_language>

Target:
public void test2aNegate() throws IOException { Text colf = new Text("a"); Text colq = new Text("b"); Value dv = new Value(); TreeMap<Key,Value> tm = new TreeMap<Key,Value>(); IteratorSetting is = new IteratorSetting(1, ColumnAgeOffFilter.class); ColumnAgeOffFilter.addTTL(is, new IteratorSetting.Column("a"), 901l); ColumnAgeOffFilter.setNegate(is, true); long ts = System.currentTimeMillis(); for (long i = 0; i < 1000; i++) { Key k = new Key(new Text(String.format("%03d", i)), colf, colq, ts - i); tm.put(k, dv); } assertTrue(tm.size() == 1000); ColumnAgeOffFilter a = new ColumnAgeOffFilter(); assertTrue(a.validateOptions(is.getOptions())); a.init(new SortedMapIterator(tm), is.getOptions(), new DefaultIteratorEnvironment()); a.overrideCurrentTime(ts); a.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(size(a), 98); ColumnAgeOffFilter.addTTL(is, new IteratorSetting.Column("a", "b"), 101l); a.init(new SortedMapIterator(tm), is.getOptions(), new DefaultIteratorEnvironment()); a.overrideCurrentTime(ts); a.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(size(a), 898); ColumnAgeOffFilter.removeTTL(is, new IteratorSetting.Column("a", "b")); a.init(new SortedMapIterator(tm), is.getOptions(), new DefaultIteratorEnvironment()); a = (ColumnAgeOffFilter) a.deepCopy(null); a.overrideCurrentTime(ts); a.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(size(a), 98); }
Source:
<code>protected void runRule(RuntimeRule rule, RuleEngineCallbackImpl.TriggerData td) { String rUID = rule.getUID(); if (reCallbacks.get(rUID) == null) { return; } synchronized (this) { final RuleStatus ruleStatus = getRuleStatus(rUID); if (ruleStatus != RuleStatus.IDLE) { logger.error("Failed to execute rule ‘{}' with status '{}'", rUID, ruleStatus.name()); return; } } setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.TRIGGERED, RuleStatusDetail.NONE, null, td.getOutputs()), true); try { clearContext(rule); setTriggerOutputs(rUID, td); boolean isSatisfied = calculateConditions(rule); if (isSatisfied) { setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.RUNNING), true); executeActions(rule, true); logger.debug("The rule '{}' is executed.", rUID); } else { logger.debug("The rule '{}' is NOT executed, since it has unsatisfied conditions.", rUID); } } catch (Throwable t) { logger.error("Failed to execute rule '{}': {}", rUID, t.getMessage()); logger.debug("", t); } synchronized (this) { <START> if (getRuleStatus(rUID) == RuleStatus.TRIGGERED || getRuleStatus(rUID) == RuleStatus.RUNNING) { <END> setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.IDLE), true); } } }</code><technical_language>I store output of getRuleStatus(rUID) in a local variable instead of this call twice</technical_language>

Target:
protected void runRule(RuntimeRule rule, RuleEngineCallbackImpl.TriggerData td) { String rUID = rule.getUID(); if (reCallbacks.get(rUID) == null) { return; } try { changeRuleStatus(rule, RuleStatusInfo.createTriggeredStatusInfo(td.getOutputs()), RuleStatus.IDLE); clearContext(rule); setTriggerOutputs(rUID, td); boolean isSatisfied = calculateConditions(rule); if (isSatisfied) { changeRuleStatus(rule, RuleStatusInfo.create(RuleStatus.RUNNING), RuleStatus.TRIGGERED); executeActions(rule, true); logger.debug("The rule '{}' is executed.", rUID); } else { logger.debug("The rule '{}' is NOT executed, since it has unsatisfied conditions.", rUID); } if (getRuleStatus(rUID) != RuleStatus.DISABLED) { changeRuleStatus(rule, RuleStatusInfo.create(RuleStatus.IDLE), RuleStatus.TRIGGERED, RuleStatus.RUNNING); } } catch (Throwable t) { logger.error("Failed to execute rule '{}': {}", rUID, t.getMessage()); logger.debug("", t); } }
Source:
<code>public void attachListeners() { this.windowListener = new WindowListener(this); this.workbench.addWindowListener(windowListener); addListenersToAlreadyOpenWindows(); new JUnitListener(); new GeneralActivityListener(workbench.getDisplay()); addDebuggerListeners(); addShutdownListeners(); <START> addStaticAnalysisListeners(); <END> }</code><technical_language>move</technical_language>

Target:
public void attachListeners() { this.windowListener = new WindowListener(this.trackingEventManager); this.workbench.addWindowListener(windowListener); addListenersToAlreadyOpenWindows(); new JUnitListener(); new GeneralActivityListener(workbench.getDisplay()); addDebuggerListeners(); addStaticAnalysisListeners(); addShutdownListeners(); }
Source:
<code>public void sittable$setOwner(Tamer tamer) { if (tamer instanceof EntityPlayer) { <START> this.func_152115_b(((EntityPlayer) tamer).getName()); <END> this.tamer = null; } else { this.func_152115_b(null); this.tamer = tamer; } }</code><technical_language>a UUID string a name. usage of func_152115_b in vanilla</technical_language>

Target:
public void sittable$setOwner(Tamer tamer) { if (tamer instanceof EntityPlayer) { this.func_152115_b(((EntityPlayer) tamer).getUniqueID().toString()); this.tamer = null; } else { this.func_152115_b(null); this.tamer = tamer; } }
Source:
<code>public void shouldUploadReservedIdentifiers() throws Exception { String reservedIdentifiers = "{\"reservedIdentifiers\": \"1,2,3,4\"," + "\"sourceUuid\": \""+SEQUENTIAL_IDENTIFIER_SOURCE_UUID+"\"}"; MockHttpServletRequest getRequest = newGetRequest(getURI() + "/" + SEQUENTIAL_IDENTIFIER_SOURCE_UUID); getRequest.addParameter("v", "custom:(reservedIdentifiers)"); SimpleObject initialIdentifiers = deserialize(handle(getRequest)); assertEquals(initialIdentifiers.get("reservedIdentifiers").toString(), "[]"); newPostRequest(getURI() + "/" + SEQUENTIAL_IDENTIFIER_SOURCE_UUID, reservedIdentifiers); MockHttpServletRequest getRequestAfterPost = newGetRequest(getURI() + "/" + SEQUENTIAL_IDENTIFIER_SOURCE_UUID); getRequestAfterPost.addParameter("v", "custom:(reservedIdentifiers)"); SimpleObject identifiersAfterUpload = deserialize(handle(getRequestAfterPost)); <START> assertEquals(identifiersAfterUpload.get("reservedIdentifiers").toString(), "[1,2,3,4]"); <END> }</code><technical_language>expect parameter</technical_language>

Target:
public void shouldUploadReservedIdentifiers() throws Exception { String reservedIdentifiers = "{\"reservedIdentifiers\": \"1,2,3,4\"}"; MockHttpServletRequest getRequest = newGetRequest(getURI() + "/" + SEQUENTIAL_IDENTIFIER_SOURCE_UUID); getRequest.addParameter("v", "custom:(reservedIdentifiers)"); SimpleObject initialIdentifiers = deserialize(handle(getRequest)); assertEquals("[]", initialIdentifiers.get("reservedIdentifiers").toString()); MockHttpServletRequest postRequest = newPostRequest(getURI() + "/" + SEQUENTIAL_IDENTIFIER_SOURCE_UUID, reservedIdentifiers); SimpleObject uploadResult = deserialize(handle(postRequest)); assertThat( uploadResult.toString(), containsString(SEQUENTIAL_IDENTIFIER_SOURCE_UUID) ); MockHttpServletRequest getRequestAfterUpload = newGetRequest(getURI() + "/" + SEQUENTIAL_IDENTIFIER_SOURCE_UUID); getRequestAfterUpload.addParameter("v", "custom:(reservedIdentifiers)"); SimpleObject identifiersAfterUpload = deserialize(handle(getRequestAfterUpload)); assertEquals("[1, 2, 3, 4]", identifiersAfterUpload.get("reservedIdentifiers").toString()); }
Source:
<code>public void testCookieAuthWithoutRetry() throws IOException { CookieInterceptor interceptor = new CookieInterceptor(CloudantClientHelper.COUCH_USERNAME, <START> CloudantClientHelper.COUCH_PASSWORD, dbResource.get().getDBUri().toString()); <END> HttpConnection conn = new HttpConnection("POST", dbResource.get().getDBUri().toURL(), "application/json"); conn.responseInterceptors.add(interceptor); conn.requestInterceptors.add(interceptor); ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); assertEquals(data.getBytes().length, bis.available()); conn.setRequestBody(bis); HttpConnection responseConn = conn.execute(); assertEquals(0, bis.available()); assertEquals(2, responseConn.getConnection().getResponseCode() / 100); Gson gson = new Gson(); InputStream is = responseConn.responseAsInputStream(); try { JsonObject response = gson.fromJson(new InputStreamReader(is), JsonObject.class); assertTrue(response.has("ok")); assertTrue(response.get("ok").getAsBoolean()); assertTrue(response.has("id")); assertTrue(response.has("rev")); } finally { is.close(); } }</code><technical_language>This clientResource is baseURI is needed</technical_language>

Target:
public void testCookieAuthWithoutRetry() throws IOException { CookieInterceptor interceptor = new CookieInterceptor(CloudantClientHelper.COUCH_USERNAME, CloudantClientHelper.COUCH_PASSWORD, clientResource.get().getBaseUri().toString()); HttpConnection conn = new HttpConnection("POST", dbResource.get().getDBUri().toURL(), "application/json"); conn.responseInterceptors.add(interceptor); conn.requestInterceptors.add(interceptor); ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); assertEquals(data.getBytes().length, bis.available()); conn.setRequestBody(bis); HttpConnection responseConn = conn.execute(); assertEquals(0, bis.available()); assertEquals(2, responseConn.getConnection().getResponseCode() / 100); Gson gson = new Gson(); InputStream is = responseConn.responseAsInputStream(); try { JsonObject response = gson.fromJson(new InputStreamReader(is), JsonObject.class); assertTrue(response.has("ok")); assertTrue(response.get("ok").getAsBoolean()); assertTrue(response.has("id")); assertTrue(response.has("rev")); } finally { is.close(); } }
Source:
<code>@Override public void injectMembers(T t) { <START> throw new UnsupportedOperationException(); END> }</code><technical_language>Similarly</technical_language>

Target:
@Override public void injectMembers(T t) { throw new AssertionError("Provides method bindings are not MembersInjectors"); }
Source:
<code>private static LanguageServerWrapper getLSWrapperForConnection(@NonNull IProject project, @NonNull LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) throws IOException { <START> return addStartedServerSynchronized(() -> { <END> LanguageServerWrapper wrapper = null; for (LanguageServerWrapper startedWrapper : getStartedLSWrappers(project)) { if (startedWrapper.serverDefinition.equals(serverDefinition)) { wrapper = startedWrapper; break; } } if (wrapper == null) { wrapper = project != null ? new LanguageServerWrapper(project, serverDefinition) : new LanguageServerWrapper(serverDefinition, initialPath); wrapper.start(); } return wrapper; }); }</code><technical_language>a big fan of this construct, hides synchronizing (which is IMO critical information explicit deal synchronization. a requirement for codeLens/command stuff, please stick previous version, create a separate patch discuss this refactoring</technical_language>

Target:
private static LanguageServerWrapper getLSWrapperForConnection(@NonNull IProject project, @NonNull LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) throws IOException { LanguageServerWrapper wrapper = null; synchronized (startedServers) { for (LanguageServerWrapper startedWrapper : getStartedLSWrappers(project)) { if (startedWrapper.serverDefinition.equals(serverDefinition)) { wrapper = startedWrapper; break; } } if (wrapper == null) { wrapper = project != null ? new LanguageServerWrapper(project, serverDefinition) : new LanguageServerWrapper(serverDefinition, initialPath); wrapper.start(); } startedServers.add(wrapper); } return wrapper; }
Source:
<code><START> public List<Node> getNodes() { <END> return getContents(); }</code><technical_language>Instead of methods, getNodes getContents, in regular blocks, I pick name. getContents, getNodes is fine me. if prefer getNodes, I deprecate getContents for removal this duplication</technical_language>

Target:
public List<Node> getNodes() { return Collections.unmodifiableList(contents); }
Source:
<code>public AndPredicate( @JsonProperty("predicates") List<JoinPredicate> predicates ) { <START> this.predicates = predicates; <END> }</code><technical_language>add null check, if equals() is implemented null precautions</technical_language>

Target:
public AndPredicate( @JsonProperty("predicates") List<JoinPredicate> predicates ) { Preconditions.checkArgument(predicates != null && !predicates.isEmpty(), "predicates"); this.predicates = predicates; }
Source:
<code>public void testAddSubprocessItemDefs() throws Exception { final List<ItemDefinition> itemDefinitionList = new ArrayList<>(3); <START> { <END> final ItemDefinition itemDefinition1 = mock(ItemDefinition.class); when(itemDefinition1.getId()).thenReturn("mockItemDefinition1"); itemDefinitionList.add(itemDefinition1); final ItemDefinition itemDefinition2 = mock(ItemDefinition.class); when(itemDefinition2.getId()).thenReturn("mockItemDefinition2"); itemDefinitionList.add(itemDefinition2); final ItemDefinition itemDefinition3 = mock(ItemDefinition.class); when(itemDefinition3.getId()).thenReturn("mockItemDefinition3"); itemDefinitionList.add(itemDefinition3); } itemDefinitionList.stream().forEach(i -> tested.addSubprocessItemDefs(i)); final List<RootElement> rootElementList = new ArrayList<>(3); final Definitions definitions = mock(Definitions.class); when(definitions.getRootElements()).thenReturn(rootElementList); { tested.revisitSubProcessItemDefs(definitions); assertTrue(rootElementList.containsAll(itemDefinitionList)); } { rootElementList.clear(); tested.revisitSubProcessItemDefs(definitions); assertTrue(rootElementList.isEmpty()); } }</code><technical_language>I add braces here. adding missing empty lines removing redundant empty lines sufficient code more readable. please remove redundant braces here</technical_language>

Target:
public void testAddSubprocessItemDefs() throws Exception { final List<ItemDefinition> itemDefinitionList = new ArrayList<>(3); final ItemDefinition itemDefinition1 = mock(ItemDefinition.class); when(itemDefinition1.getId()).thenReturn("mockItemDefinition1"); itemDefinitionList.add(itemDefinition1); final ItemDefinition itemDefinition2 = mock(ItemDefinition.class); when(itemDefinition2.getId()).thenReturn("mockItemDefinition2"); itemDefinitionList.add(itemDefinition2); final ItemDefinition itemDefinition3 = mock(ItemDefinition.class); when(itemDefinition3.getId()).thenReturn("mockItemDefinition3"); itemDefinitionList.add(itemDefinition3); itemDefinitionList.stream().forEach(i -> tested.addSubprocessItemDefs(i)); final List<RootElement> rootElementList = new ArrayList<>(3); final Definitions definitions = mock(Definitions.class); when(definitions.getRootElements()).thenReturn(rootElementList); tested.revisitSubProcessItemDefs(definitions); assertTrue(rootElementList.containsAll(itemDefinitionList)); rootElementList.clear(); tested.revisitSubProcessItemDefs(definitions); assertTrue(rootElementList.isEmpty()); }
Source:
<code>public static Object getTemplateItem(Component template, JsonObject argValue, Type convertedType) { <START> StateNode node = template.getUI().get().getInternals().getStateTree() <END> .getNodeById((int) argValue.getNumber("nodeId")); ModelType propertyType = ((PolymerTemplate<?>) template) .getModelType(convertedType); return propertyType.modelToApplication(node); }</code><technical_language>This impl assumes template is attached. This explicitly checked assertion e.g</technical_language>

Target:
public static Object getTemplateItem(Component template, JsonObject argValue, Type convertedType) { final Optional<UI> ui = template.getUI(); if (ui.isPresent()) { StateNode node = ui.get().getInternals().getStateTree() .getNodeById((int) argValue.getNumber("nodeId")); ModelType propertyType = ((PolymerTemplate<?>) template) .getModelType(convertedType); return propertyType.modelToApplication(node); } throw new IllegalArgumentException( "Event sent for a non attached template component"); }
Source:
<code>public boolean isVisible(By elementLocator) { try { return seleniumWebDriver.findElement(elementLocator).isDisplayed(); } catch (NoSuchElementException ex) { return false; } catch (Exception ex) { <START> LOG.info("Unhandled in \"isVisible()\" method", ex.getClass().getSimpleName()); <END> return false; } }</code><technical_language>omit in \"isVisible()\" method string log4j prints reference itself, logging this info is useless IMHO</technical_language>

Target:
public boolean isVisible(By elementLocator) { try { return seleniumWebDriver.findElement(elementLocator).isDisplayed(); } catch (NoSuchElementException ex) { return false; } }
Source:
<code>protected boolean canDoAction() { if (validateParameters()) { NetworkQosValidator validator = new NetworkQosValidator(getNetworkQoS()); if (!validate(validator.qosExists()) || !validate(validator.consistentDataCenter())) { return false; } else { <START> NetworkQoS oldNetworkQoS = getNetworkQoSDao().get(getNetworkQoS().getId()); <END> if (validateValues()) { if (!oldNetworkQoS.getName().equals(getNetworkQoS().getName())) { return validateNameNotExistInDC(); } } else { return false; } } } return true; }</code><technical_language>get validator</technical_language>

Target:
protected boolean canDoAction() { if (validateParameters()) { NetworkQosValidator validator = new NetworkQosValidator(getNetworkQoS()); return (validate(validator.qosExists()) && !validate(validator.consistentDataCenter()) && !validateValues() && !validate(validator.nameNotTakenInDc())); } return true; }
Source:
<code>public Optional<RemoteException> handle(Response response) { if (response.body() == null || response.body().byteStream() == null || response.isSuccessful() || response.code() == 101) { return Optional.empty(); } Collection<String> contentTypes = response.headers("Content-Type"); if (contentTypes.contains(MediaType.APPLICATION_JSON)) { final String body; try { body = toString(response.body().byteStream()); } catch (IOException e) { return Optional.empty(); } try { SerializableError serializableError = MAPPER.readValue(body, SerializableError.class); return Optional.of(new RemoteException(serializableError, response.code())); } catch (Exception e) { <START> log.warn("Failed to deserialize JSON: {}", String.format( <END> "Error %s. Failed to parse error body and deserialize exception: %s. Body:%n%s", response.code(), e.getMessage(), body), e); } } return Optional.empty(); }</code><technical_language>This log.warn is a bit strange... String.format a double message. if normal safeArg response.code()</technical_language>

Target:
public Optional<RemoteException> handle(Response response) { if (response.body() == null || response.body().byteStream() == null || response.isSuccessful() || response.code() == MoreHttpCodes.SWITCHING_PROTOCOLS) { return Optional.empty(); } Collection<String> contentTypes = response.headers("Content-Type"); if (contentTypes.contains(MediaType.APPLICATION_JSON)) { final String body; try { body = toString(response.body().byteStream()); } catch (IOException e) { return Optional.empty(); } try { SerializableError serializableError = MAPPER.readValue(body, SerializableError.class); return Optional.of(new RemoteException(serializableError, response.code())); } catch (Exception e) { log.warn("Failed to deserialize JSON, could not deserialize SerializableError", SafeArg.of("code", response.code()), UnsafeArg.of("body", body), e); } } return Optional.empty(); }
Source:
<code>protected boolean tryDelete() { boolean result = true; if (folder != null) { result = recursiveDelete(folder); } <START> return result; <END> }</code><technical_language>This method boils java return folder == null || recursiveDelete(folder); java if (folder == null) return true; return recursiveDelete(folder);</technical_language>

Target:
protected boolean tryDelete() { if (folder == null) { return true; } return recursiveDelete(folder); }