auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void actionPerformed(ActionEvent e) { final List<java.lang.Class<?>> types = new ArrayList<java.lang.Class<?>>(); types.add(com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class.class); final Frame dialogParent = MDDialogParentProvider.getProvider().getDialogParent(); final ElementSelectionDlg dlg = ElementSelectionDlgFactory.create(dialogParent); SessionManager.getInstance().createSession(Application.getInstance().getProject(), "Creating aspect."); final SelectElementTypes set = new SelectElementTypes(types, types, null, null); final SelectElementInfo sei = new SelectElementInfo(true, false, Application.getInstance().getProject().getModel().getOwner(), true); ArrayList<Classifier> aspects = new ArrayList<>(); findAspectsOfClassifier(aspects); ElementSelectionDlgFactory.initMultiple(dlg,set,sei,aspects); dlg.show(); if (dlg.isOkClicked()) { List<BaseElement> selected = dlg.getSelectedElements(); for(BaseElement be : selected){ System.out.println(be.getHumanName()); <START> Stereotype aspectSt = Utils.getStereotype("aspect"); <END> Utils.createDependencyWithStereotype(classToAddAspect, (Element) be, aspectSt); AspectRemedyAction ara = new AspectRemedyAction(classToAddAspect, (Classifier) be); ara.run(); } } SessionManager.getInstance().closeSession(Application.getInstance().getProject()); }</code><technical_language>Stereotypes ID StereotypesHelper. ID a static constant</technical_language>

Target:
public void actionPerformed(ActionEvent e) { final List<java.lang.Class<?>> types = new ArrayList<java.lang.Class<?>>(); types.add(com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class.class); final Frame dialogParent = MDDialogParentProvider.getProvider().getDialogParent(); final ElementSelectionDlg dlg = ElementSelectionDlgFactory.create(dialogParent); SessionManager.getInstance().createSession(Application.getInstance().getProject(), "Creating aspect."); final SelectElementTypes set = new SelectElementTypes(types, types, null, null); final SelectElementInfo sei = new SelectElementInfo(true, false, Application.getInstance().getProject().getModel().getOwner(), true); ArrayList<Classifier> aspects = new ArrayList<>(); findAspectsOfClassifier(aspects); ElementSelectionDlgFactory.initMultiple(dlg, set, sei, aspects); dlg.show(); if (dlg.isOkClicked()) { List<BaseElement> selected = dlg.getSelectedElements(); Element aspectStereotype = Converters.getIdToElementConverter().apply("_18_0_2_407019f_1449688347122_736579_14412", Application.getInstance().getProject()); for (BaseElement be : selected) { System.out.println(be.getHumanName()); if (aspectStereotype != null && aspectStereotype instanceof Stereotype) { Utils.createDependencyWithStereotype(classToAddAspect, (Element) be, (Stereotype) aspectStereotype); AspectRemedyAction ara = new AspectRemedyAction(classToAddAspect, (Classifier) be); ara.run(); } } } SessionManager.getInstance().closeSession(Application.getInstance().getProject()); }
Source:
<code><START> public void stop(Runnable runnable) { <END> }</code><technical_language>need call runnable.run() here. want set running false (also in stop() )</technical_language>

Target:
public void stop(Runnable runnable) { stop(); runnable.run(); }
Source:
<code>public void run() { try (Realm realm = Realm.getDefaultInstance()) { final RealmResults<Person> persons = realm.where(Person.class).findAll(); Realm.Transaction transaction = (Realm r) -> { for (Person person : persons) { person.setAge(person.getAge() + 1); } }; while (!isInterrupted()) { realm.executeTransaction(transaction); <START> Thread.sleep(1000L); <END> } } catch (InterruptedException e) { Log.i(TAG, "Background job stopped."); } }</code><technical_language>Minor: sleep SystemClock.sleep(1000); need of try-catch</technical_language>

Target:
public void run() { try (Realm realm = Realm.getDefaultInstance()) { final RealmResults<Person> persons = realm.where(Person.class).findAll(); Realm.Transaction transaction = (Realm r) -> { for (Person person : persons) { person.setAge(person.getAge() + 1); } }; while (!isInterrupted()) { realm.executeTransaction(transaction); SystemClock.sleep(1000L); } } Log.i(TAG, "Background job stopped."); }
Source:
<code>public long timestampCyclesToNanos(long cycles){ long retVal = cycles + getOffset(); <START> if( getTimeScale() != 1.0 ){ <END> retVal = (long)(retVal * getTimeScale()); } return retVal; }</code><technical_language>saver check for a clock frequency of 1GHz (comparison of long values) instead of checking scale 1.0 (comparison of double values)</technical_language>

Target:
public long timestampCyclesToNanos(long cycles){ long retVal = cycles + getOffset(); if( clockNeedsScale() ) { retVal = (long)(retVal * getTimeScale()); } return retVal; }
Source:
<code>protected Header generateBasicAuthHeader(HttpUriRequest request, Configuration configuration) { Header basicAuthHeader; BasicScheme basicScheme = new BasicScheme(); try { basicAuthHeader = basicScheme.authenticate( new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()), request, HttpClientContext.create()); } catch (Exception e) { <START> return null; <END> } return basicAuthHeader; }</code><technical_language>issue before, this lead a library error in case. In worst case auth silently left user figure this out</technical_language>

Target:
protected Header generateBasicAuthHeader(HttpUriRequest request, Configuration configuration) { Header basicAuthHeader; BasicScheme basicScheme = new BasicScheme(); try { basicAuthHeader = basicScheme.authenticate( new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()), request, HttpClientContext.create()); } catch (Exception e) { throw new BasicAuthException(e); } return basicAuthHeader; }
Source:
<code>public String renderSiteContent(Model model, @SiteParam Site site, @PathVariable String pageName) throws IOException { Theme theme = site.getTheme(); Map<String, Object> pageConfig = theme.getConfigMap("siteContent"); String repoKeyPrefix = (String) pageConfig.get("contentRepoKeyPrefix"); if (repoKeyPrefix == null) { throw new RuntimeConfigurationException("Content repo prefix not configured for theme " + theme.toString()); } String repoKey = repoKeyPrefix.concat(".").concat(pageName); String cacheKey = "siteContent_meta:" + repoKey; Optional<Integer> version = Optional.absent(); try { Map<String, Object> pageMetadata = editorialContentService.requestMetadata(CacheParams.create(cacheKey), repoKey, version); } catch (EntityNotFoundException e) { <START> throw new NotFoundException(); <END> } model.addAttribute("siteContentRepoKey", repoKey); return site + "/ftl/siteContent/container"; }</code><technical_language>new NotFoundException(e)</technical_language>

Target:
public String renderSiteContent(Model model, @SiteParam Site site, @PathVariable String pageName) throws IOException { Theme theme = site.getTheme(); Map<String, Object> pageConfig = theme.getConfigMap("siteContent"); String repoKeyPrefix = (String) pageConfig.get("contentRepoKeyPrefix"); if (repoKeyPrefix == null) { throw new RuntimeConfigurationException("Content repo prefix not configured for theme " + theme.toString()); } String repoKey = repoKeyPrefix.concat(".").concat(pageName); String cacheKey = "siteContent_meta:" + repoKey; Optional<Integer> version = Optional.absent(); try { Map<String, Object> pageMetadata = editorialContentService.requestMetadata(CacheParams.create(cacheKey), repoKey, version); } catch (EntityNotFoundException e) { throw new NotFoundException(e); } model.addAttribute("siteContentRepoKey", repoKey); return site + "/ftl/siteContent/container"; }
Source:
<code>private Map<String, String> sortMapByValue(Map<String, String> map) { List<Map.Entry<String, String>> list = new LinkedList<Map.Entry<String, String>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, String>>() { <START> private Pattern regex = Pattern.compile(SysprepHandler.TimzeZoneExtractTimePattern); <END> @Override public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { int a = 0, b = 0; Matcher match1 = regex.matcher(o1.toString()); Matcher match2 = regex.matcher(o2.toString()); if (match1.matches() && match1.groupCount() > 0) { a = Integer.parseInt(match1.group(1).substring(3).replace(":", "").replace("+", "")); } if (match2.matches() && match2.groupCount() > 0) { b = Integer.parseInt(match2.group(1).substring(3).replace(":", "").replace("+", "")); } return (a > b) ? 1 : 0; } }); Map<String, String> result = new LinkedHashMap<String, String>(); for (Iterator<Map.Entry<String, String>> it = list.iterator(); it.hasNext();) { Map.Entry<String, String> entry = it.next(); result.put(entry.getKey(), entry.getValue()); } return result; }</code><technical_language>this static final Patterns immutable</technical_language>

Target:
private static Map<String, String> sortMapByValue(Map<String, String> map) { List<Map.Entry<String, String>> list = new LinkedList<Map.Entry<String, String>>(map.entrySet()); Collections.sort(list, TimeZoneTimeExtractComperator.instance); Map<String, String> result = new LinkedHashMap<String, String>(); for (Iterator<Map.Entry<String, String>> it = list.iterator(); it.hasNext();) { Map.Entry<String, String> entry = it.next(); result.put(entry.getKey(), entry.getValue()); } return result; }
Source:
<code>private void readVersion() { final String command = fScriptCommand.get(0); final List<String> commandLine = ImmutableList.<@NonNull String> builder() .add(command).add(MI_VERSION_FLAG).build(); final String output = getOutputFromCommand(commandLine); if (output == null) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_NO_MI_VERSION, "No specific or invalid MI version", command); return; } final String versionString = output.trim(); if (!versionString.matches("\\d{1,3}\\.\\d{1,3}")) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_NO_MI_VERSION, "command", command, "version", versionString); return; } TraceCompassLogUtils.traceInstant(LOGGER, <START> Level.INFO, LOG_VERSION, <END> "command", command, "version", versionString); final String[] parts = versionString.split("\\."); final int major = Integer.valueOf(parts[0]); final int minor = Integer.valueOf(parts[1]); fMiVersion = major * 100 + minor; }</code><technical_language>Fine? worked, need this, right</technical_language>

Target:
private void readVersion() { final String command = fScriptCommand.get(0); final List<String> commandLine = ImmutableList.<@NonNull String> builder() .add(command).add(MI_VERSION_FLAG).build(); final String output = getOutputFromCommand(commandLine); if (output == null) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_NO_MI_VERSION, INVALID_MI_VERSION, command); return; } final String versionString = output.trim(); if (!versionString.matches("\\d{1,3}\\.\\d{1,3}")) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_NO_MI_VERSION, COMMAND, command, VERSION, versionString); return; } TraceCompassLogUtils.traceInstant(LOGGER, Level.FINE, LOG_VERSION, COMMAND, command, VERSION, versionString); final String[] parts = versionString.split("\\."); final int major = Integer.valueOf(parts[0]); final int minor = Integer.valueOf(parts[1]); fMiVersion = major * 100 + minor; }
Source:
<code>public void testWhitelistedCapabilities_noWhitelist() throws Exception { final Job job = Job.newBuilder() .setName("foo") .setVersion("1") .setImage("foobar") .setAddedCapabilities(ImmutableSet.of("cap1", "cap2")) .build(); <START> assertEquals(1, validator.validate(job).size()); <END> }</code><technical_language>extra careful set math, want test capability deemed allowed</technical_language>

Target:
public void testWhitelistedCapabilities_noWhitelist() throws Exception { final Job job = Job.newBuilder() .setName("foo") .setVersion("1") .setImage("foobar") .setAddCapabilities(ImmutableSet.of("cap1", "cap2")) .build(); assertEquals(1, validator.validate(job).size()); }
Source:
<code><START> public synchronized int draw(GC gc, long nanosec, Rectangle rect) { <END> String stime; synchronized (formats) { stime = MONTH_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); }</code><technical_language>added synchronized method here, wanted</technical_language>

Target:
public int draw(GC gc, long nanosec, Rectangle rect) { String stime; synchronized (MONTH_FORMAT) { stime = MONTH_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); }
Source:
<code>private static void setupHelixClusterIfNeeded(String helixClusterName, String zkPath) { HelixAdmin admin = new ZKHelixAdmin(zkPath); if (admin.getClusters().contains(helixClusterName)) { LOGGER.info("Helix cluster: already exists", helixClusterName); } else { LOGGER.info("Creating a new Helix cluster: {}", helixClusterName); admin.addCluster(helixClusterName, false); HelixConfigScope configScope = new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER).forCluster(helixClusterName).build(); Map<String, String> configMap = new HashMap<>(); configMap.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, Boolean.toString(true)); configMap.put(ENABLE_CASE_INSENSITIVE_KEY, Boolean.toString(false)); configMap.put(DEFAULT_HYPERLOGLOG_LOG2M_KEY, Integer.toString(DEFAULT_HYPERLOGLOG_LOG2M)); configMap.put(CommonConstants.Broker.CONFIG_OF_ENABLE_QUERY_LIMIT_OVERRIDE, Boolean.toString(false)); admin.setConfig(configScope, configMap); <START> admin.close(); <END> LOGGER.info("New Helix cluster: created", helixClusterName); } }</code><technical_language>need close in cases? (Move out of else block)</technical_language>

Target:
private static void setupHelixClusterIfNeeded(String helixClusterName, String zkPath) { HelixAdmin admin = null; try { admin = new ZKHelixAdmin(zkPath); if (admin.getClusters().contains(helixClusterName)) { LOGGER.info("Helix cluster: already exists", helixClusterName); } else { LOGGER.info("Creating a new Helix cluster: {}", helixClusterName); admin.addCluster(helixClusterName, false); HelixConfigScope configScope = new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER).forCluster(helixClusterName).build(); Map<String, String> configMap = new HashMap<>(); configMap.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, Boolean.toString(true)); configMap.put(ENABLE_CASE_INSENSITIVE_KEY, Boolean.toString(false)); configMap.put(DEFAULT_HYPERLOGLOG_LOG2M_KEY, Integer.toString(DEFAULT_HYPERLOGLOG_LOG2M)); configMap.put(CommonConstants.Broker.CONFIG_OF_ENABLE_QUERY_LIMIT_OVERRIDE, Boolean.toString(false)); admin.setConfig(configScope, configMap); LOGGER.info("New Helix cluster: created", helixClusterName); } } finally { if (admin != null) { admin.close(); } } }
Source:
<code>public void setBuildSource(IBuildSource source){ switch(source.getType()) { <START> case BuildSourceType.Git: <END> if(!(source instanceof IGitBuildSource)) { throw new IllegalArgumentException("IBuildSource of type Git does not implement IGitBuildSource"); } IGitBuildSource git = (IGitBuildSource) source; set(BUILDCONFIG_SOURCE_REF, git.getRef()); break; } set(BUILDCONFIG_SOURCE_URI, source.getURI()); set(BUILDCONFIG_SOURCE_TYPE, source.getType().toString()); }</code><technical_language>missed constants? others</technical_language>

Target:
public void setBuildSource(IBuildSource source){ switch(source.getType()) { case BuildSourceType.GIT: if(!(source instanceof IGitBuildSource)) { throw new IllegalArgumentException("IBuildSource of type Git does not implement IGitBuildSource"); } IGitBuildSource git = (IGitBuildSource) source; set(BUILDCONFIG_SOURCE_REF, git.getRef()); break; } set(BUILDCONFIG_SOURCE_URI, source.getURI()); set(BUILDCONFIG_SOURCE_TYPE, source.getType().toString()); }
Source:
<code>public void setInputs( final Map<String, Object> inputs ) { if ( inputs == null ) { this.inputs = Collections.emptyMap(); return; } this.inputs = inputs; if ( inputs.containsKey( OUTPUT_TYPE ) ) { setOutputType( String.valueOf( inputs.get( OUTPUT_TYPE ) ) ); } if ( inputs.containsKey( OUTPUT_TARGET ) ) { setOutputTarget( String.valueOf( inputs.get( OUTPUT_TARGET ) ) ); } if ( inputs.containsKey( REPORT_DEFINITION_INPUT ) ) { setReportDefinitionInputStream( (InputStream) inputs.get( REPORT_DEFINITION_INPUT ) ); } if ( inputs.containsKey( PAGINATE_OUTPUT ) ) { paginateOutput = "true".equals( String.valueOf( inputs.get( PAGINATE_OUTPUT ) ) ); } if ( inputs.containsKey( ACCEPTED_PAGE ) ) { acceptedPage = ParserUtil.parseInt( String.valueOf( inputs.get( ACCEPTED_PAGE ) ), -1 ); } if ( inputs.containsKey( PRINT ) ) { print = "true".equals( String.valueOf( inputs.get( PRINT ) ) ); } if ( inputs.containsKey( PRINTER_NAME ) ) { printer = String.valueOf( inputs.get( PRINTER_NAME ) ); } if ( inputs.containsKey( DASHBOARD_MODE ) ) { dashboardMode = "true".equals( String.valueOf( inputs.get( DASHBOARD_MODE ) ) ); } if ( inputs.containsKey( QUERY_LIMIT ) ) { try { <START> if ( this.getReport() != null && inputs.get( QUERY_LIMIT ) != null ) { <END> this.getReport().setQueryLimit( Integer.parseInt( (String) inputs.get( QUERY_LIMIT ) ) ); } } catch ( Exception e ) { log.warn( e.getMessage(), e ); } } }</code><technical_language>getReport() returns null. If report-object is set, try parse of other properties, if fails, throw ResourceException</technical_language>

Target:
public void setInputs( final Map<String, Object> inputs ) { if ( inputs == null ) { this.inputs = Collections.emptyMap(); return; } this.inputs = inputs; if ( inputs.containsKey( OUTPUT_TYPE ) ) { setOutputType( String.valueOf( inputs.get( OUTPUT_TYPE ) ) ); } if ( inputs.containsKey( OUTPUT_TARGET ) ) { setOutputTarget( String.valueOf( inputs.get( OUTPUT_TARGET ) ) ); } if ( inputs.containsKey( REPORT_DEFINITION_INPUT ) ) { setReportDefinitionInputStream( (InputStream) inputs.get( REPORT_DEFINITION_INPUT ) ); } if ( inputs.containsKey( PAGINATE_OUTPUT ) ) { paginateOutput = "true".equals( String.valueOf( inputs.get( PAGINATE_OUTPUT ) ) ); } if ( inputs.containsKey( ACCEPTED_PAGE ) ) { acceptedPage = ParserUtil.parseInt( String.valueOf( inputs.get( ACCEPTED_PAGE ) ), -1 ); } if ( inputs.containsKey( PRINT ) ) { print = "true".equals( String.valueOf( inputs.get( PRINT ) ) ); } if ( inputs.containsKey( PRINTER_NAME ) ) { printer = String.valueOf( inputs.get( PRINTER_NAME ) ); } if ( inputs.containsKey( DASHBOARD_MODE ) ) { dashboardMode = "true".equals( String.valueOf( inputs.get( DASHBOARD_MODE ) ) ); } if ( inputs.containsKey( ParameterXmlContentHandler.SYS_PARAM_QUERY_LIMIT ) ) { try { if ( inputs.get( ParameterXmlContentHandler.SYS_PARAM_QUERY_LIMIT ) != null ) { this.getReport().setQueryLimit( checkAndGetUserInputQueryLimit( inputs.get( ParameterXmlContentHandler.SYS_PARAM_QUERY_LIMIT ), this.getReport().getQueryLimit() ) ); } } catch ( Exception e ) { log.warn( e.getMessage(), e ); } } }
Source:
<code>private Requester initRequesterForResponsesWithTimeout(int numberOfResponses) throws Exception { RequestOptions requestOptionsMock = mock(RequestOptions.class); MessageTemplate messageTemplateMock = mock(MessageTemplate.class); when(requestOptionsMock.getMessageTemplate()).thenReturn(messageTemplateMock); when(requestOptionsMock.getWaitForResponses()).thenReturn(numberOfResponses); when(requestOptionsMock.isWaitForResponses()).thenReturn(numberOfResponses > 0 ? true : false); when(requestOptionsMock.getResponseTimeout()).thenReturn(100); when(channelManagerMock.findOrCreateProducer(anyString())).thenReturn(producerMock); MsbContext msbContext = TestUtils.createSimpleMsbContext(); <START> msbContext = TestUtils.createMsbContext(msbContext.getMsbConfig(), msbContext.getMessageFactory(), <END> channelManagerMock, msbContext.getClock(), msbContext.getTimeoutManager()); Requester requester = spy(Requester.create("test:requester", requestOptionsMock, null, msbContext)); collectorMock = spy(new Collector(requestOptionsMock, msbContext, eventHandlerMock)); doReturn(collectorMock) .when(requester) .createCollector(any(RequestOptions.class), any(MsbContext.class), any(EventHandlers.class)); return requester; }</code><technical_language>tricky. provide easier channel manager instance</technical_language>

Target:
private Requester initRequesterForResponsesWithTimeout(int numberOfResponses) throws Exception { RequestOptions requestOptionsMock = mock(RequestOptions.class); MessageTemplate messageTemplateMock = mock(MessageTemplate.class); when(requestOptionsMock.getMessageTemplate()).thenReturn(messageTemplateMock); when(requestOptionsMock.getWaitForResponses()).thenReturn(numberOfResponses); when(requestOptionsMock.isWaitForResponses()).thenReturn(numberOfResponses > 0 ? true : false); when(requestOptionsMock.getResponseTimeout()).thenReturn(100); when(channelManagerMock.findOrCreateProducer(anyString())).thenReturn(producerMock); MsbContext msbContext = TestUtils.createMsbContextBuilder() .withChannelManager(channelManagerMock) .build(); Requester requester = spy(Requester.create("test:requester", requestOptionsMock, null, msbContext)); collectorMock = spy(new Collector(requestOptionsMock, msbContext, eventHandlerMock)); doReturn(collectorMock) .when(requester) .createCollector(any(RequestOptions.class), any(MsbContext.class), any(EventHandlers.class)); return requester; }
Source:
<code><START> static ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("ContainerPlacementModule", new Version(1, 0, 0, "")); module.addSerializer(ContainerPlacementMessage.class, new ContainerPlacementMessageObjectMapper.ContainerPlacementMessageSerializer()); module.addDeserializer(ContainerPlacementMessage.class, new ContainerPlacementMessageObjectMapper.ContainerPlacementMessageDeserializer()); objectMapper.registerModule(module); objectMapper.registerSubtypes(new NamedType(ContainerPlacementResponseMessage.class)); objectMapper.registerSubtypes(new NamedType(ContainerPlacementRequestMessage.class)); return objectMapper; } <END></code><technical_language>a static ObjectMapper? is thread safe changing configuration either</technical_language>

Target:
static ObjectMapper getObjectMapper() { if (objectMapper == null) { objectMapper = createObjectMapper(); } return objectMapper; }
Source:
<code>private InputStream runOcrAndGetOutputStream(AbstractFile file) throws ExtractionException { File inputFile = null; File outputFile = null; try { String localDiskPath = Case.getCurrentCaseThrows().getTempDirectory() <START> + File.separator + file.getId() + file.getName(); <END> inputFile = new File(localDiskPath); ContentUtils.writeToFile(content, inputFile); ProcessBuilder process = new ProcessBuilder(); String outputFilePath = Case.getCurrentCaseThrows().getTempDirectory() + File.separator + file.getId() + "output"; String executeablePath = TESSERACT_PATH.toString(); process.command(executeablePath, String.format("\"%s\"", inputFile.getAbsolutePath()), String.format("\"%s\"", outputFilePath), "-l", LANGUAGE_PACKS); if (processTerminator != null) { ExecUtil.execute(process, 1, TimeUnit.SECONDS, processTerminator); } else { ExecUtil.execute(process); } outputFile = new File(outputFilePath + ".txt"); return new CleanUpStream(outputFile); } catch (NoCurrentCaseException | IOException ex) { if (outputFile != null) { outputFile.delete(); } throw new ExtractionException("Could not successfully run Tesseract", ex); } finally { if (inputFile != null) { inputFile.delete(); } } }</code><technical_language>Paths construct paths avoid messiness of path component concatenation File.separator</technical_language>

Target:
private InputStream runOcrAndGetOutputStream(AbstractFile file) throws ExtractionException { File inputFile = null; File outputFile = null; try { String tempFileName = file.getId() + file.getName(); inputFile = Paths.get(Case.getCurrentCaseThrows().getTempDirectory(), tempFileName).toFile(); ContentUtils.writeToFile(content, inputFile); String tempOutputName = file.getId() + TESSERACT_OUTPUT_FILE_NAME; String outputFilePath = Paths.get(Case.getCurrentCaseThrows().getTempDirectory(), tempOutputName).toString(); String executeablePath = TESSERACT_PATH.toString(); ProcessBuilder process = new ProcessBuilder(); process.command(executeablePath, String.format("\"%s\"", inputFile.getAbsolutePath()), String.format("\"%s\"", outputFilePath), "-l", LANGUAGE_PACKS); if (processTerminator != null) { ExecUtil.execute(process, 1, TimeUnit.SECONDS, processTerminator); } else { ExecUtil.execute(process); } outputFile = new File(outputFilePath + ".txt"); return new CleanUpStream(outputFile); } catch (NoCurrentCaseException | IOException ex) { if (outputFile != null) { outputFile.delete(); } throw new ExtractionException("Could not successfully run Tesseract", ex); } finally { if (inputFile != null) { inputFile.delete(); } } }
Source:
<code>public static double theoreticalSensitivity(final Histogram<Integer> depthHistogram, final Histogram<Integer> qualityHistogram, final int sampleSize, final double logOddsThreshold, final double alleleFraction) { if (alleleFraction > 1.0 || alleleFraction < 0.0) { throw new PicardException("Allele fractions must be between 0 and 1."); } final double[] depthDistribution = normalizeHistogram(depthHistogram); double sensitivity = 0.0; <START> int k = 0; <END> double right = sensitivityAtConstantDepth(k, qualityHistogram, logOddsThreshold, sampleSize, alleleFraction); while (k < depthDistribution.length) { double width = 0.0; while (width < DEPTH_BIN_WIDTH && k < depthDistribution.length) { width += depthDistribution[k]; k++; } double left = right; right = sensitivityAtConstantDepth(k, qualityHistogram, logOddsThreshold, sampleSize, alleleFraction); sensitivity += width * (left + right) / 2.0; } return sensitivity; }</code><technical_language>give a name please</technical_language>

Target:
public static double theoreticalSensitivity(final Histogram<Integer> depthHistogram, final Histogram<Integer> qualityHistogram, final int sampleSize, final double logOddsThreshold, final double alleleFraction) { if (alleleFraction > 1.0 || alleleFraction < 0.0) { throw new IllegalArgumentException("Allele fractions must be between 0 and 1."); } final double[] depthDistribution = normalizeHistogram(depthHistogram); double sensitivity = 0.0; int currentDepth = 0; double right = 0; while (currentDepth < depthDistribution.length) { double deltaDepthProbability = 0.0; while (deltaDepthProbability == 0 && currentDepth < depthDistribution.length || deltaDepthProbability < DEPTH_BIN_WIDTH && currentDepth < depthDistribution.length && depthDistribution[currentDepth] < DEPTH_BIN_WIDTH / 2.0) { deltaDepthProbability += depthDistribution[currentDepth]; currentDepth++; } final double left = right; right = sensitivityAtConstantDepth(currentDepth, qualityHistogram, logOddsThreshold, sampleSize, alleleFraction); sensitivity += deltaDepthProbability * (left + right) / 2.0; } return sensitivity; }
Source:
<code>public void putAll(Map<K, V> entries) { if (trace) log.tracef("PUT_ALL cache=%s keys=%s", noReturn.getName(), entries); if (preferAsync) { <START> noReturn.putAllAsync(entries); <END> } else { noReturn.putAll(entries); } }</code><technical_language>Incorrect, this call noReturn.putAsync in a loop (and wait for futures), do operation asynchronously</technical_language>

Target:
public void putAll(Map<K, V> entries) { if (trace) log.tracef("PUT_ALL cache=%s keys=%s", noReturn.getName(), entries); if (preferAsync) { Map<K, Future<V>> futures = new HashMap<K, Future<V>>(entries.size()); for (Map.Entry<K, V> entry : entries.entrySet()) { futures.put(entry.getKey(), noReturn.putAsync(entry.getKey(), entry.getValue())); } for (Map.Entry<K, Future<V>> entry : futures.entrySet()) { try { entry.getValue().get(); } catch (Exception e) { throw new RuntimeException(e); } } } else { noReturn.putAll(entries); } }
Source:
<code>public static List<CancerGene> getCancerGeneList() { List<CancerGene> CancerGeneList = new ArrayList<CancerGene>(); try { List<String> lines = FileUtils.readTrimedLinesStream( CancerGeneUtils.class.getResourceAsStream(CANCER_GENE_FILE_PATH)); Iterator itr = lines.iterator(); itr.next(); while(itr.hasNext()) { String[] line = itr.next().toString().split("\t"); if (line.length != 10) continue; CancerGene item = new CancerGene(); item.setHugoSymbol(line[0]); item.setEntrezGeneId(line[1]); <START> item.setOncokbAnnotated(line[2].trim().equals("1") ? true : false); <END> item.setOccurrenceCount(MainUtils.isInteger(line[3].trim()) ? Integer.parseInt(line[3].trim()) : 0); item.setMSKImpact(line[4].trim().equals("1") ? true : false); item.setMSKHeme(line[5].trim().equals("1") ? true : false); item.setFoundation(line[6].trim().equals("1") ? true : false); item.setFoundationHeme(line[7].trim().equals("1") ? true : false); item.setVogelstein(line[8].trim().equals("1") ? true : false); item.setSangerCGC(line[9].trim().equals("1") ? true : false); CancerGeneList.add(item); } } catch (IOException e) { e.printStackTrace(); } return CancerGeneList; }</code><technical_language>This item.setOncokbAnnotated(line[2].trim().equals("1")); Similar other items</technical_language>

Target:
public static List<CancerGene> getCancerGeneList() { List<CancerGene> CancerGeneList = new ArrayList<CancerGene>(); try { List<String> lines = FileUtils.readTrimedLinesStream( CancerGeneUtils.class.getResourceAsStream(CANCER_GENE_FILE_PATH)); Iterator itr = lines.iterator(); itr.next(); while(itr.hasNext()) { String[] line = itr.next().toString().split("\t"); if (line.length != 10) continue; CancerGene item = new CancerGene(); item.setHugoSymbol(line[0]); item.setEntrezGeneId(line[1]); item.setOncokbAnnotated(line[2].trim().equals("1")); item.setOccurrenceCount(NumberUtils.isNumber(line[3].trim()) ? Integer.parseInt(line[3].trim()) : 0); item.setmSKImpact(line[4].trim().equals("1")); item.setmSKHeme(line[5].trim().equals("1")); item.setFoundation(line[6].trim().equals("1")); item.setFoundationHeme(line[7].trim().equals("1")); item.setVogelstein(line[8].trim().equals("1")); item.setSangerCGC(line[9].trim().equals("1")); CancerGeneList.add(item); } } catch (IOException e) { e.printStackTrace(); } return CancerGeneList; }
Source:
<code>private boolean isMatchmakerPartyMessage(String channelName) { <START> return channelName.endsWith("'sParty"); <END> }</code><technical_language>good this a constant referencing easier</technical_language>

Target:
private boolean isMatchmakerPartyMessage(String channelName) { return channelName.endsWith(PARTY_CHANNEL_SUFFIX); }
Source:
<code>public void testRecoveryMonitorWithSuccess() throws Exception { XAResource dummy = new XAResource() { @Override public void commit(Xid xid, boolean b) throws XAException { } @Override public void end(Xid xid, int i) throws XAException { } @Override public void forget(Xid xid) throws XAException { } @Override public int getTransactionTimeout() throws XAException { return 0; } @Override public boolean isSameRM(XAResource xaResource) throws XAException { return false; } @Override public int prepare(Xid xid) throws XAException { return 0; } @Override public Xid[] recover(int i) throws XAException { return new Xid[0]; } @Override public void rollback(Xid xid) throws XAException { } @Override public boolean setTransactionTimeout(int i) throws XAException { return false; } @Override public void start(Xid xid, int i) throws XAException { } }; XATestResourceXARecovery.setUseFaultyResources(false); UserTransaction ut = com.arjuna.ats.jta.UserTransaction.userTransaction(); ut.begin(); TransactionImple tx = TransactionImple.getTransaction(); assertTrue(tx.enlistResource(dummy)); assertTrue(tx.enlistResource(dummy)); ut.commit(); manager.scan(); <START> assertFalse(!xaRecoveryModule.isPeriodicWorkSuccessful()); <END> }</code><technical_language>assertTrue avoids double negative</technical_language>

Target:
public void testRecoveryMonitorWithSuccess() throws Exception { XAResource dummy = new XAResource() { @Override public void commit(Xid xid, boolean b) throws XAException { } @Override public void end(Xid xid, int i) throws XAException { } @Override public void forget(Xid xid) throws XAException { } @Override public int getTransactionTimeout() throws XAException { return 0; } @Override public boolean isSameRM(XAResource xaResource) throws XAException { return false; } @Override public int prepare(Xid xid) throws XAException { return 0; } @Override public Xid[] recover(int i) throws XAException { return new Xid[0]; } @Override public void rollback(Xid xid) throws XAException { } @Override public boolean setTransactionTimeout(int i) throws XAException { return false; } @Override public void start(Xid xid, int i) throws XAException { } }; XATestResourceXARecovery.setUseFaultyResources(false); UserTransaction ut = com.arjuna.ats.jta.UserTransaction.userTransaction(); ut.begin(); TransactionImple tx = TransactionImple.getTransaction(); assertTrue(tx.enlistResource(dummy)); assertTrue(tx.enlistResource(dummy)); ut.commit(); manager.scan(); assertTrue(xaRecoveryModule.isPeriodicWorkSuccessful()); }
Source:
<code><START> private ResultScanner<Row> readRows( <END> ReadRowsRequest request, boolean retriable, boolean resumable) { if (retriable) { return new RetryingStreamingResultScanner( retryOptions, request, new BigtableResultScannerFactory() { @Override public ResultScanner<Row> createScanner(ReadRowsRequest request) { return readRows(request, false, false); } }); } if (resumable) { return new ResumingBigtableResultScanner(request, new BigtableResultScannerFactory() { @Override public ResultScanner<Row> createScanner(ReadRowsRequest request) { return readRows(request, false, false); } }); } final Call<ReadRowsRequest, ReadRowsResponse> readRowsCall = channel.newCall(BigtableServiceGrpc.CONFIG.readRows); CancellationToken cancellationToken = new CancellationToken(); cancellationToken.addListener(new Runnable() { @Override public void run() { readRowsCall.cancel(); } }, executorService); StreamingBigtableResultScanner resultScanner = new StreamingBigtableResultScanner( retryOptions.getStreamingBufferSize(), retryOptions.getReadPartialRowTimeoutMillis(), cancellationToken); Calls.asyncServerStreamingCall( readRowsCall, request, new ReadRowsStreamObserver(resultScanner, readRowsCall)); return resultScanner; }</code><technical_language>a fan of this method. 2 instead of a single thing, 3. this broken methods add</technical_language>

Target:
private ResultScanner<Row> readRows( ReadRowsRequest request, boolean retriable, boolean resumable) { if (retriable) { return new RetryingStreamingResultScanner(retryOptions, request, streamingScannerFactory); } if (resumable) { return new ResumingBigtableResultScanner(request, streamingScannerFactory); } return createStreamingScanner(request); }
Source:
<code>public void testDuplicateQueuedFlows() throws ExecutorManagerException, IOException { try { ExecutorManager manager = createMultiExecutorManagerInstance(); ExecutableFlow flow1 = createExecutableFlow("exec1"); flow1.getExecutionOptions().setConcurrentOption( ExecutionOptions.CONCURRENT_OPTION_SKIP); User testUser = getTestUser(); manager.submitExecutableFlow(flow1, testUser.getUserId()); manager.submitExecutableFlow(flow1, testUser.getUserId()); manager.enableQueueProcessorThread(); <START> manager.submitExecutableFlow(flow1, testUser.getUserId()); <END> Assert.fail("Expecting exception, but didn't get one"); } catch (ExecutorManagerException ex) { System.out.println("Test true"); } }</code><technical_language>Is this submit necessary</technical_language>

Target:
public void testDuplicateQueuedFlows() throws ExecutorManagerException, IOException { ExecutorManager manager = createMultiExecutorManagerInstance(); ExecutableFlow flow1 = TestUtils.createExecutableFlow("exectest1", "exec1"); flow1.getExecutionOptions().setConcurrentOption( ExecutionOptions.CONCURRENT_OPTION_SKIP); User testUser = TestUtils.getTestUser(); manager.submitExecutableFlow(flow1, testUser.getUserId()); manager.submitExecutableFlow(flow1, testUser.getUserId()); }
Source:
<code>public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException { Moh361BCohortDefinition definition = (Moh361BCohortDefinition) cohortDefinition; if (definition == null) return null; String reportDate = sdf.format(context.getEvaluationDate()); String sql = "select person_id" + " from amrsreports_hiv_care_enrollment " + " where " + " first_arv_date is not NULL" + " enrollment_date is not NULL" + <START> " and enrollment_date <= ':reportDate'" + <END> " and enrollment_location_id in ( :locationList )"; List<Location> locationList = (List<Location>) context.getParameterValue("locationList"); sql.replaceAll(":locationList",locationList.toString()); SqlCohortDefinition sqlCohortDefinition = new SqlCohortDefinition(sql.replaceAll(":reportDate", reportDate)); Cohort results = Context.getService(CohortDefinitionService.class).evaluate(sqlCohortDefinition, context); return new EvaluatedCohort(results, sqlCohortDefinition, context); }</code><technical_language>change this first_arv_date</technical_language>

Target:
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException { Moh361BCohortDefinition definition = (Moh361BCohortDefinition) cohortDefinition; if (definition == null) return null; String reportDate = sdf.format(context.getEvaluationDate()); List<Location> locationList = (List<Location>) context.getParameterValue("locationList"); String sql = "select person_id" + " from amrsreports_hiv_care_enrollment " + " where " + " first_arv_date is not NULL" + " and enrollment_date is not NULL" + " and first_arv_date <= ':reportDate'" + " and first_arv_location_id in ( :locationList )"; SqlCohortDefinition sqlCohortDefinition = new SqlCohortDefinition(sql.replaceAll(":reportDate", reportDate)); Cohort results = Context.getService(CohortDefinitionService.class).evaluate(sqlCohortDefinition, context); return new EvaluatedCohort(results, sqlCohortDefinition, context); }
Source:
<code>public static RandomPasswordEntropy createEntropy(final List<Rule> passwordRules, final PasswordData passwordData) { <START> final Set<Character> uniqueCharacters = new HashSet<>(); <END> passwordRules.stream().forEach((rule) -> { if (rule instanceof CharacterCharacteristicsRule) { final CharacterCharacteristicsRule characteristicRule = (CharacterCharacteristicsRule) rule; characteristicRule.getRules().forEach((characterRule) -> uniqueCharacters.addAll(getUniqueCharacters(characterRule.getValidCharacters()))); } else if (rule instanceof AllowedCharacterRule) { final AllowedCharacterRule allowedCharacterRule = (AllowedCharacterRule) rule; uniqueCharacters.addAll(getUniqueCharacters(String.valueOf(allowedCharacterRule.getAllowedCharacters()))); } }); if (uniqueCharacters.isEmpty()) { throw new IllegalArgumentException( "Password rules must contain at least 1 unique character by CharacterRule definition"); } return new RandomPasswordEntropy(uniqueCharacters.size(), passwordData.getPassword().length()); }</code><technical_language>simply a counter here? need actual characters rule determine alphabet size. character sets overlap top of head, more efficient</technical_language>

Target:
public static RandomPasswordEntropy createEntropy(final List<Rule> passwordRules, final PasswordData passwordData) { if (!passwordData.getOrigin().equals(PasswordData.Origin.Generated)) { throw new IllegalArgumentException("Password data must have an origin of " + PasswordData.Origin.Generated); } final Set<Character> uniqueCharacters = new HashSet<>(); passwordRules.stream().forEach((rule) -> { if (rule instanceof CharacterCharacteristicsRule) { final CharacterCharacteristicsRule characteristicRule = (CharacterCharacteristicsRule) rule; characteristicRule.getRules().forEach((characterRule) -> uniqueCharacters.addAll(getUniqueCharacters(characterRule.getValidCharacters()))); } else if (rule instanceof CharacterRule) { final CharacterRule characterRule = (CharacterRule) rule; uniqueCharacters.addAll(getUniqueCharacters(characterRule.getValidCharacters())); } else if (rule instanceof AllowedCharacterRule) { final AllowedCharacterRule allowedCharacterRule = (AllowedCharacterRule) rule; uniqueCharacters.addAll(getUniqueCharacters(String.valueOf(allowedCharacterRule.getAllowedCharacters()))); } }); if (uniqueCharacters.isEmpty()) { throw new IllegalArgumentException( "Password rules must contain at least 1 unique character by CharacterRule definition"); } return new RandomPasswordEntropy(uniqueCharacters.size(), passwordData.getPassword().length()); }
Source:
<code>public static ArrayList<String> readCSVFile(MultipartFile file) throws IOException { BufferedReader reader; ArrayList<String> subjectKeyList = new ArrayList<>(); String line; InputStream is = file.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING).withFirstRecordAsHeader().withTrim(); CSVParser csvParser = new CSVParser(reader, csvFileFormat); Iterable<CSVRecord> csvRecords = csvParser.getRecords(); for (CSVRecord csvRecord : csvRecords) { String participantID = csvRecord.get("ParticipantID"); <START> if (participantID != null && !(participantID.isEmpty())) { <END> subjectKeyList.add(participantID); } } return subjectKeyList; }</code><technical_language>StringUtils.isNotEmpty(participantID) instead</technical_language>

Target:
public static ArrayList<String> readCSVFile(MultipartFile file) throws IOException { ArrayList<String> subjectKeyList = new ArrayList<>(); try { BufferedReader reader; String line; InputStream is = file.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING).withFirstRecordAsHeader().withTrim(); CSVParser csvParser = new CSVParser(reader, csvFileFormat); for (CSVRecord csvRecord : csvParser) { String participantID = csvRecord.get("ParticipantID"); if (StringUtils.isNotEmpty(participantID)) { subjectKeyList.add(participantID); } } }catch (Exception e) { log.error("Exception with cause = {}", e.getCause(), e.getMessage()); } return subjectKeyList; }
Source:
<code>String getKeyAsString() { if (key == null || key.getAsString().equals("")) { <START> logger.warn("Found user with null/empty key: " + toString()); <END> return ""; } else { return key.getAsString(); } }</code><technical_language>I this log message more sense in ctor here. users immutable want this logged a malformed user is created, time access key</technical_language>

Target:
String getKeyAsString() { if (key == null) { return ""; } else { return key.getAsString(); } }
Source:
<code>public int weigh(EntryKey k, Boolean v) { return 16 + 2 * (16 + 20) + 8 + 8 + <START> 2 * k.mergeStrategy.length() <END> + 1; }</code><technical_language>static strings held reused? charge for weight of merge strategy string. Actual memory entry is pointer sized string length</technical_language>

Target:
public int weigh(EntryKey k, Boolean v) { return 16 + 2 * (16 + 20) + 4 * 8 + 1; }
Source:
<code>public void testCompletingCheckoutWithNullPaymentToken() throws InterruptedException { <START> final CountDownLatch latch = new CountDownLatch(1); <END> try { buyClient.completeCheckout(null, checkout.getToken()); } catch (NullPointerException e) { latch.countDown(); return; } latch.await(); fail("Expected an NullPointerException"); }</code><technical_language>^^^</technical_language>

Target:
public void testCompletingCheckoutWithNullPaymentToken() throws InterruptedException { try { buyClient.completeCheckout(null, checkout.getToken()); } catch (NullPointerException e) { return; } fail("Expected an NullPointerException"); }
Source:
<code>public void getsAllBatchStatuses_whenServiceAlreadyExists() { downloadManager.initialise(mock(DownloadService.class)); downloadManager.getAllDownloadBatchStatuses(allBatchStatusesCallback); <START> assertThat(downloadBatchStatuses).containsAllOf(BATCH_STATUS, ADDITIONAL_BATCH_STATUS); <END> }</code><technical_language>containsOnly, more specific</technical_language>

Target:
public void getsAllBatchStatuses_whenServiceAlreadyExists() { downloadManager.initialise(mock(DownloadService.class)); downloadManager.getAllDownloadBatchStatuses(allBatchStatusesCallback); assertThat(downloadBatchStatuses).containsExactly(BATCH_STATUS, ADDITIONAL_BATCH_STATUS); }
Source:
<code>protected void onMethodInvocationFound(MethodInvocationTree mit) { ExpressionTree expressionToEvaluate = mit.arguments().get(1); if (expressionToEvaluate.is(Tree.Kind.IDENTIFIER)) { Symbol variable = ((IdentifierTree) expressionToEvaluate).symbol(); ExpressionTree lastAssignmentOrDeclaration = ReassignmentFinder.getClosestReassignmentOrDeclarationExpression(mit, variable); if (lastAssignmentOrDeclaration != null && !usedBetween(variable, lastAssignmentOrDeclaration, mit)) { expressionToEvaluate = lastAssignmentOrDeclaration; } } if (isRequestOrCookieDataRetrieval(expressionToEvaluate)) { <START> addIssue(mit, "Make sure the user is authenticated before this data is stored in the session."); <END> } }</code><technical_language>@m-g-sonar try new api: reportIssue(mit.methodSelect(), "Make user is authenticated this data is stored in session.");</technical_language>

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { for (ExpressionTree argument : mit.arguments()) { checkArgument(argument, mit, mit); } }
Source:
<code>public void getAllCandidateShouldCallRepositoryWithAscendingSortWhenPassingAscendingFilterRequest() { Sort ascendingSort = new Sort(Sort.Direction.ASC, SORT_FIELD); Collection<CandidateDTO> result = candidateService.getAllCandidate(ascendingFilterRequest); ArgumentCaptor<String> nameArgumentCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> emailArgumentCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> phoneArgumentCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Sort> sortArgumentCaptor = ArgumentCaptor.forClass(Sort.class); <START> verify(candidateRepository).findAllCandidatesByFilterRequest( <END> nameArgumentCaptor.capture(), emailArgumentCaptor.capture(), phoneArgumentCaptor.capture(), sortArgumentCaptor.capture()); assertThat(nameArgumentCaptor.getValue(), equalTo(NAME)); assertThat(emailArgumentCaptor.getValue(), equalTo(EMAIL)); assertThat(phoneArgumentCaptor.getValue(), equalTo(PHONE)); assertThat(sortArgumentCaptor.getValue(), equalTo(ascendingSort)); }</code><technical_language>argument captor single line: > verify(candidateRepository).findAllCandidatesByFilterRequest(NAME, EMAIL, PHONE, ascendingSort);</technical_language>

Target:
public void getAllCandidateShouldCallRepositoryWithAscendingSortWhenPassingAscendingFilterRequest() { Collection<CandidateDTO> result = candidateService.getAllCandidate(ascendingFilterRequest); verify(candidateRepository).findAllCandidatesByFilterRequest(NAME, EMAIL, PHONE, ascendingSort); }
Source:
<code>public RegisteredPackage open(@Nonnull PackageId id) throws IOException { try { Node node = getPackageNode(id); if (node == null && baseRegistry != null) { <START> if (baseRegistry.contains(id)) { <END> return baseRegistry.open(id); } } return node == null ? null : new JcrRegisteredPackage(open(node, false)); } catch (RepositoryException e) { throw new IOException(e); } }</code><technical_language>this simplified just: suggestion return baseRegistry.open(id) bring additional check contains() first</technical_language>

Target:
public RegisteredPackage open(@Nonnull PackageId id) throws IOException { try { Node node = getPackageNode(id); if (node == null && baseRegistry != null) { return baseRegistry.open(id); } return node == null ? null : new JcrRegisteredPackage(open(node, false)); } catch (RepositoryException e) { throw new IOException(e); } }
Source:
<code>private Object sortPlugins(List<JSONObject> list) { List<JSONObject> sorted = new ArrayList<>(list); Collections.sort(sorted, new Comparator<JSONObject>() { public int compare(JSONObject j1, JSONObject j2) { return j1.getString("name").compareTo(j2.getString("name")); } <START> ; <END> }); return sorted; }</code><technical_language>NIT: strange formatting glitches</technical_language>

Target:
private Object sortPlugins(List<JSONObject> list) { List<JSONObject> sorted = new ArrayList<>(list); Collections.sort(sorted, new Comparator<JSONObject>() { public int compare(JSONObject j1, JSONObject j2) { return j1.getString("name").compareTo(j2.getString("name")); } }); return sorted; }