auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String escapeShell(String[] args, OS os) { if (os.isPosix) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if (i != 0) sb.append('\''); sb.append(StringUtils.replace(arg, "'", "'\\''")); if (i != 0) sb.append('\''); sb.append(' '); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } else if (os == OS.WIN) { StringBuilder sb = new StringBuilder(); <START> for (int i = 0; i < args.length; i++) { <END> String arg = args[i]; if (i != 0) sb.append('"'); sb.append(StringUtils.replace(StringUtils.replace(arg, "\\", "\\\\"), "\"", "\\\"")); if (i != 0) sb.append('"'); sb.append(' '); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } throw new IllegalArgumentException("unsupported OS"); }</code><technical_language>okay, I problem is here. escaping backslashes in fact windows escape backslashes way. Windows escapes quotes backslash escape backslash. correct solution is escape \ \ escape " \"</technical_language>

Target:
public static String escapeShell(String[] args, OS os) { if (os.isPosix) { StringBuilder sb = new StringBuilder(); for (String arg : args) { sb.append("'"); sb.append(StringUtils.replace(arg, "'", "'\\''")); sb.append("' "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } else if (os == OS.WIN) { StringBuilder sb = new StringBuilder(); for (String arg : args) { sb.append('"'); sb.append(StringUtils.replace(arg, "\"", "\\\"")); sb.append("\" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } throw new IllegalArgumentException("unsupported OS"); }
Source:
<code>protected boolean isThisTheExecutionRoot() { ContextualLog log = new DelegatingContextualLog( getLog() ); log.debug("Root Folder:" + session.getExecutionRootDirectory()); log.debug("Current Folder:"+ basedir ); boolean result = session.getExecutionRootDirectory().equalsIgnoreCase(basedir.toString()); if (result) { log.debug( "This is the execution root." ); } else { log.debug( "This is NOT the execution root." ); <START> } <END> return result; }</code><technical_language>Another option log.debug("This is execution root? " + result) replace lines 532 539</technical_language>

Target:
protected boolean isThisTheExecutionRoot() { ContextualLog log = new DelegatingContextualLog( getLog() ); log.debug("Root Folder:" + session.getExecutionRootDirectory()); log.debug("Current Folder:"+ basedir ); boolean result = session.getExecutionRootDirectory().equalsIgnoreCase(basedir.toString()); log.debug( "This is the execution root?" + result); return result; }
Source:
<code><START> static public boolean isTransition(final VariantContext vc) throws IllegalAccessException { <END> final byte refAllele = vc.getReference().getBases()[0]; final Collection<Allele> altAlleles = vc.getAlternateAlleles(); if(vc.type == VariantContext.Type.NO_VARIATION) { throw new IllegalAccessException("Variant context is monomorphic: " + vc.toString()); } if(vc.type != VariantContext.Type.SNP) { throw new IllegalAccessException("Variant context is not a SNP: " + vc.toString()); } if(altAlleles.size() != 1 ) { throw new IllegalAccessException("Expected exactly 1 alternative Allele. Found: " + altAlleles.size()); } final Byte altAllele = altAlleles.iterator().next().getBases()[0]; return (refAllele == 'A' && altAllele == 'G') || (refAllele == 'G' && altAllele == 'A') || (refAllele == 'C' && altAllele == 'T') || (refAllele == 'T' && altAllele == 'C'); }</code><technical_language>I IllegalArgumentException</technical_language>

Target:
static public boolean isTransition(final VariantContext vc) throws IllegalArgumentException { final byte refAllele = vc.getReference().getBases()[0]; final Collection<Allele> altAlleles = vc.getAlternateAlleles(); if(vc.type == VariantContext.Type.NO_VARIATION) { throw new IllegalArgumentException("Variant context is monomorphic: " + vc.toString()); } if(vc.type != VariantContext.Type.SNP) { throw new IllegalArgumentException("Variant context is not a SNP: " + vc.toString()); } if(altAlleles.size() != 1 ) { throw new IllegalArgumentException("Expected exactly 1 alternative Allele. Found: " + altAlleles.size()); } final Byte altAllele = altAlleles.iterator().next().getBases()[0]; return (refAllele == 'A' && altAllele == 'G') || (refAllele == 'G' && altAllele == 'A') || (refAllele == 'C' && altAllele == 'T') || (refAllele == 'T' && altAllele == 'C'); }
Source:
<code>public Object configureL3(String json) throws Exception { IRoutingService routingService = (IRoutingService) getContext() .getAttributes().get(IRoutingService.class.getCanonicalName()); if (json == null) { setStatus(org.restlet.data.Status.CLIENT_ERROR_BAD_REQUEST, "One or more required fields missing."); return null; } JsonNode jsonNode = new ObjectMapper().readTree(json); JsonNode enableNode = jsonNode.get("enable"); if (enableNode == null) { <START> setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "One or more required fields missing."); <END> return null; } if (enableNode.asBoolean()) { routingService.enableL3Routing(); } else { routingService.disableL3Routing(); } return getL3Config(); }</code><technical_language>crucial, consider returning field is missing</technical_language>

Target:
public Object configureL3(String json) throws Exception { IRoutingService routingService = (IRoutingService) getContext() .getAttributes().get(IRoutingService.class.getCanonicalName()); if (json == null) { setStatus(org.restlet.data.Status.CLIENT_ERROR_BAD_REQUEST, "Field missing to enable/disable L3 routing."); return null; } JsonNode jsonNode = new ObjectMapper().readTree(json); JsonNode enableNode = jsonNode.get("enable"); if (enableNode == null) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "One or more required fields missing."); return null; } if (enableNode.asBoolean()) { routingService.enableL3Routing(); } else { routingService.disableL3Routing(); } return getL3Config(); }
Source:
<code>private LinuxStyle(String label, int red, int green, int blue, int alpha, float heightFactor) { if (label == null) { throw new IllegalArgumentException("Label cannot be null"); } if (red > 255 || red < 0) { throw new IllegalArgumentException("Red needs to be between 0 and 255"); } if (green > 255 || green < 0) { throw new IllegalArgumentException("Green needs to be between 0 and 255"); } if (blue > 255 || blue < 0) { throw new IllegalArgumentException("Blue needs to be between 0 and 255"); } if (alpha > 255 || alpha < 0) { throw new IllegalArgumentException("alpha needs to be between 0 and 255"); } if (heightFactor > 1.0 || heightFactor < 0) { throw new IllegalArgumentException("Height factor needs to be between 0 and 1.0, given hint : " + heightFactor); } fMap = ImmutableMap.of(StyleProperties.STYLE_NAME, label, StyleProperties.BACKGROUND_COLOR, <START> X11ColorUtils.toHexColor(red, <END> green, blue), StyleProperties.HEIGHT, heightFactor, StyleProperties.OPACITY, (float) alpha / 255); }</code><technical_language>ColorUtils</technical_language>

Target:
private LinuxStyle(String label, int red, int green, int blue, int alpha, float heightFactor) { if (label == null) { throw new IllegalArgumentException("Label cannot be null"); } if (red > 255 || red < 0) { throw new IllegalArgumentException("Red needs to be between 0 and 255"); } if (green > 255 || green < 0) { throw new IllegalArgumentException("Green needs to be between 0 and 255"); } if (blue > 255 || blue < 0) { throw new IllegalArgumentException("Blue needs to be between 0 and 255"); } if (alpha > 255 || alpha < 0) { throw new IllegalArgumentException("alpha needs to be between 0 and 255"); } if (heightFactor > 1.0 || heightFactor < 0) { throw new IllegalArgumentException("Height factor needs to be between 0 and 1.0, given hint : " + heightFactor); } fMap = ImmutableMap.of(StyleProperties.STYLE_NAME, label, StyleProperties.BACKGROUND_COLOR, ColorUtils.toHexColor(red, green, blue), StyleProperties.HEIGHT, heightFactor, StyleProperties.OPACITY, (float) alpha / 255); }
Source:
<code>private boolean isBinaryEquivalent(IntegerDeclaration other) { if (fAlignment != other.fAlignment) { return false; } if (fLength != other.fLength) { return false; } if (fSigned != other.fSigned) { return false; } <START> return !(fLength == BYTE_ALIGN) && fByteOrder.equals(other.fByteOrder); <END> }</code><technical_language>This is equivalent</technical_language>

Target:
private boolean isBinaryEquivalent(IntegerDeclaration other) { if (fAlignment != other.fAlignment) { return false; } if (fLength != other.fLength) { return false; } if (fSigned != other.fSigned) { return false; } return !((fLength != BYTE_ALIGN) && !fByteOrder.equals(other.fByteOrder)); }
Source:
<code>private Object clearUserProfile(final Object value) { <START> if(value instanceof LinkedHashMap<?,?>) { <END> final LinkedHashMap<String, CommonProfile> profiles = (LinkedHashMap<String, CommonProfile>) value; profiles.forEach((name, profile) -> profile.clearSensitiveData()); return profiles; } else { final CommonProfile profile = (CommonProfile) value; profile.clearSensitiveData(); return profile; } }</code><technical_language>this Map instead of a LinkedHashMap? thinking if profiles Map impl change underlying interface</technical_language>

Target:
private Object clearUserProfile(final Object value) { if(value instanceof Map<?,?>) { final Map<String, CommonProfile> profiles = (Map<String, CommonProfile>) value; profiles.forEach((name, profile) -> profile.clearSensitiveData()); return profiles; } else { final CommonProfile profile = (CommonProfile) value; profile.clearSensitiveData(); return profile; } }
Source:
<code>public void initialise() { wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new SetViewportToSizeOf(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); update(); addDesiredStateChange(new EnableMaterial(CHUNK_SHADER.toString())); chunkShader = getMaterial(CHUNK_SHADER); <START> displayResolutionDependentFBOs.subscribe(this); <END> }</code><technical_language>move this shader-related lines, is related FBO instead</technical_language>

Target:
public void initialise() { wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new EnableMaterial(CHUNK_SHADER.toString())); chunkShader = getMaterial(CHUNK_SHADER); }
Source:
<code><START> public final void doInit() { <END> this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); if (this.destinationDirectoryExpression instanceof LiteralExpression) { final File directory = new File(this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } if (!this.fileNameGeneratorSet && this.fileNameGenerator instanceof BeanFactoryAware) { ((BeanFactoryAware) this.fileNameGenerator).setBeanFactory(this.getBeanFactory()); } }</code><technical_language>I doInit() implementation stay protected void. for classes allow end-users invoke - afterPropertiesSet(), do in tests now</technical_language>

Target:
protected void doInit() { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); if (this.destinationDirectoryExpression instanceof LiteralExpression) { final File directory = new File(this.destinationDirectoryExpression.getValue( this.evaluationContext, null, String.class)); validateDestinationDirectory(directory, this.autoCreateDirectory); } if (!this.fileNameGeneratorSet && this.fileNameGenerator instanceof BeanFactoryAware) { ((BeanFactoryAware) this.fileNameGenerator).setBeanFactory(this.getBeanFactory()); } }
Source:
<code><START> protected long[] sequentialTimestamps(int count) { <END> return sequentialTimestamps(count, System.currentTimeMillis()); }</code><technical_language>public</technical_language>

Target:
public long[] sequentialTimestamps(int count) { return sequentialTimestamps(count, System.currentTimeMillis()); }
Source:
<code>private void updateExecutableFlow(final ExecutableFlow flow, final EncodingType encType) throws ExecutorManagerException { final String UPDATE_EXECUTABLE_FLOW_DATA = "UPDATE execution_flows " + "SET status=?,update_time=?,start_time=?,end_time=?,enc_type=?,flow_data=? " + "WHERE exec_id=?"; byte[] data = null; try { final String json = JSONUtils.toJSON(flow.toObject()); final byte[] stringData = json.getBytes("UTF-8"); data = stringData; if (encType == EncodingType.GZIP) { data = GZIPUtils.gzipBytes(stringData); } } catch (final IOException e) { flow.setStatus(Status.FAILED); updateExecutableFlowStatus(flow); throw new ExecutorManagerException("Error encoding the execution flow. Execution Id = " + flow.getExecutionId()); } catch (final NullPointerException npe) { flow.setStatus(Status.FAILED); if ( data == null) { logger.warn("Failed to serialize executable flow for " + flow.getExecutionId() + ". Likely due to SLA missing options. Please re-check the flow SLA"); } <START> updateExecutableFlowStatus(flow); <END> throw new ExecutorManagerException("Error encoding the execution flow due to NPE. " + "Execution Id = " + flow.getExecutionId()); } try { this.dbOperator.update(UPDATE_EXECUTABLE_FLOW_DATA, flow.getStatus() .getNumVal(), flow.getUpdateTime(), flow.getStartTime(), flow .getEndTime(), encType.getNumVal(), data, flow.getExecutionId()); } catch (final SQLException e) { throw new ExecutorManagerException("Error updating flow.", e); } }</code><technical_language>This is invoked times moved a finally block. do want update failure exception</technical_language>

Target:
private void updateExecutableFlow(final ExecutableFlow flow, final EncodingType encType) throws ExecutorManagerException { final String UPDATE_EXECUTABLE_FLOW_DATA = "UPDATE execution_flows " + "SET status=?,update_time=?,start_time=?,end_time=?,enc_type=?,flow_data=? " + "WHERE exec_id=?"; byte[] data = null; try { final String json = JSONUtils.toJSON(flow.toObject()); final byte[] stringData = json.getBytes("UTF-8"); data = stringData; if (encType == EncodingType.GZIP) { data = GZIPUtils.gzipBytes(stringData); } } catch (final IOException e) { flow.setStatus(Status.FAILED); updateExecutableFlowStatusInDB(flow); throw new ExecutorManagerException("Error encoding the execution flow. Execution Id = " + flow.getExecutionId()); } catch (final RuntimeException re) { flow.setStatus(Status.FAILED); if ( data == null && re instanceof NullPointerException) { logger.warn("Failed to serialize executable flow for " + flow.getExecutionId()); logger.warn("NPE stacktrace" + ExceptionUtils.getStackTrace(re)); } updateExecutableFlowStatusInDB(flow); throw new ExecutorManagerException("Error encoding the execution flow due to " + "RuntimeException. Execution Id = " + flow.getExecutionId(), re); } try { this.dbOperator.update(UPDATE_EXECUTABLE_FLOW_DATA, flow.getStatus() .getNumVal(), flow.getUpdateTime(), flow.getStartTime(), flow .getEndTime(), encType.getNumVal(), data, flow.getExecutionId()); } catch (final SQLException e) { throw new ExecutorManagerException("Error updating flow.", e); } }
Source:
<code>public boolean equals(final Object o) { if (this == o) { return true; } <START> if (o == null || getClass() != o.getClass()) { <END> return false; } final LoopDetectionCriteria that = (LoopDetectionCriteria) o; return seen.equals(that.seen); }</code><technical_language>Is a reason getClass() is instead of instanceof. instanceof is restrictive choice</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof LoopDetectionCriteria)) { return false; } final LoopDetectionCriteria that = (LoopDetectionCriteria) o; return seen.equals(that.seen); }
Source:
<code>public void testSaveMetaDataException() { <START> final InputStream is = new ByteArrayInputStream("hello".getBytes(StandardCharsets.UTF_8)); <END> doReturn(is).when(ioService).newInputStream(any(), any()); doThrow(IOException.class).when(ioService).write(any(org.uberfire.java.nio.file.Path.class), any(byte[].class), anyMap(), any()); service.saveMetadata(path, new Metadata(), "comment"); }</code><technical_language>need close this stream</technical_language>

Target:
public void testSaveMetaDataException() throws IOException { final InputStream is = new ByteArrayInputStream("hello".getBytes(StandardCharsets.UTF_8)); try { doReturn(is).when(ioService).newInputStream(any(), any()); doThrow(IOException.class).when(ioService).write(any(org.uberfire.java.nio.file.Path.class), any(byte[].class), anyMap(), any()); service.saveMetadata(Paths.convert(path), new Metadata(), "comment"); } finally { is.close(); } }
Source:
<code>public void setApplicationIcon(Stage stage) { stage.getIcons().add(new Image(UI.class.getResourceAsStream("logo.png"))); try { Class util = Class.forName("com.apple.eawt.Application"); Method getApplication = util.getMethod("getApplication", new Class[0]); Object application = getApplication.invoke(util); Class params[] = new Class[1]; params[0] = java.awt.Image.class; Method setDockIconImage = util.getMethod("setDockIconImage", params); setDockIconImage.invoke(application, new ImageIcon(UI.class.getResource("logo.png")).getImage()); <START> } catch (Exception e) { <END> logger.info("Not OSX", e); } }</code><technical_language>explicitly check for OS X of platform-specific methods instead. Feels a bit clearer read. Otherwise, more specific exception is expected here</technical_language>

Target:
public void setApplicationIcon(Stage stage) { stage.getIcons().add(new Image(UI.class.getResourceAsStream(APPLICATION_LOGO_FILENAME))); if (PlatformSpecific.isOnMac()) { try { Class util = Class.forName("com.apple.eawt.Application"); Method getApplication = util.getMethod("getApplication", new Class[0]); Object application = getApplication.invoke(util); Class params[] = new Class[1]; params[0] = java.awt.Image.class; Method setDockIconImage = util.getMethod("setDockIconImage", params); setDockIconImage.invoke(application, new ImageIcon(UI.class.getResource(APPLICATION_LOGO_FILENAME)).getImage()); } catch (Exception e) { logger.info("Not OSX", e); } } }
Source:
<code>public void upload(final InputStream input, OutputStream output, final OutputStream messages) throws IOException { try { rawIn = input; if (messages != null) msgOut = messages; if (timeout > 0) { final Thread caller = Thread.currentThread(); timer = new InterruptTimer(caller.getName() + "-Timer"); TimeoutInputStream i = new TimeoutInputStream(rawIn, timer); <START> @SuppressWarnings("resource") <END> TimeoutOutputStream o = new TimeoutOutputStream(output, timer); i.setTimeout(timeout * 1000); o.setTimeout(timeout * 1000); rawIn = i; output = o; } rawOut = new ResponseBufferedOutputStream( output, biDirectionalPipe); pckIn = new PacketLineIn(rawIn); pckOut = new PacketLineOut(rawOut); service(); } finally { msgOut = NullOutputStream.INSTANCE; walk.close(); if (timer != null) { try { timer.terminate(); } finally { timer = null; } } } }</code><technical_language>This is safe TimeoutOutputStream is responsible for closing output assign 'output = o' ensure close TimeoutOutputStream. start warning now? warning suppress yet</technical_language>

Target:
public void upload(final InputStream input, OutputStream output, final OutputStream messages) throws IOException { try { rawIn = input; if (messages != null) msgOut = messages; if (timeout > 0) { final Thread caller = Thread.currentThread(); timer = new InterruptTimer(caller.getName() + "-Timer"); TimeoutInputStream i = new TimeoutInputStream(rawIn, timer); @SuppressWarnings("resource") TimeoutOutputStream o = new TimeoutOutputStream(output, timer); i.setTimeout(timeout * 1000); o.setTimeout(timeout * 1000); rawIn = i; output = o; } rawOut = new ResponseBufferedOutputStream(output); if (biDirectionalPipe) { rawOut.stopBuffering(); } pckIn = new PacketLineIn(rawIn); pckOut = new PacketLineOut(rawOut); service(); } finally { msgOut = NullOutputStream.INSTANCE; walk.close(); if (timer != null) { try { timer.terminate(); } finally { timer = null; } } } }
Source:
<code>public void execute() throws IOException, CommandFailed { if ( !fs.fileExists( fromPath ) ) { throw new IllegalArgumentException( format( "Source directory does not exist [%s]", fromPath ) ); } try { Validators.CONTAINS_EXISTING_DATABASE.validate( fromPath ); } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( format( "Source directory is not a database backup [%s]", fromPath ) ); } if ( fs.fileExists( databaseDir ) && !forceOverwrite ) { throw new IllegalArgumentException( format( "Database with name [%s] already exists at %s", databaseName, databaseDir ) ); } checkLock( databaseDir.toPath() ); fs.deleteRecursively( databaseDir ); <START> if ( !databaseDir.equals( transactionLogsDirectory ) ) <END> { fs.deleteRecursively( transactionLogsDirectory ); } LogFiles backupLogFiles = LogFilesBuilder.logFilesBasedOnlyBuilder( fromPath, fs ).build(); File[] files = fromPath.listFiles(); if ( files != null ) { for ( File file : files ) { fs.copyToDirectory( file, backupLogFiles.isLogFile( file ) ? transactionLogsDirectory : databaseDir ); } } }</code><technical_language>paths canonicalized (and symlinks resolved) this comparison. Ponder if for example: dbDir = /a/b/c txDir = /a/b/c/d/.. comparison fail, try delete dir twice. canonicalization done explicit *here* in opinion</technical_language>

Target:
public void execute() throws IOException, CommandFailed { if ( !fs.fileExists( fromPath ) ) { throw new IllegalArgumentException( format( "Source directory does not exist [%s]", fromPath ) ); } try { Validators.CONTAINS_EXISTING_DATABASE.validate( fromPath ); } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( format( "Source directory is not a database backup [%s]", fromPath ) ); } if ( fs.fileExists( databaseDir ) && !forceOverwrite ) { throw new IllegalArgumentException( format( "Database with name [%s] already exists at %s", databaseName, databaseDir ) ); } checkLock( databaseDir.toPath() ); fs.deleteRecursively( databaseDir ); if ( !isSameOrChildFile( databaseDir, transactionLogsDirectory ) ) { fs.deleteRecursively( transactionLogsDirectory ); } LogFiles backupLogFiles = LogFilesBuilder.logFilesBasedOnlyBuilder( fromPath, fs ).build(); File[] files = fromPath.listFiles(); if ( files != null ) { for ( File file : files ) { fs.copyToDirectory( file, backupLogFiles.isLogFile( file ) ? transactionLogsDirectory : databaseDir ); } } }
Source:
<code>public boolean isDSDAudio() { <START> return getCodecA() != null && (getCodecA().equalsIgnoreCase(FormatConfiguration.DSDAudio)); <END> }</code><technical_language>Nice, AFAIK MediaInfo is able parse it..</technical_language>

Target:
public boolean isDSDAudio() { return FormatConfiguration.DSDAudio.equalsIgnoreCase(getCodecA()); }
Source:
<code>public void setUp() throws Exception { port = AvailablePortHelper.getRandomAvailableTCPPort(); server = new EmbeddedTomcat8(port, "JVM-1"); PeerToPeerCacheLifecycleListener p2pListener = new PeerToPeerCacheLifecycleListener(); p2pListener.setProperty(MCAST_PORT, "0"); p2pListener.setProperty(LOG_LEVEL, "config"); server.addLifecycleListener(p2pListener); sessionManager = new Tomcat8DeltaSessionManager(); sessionManager.setEnableCommitValve(true); server.getRootContext().setManager(sessionManager); AuthConfigFactory.setFactory(null); servlet = server.addServlet("/test/*", "default", CommandServlet.class.getName()); server.startContainer(); region = sessionManager.getSessionCache().getSessionRegion(); sessionManager.getTheContext().setSessionTimeout(30); region.clear(); <START> checkSanity(); <END> }</code><technical_language>leave checkSanity() in code</technical_language>

Target:
public void setUp() throws Exception { port = AvailablePortHelper.getRandomAvailableTCPPort(); server = new EmbeddedTomcat8(port, "JVM-1"); PeerToPeerCacheLifecycleListener p2pListener = new PeerToPeerCacheLifecycleListener(); p2pListener.setProperty(MCAST_PORT, "0"); p2pListener.setProperty(LOG_LEVEL, "config"); server.addLifecycleListener(p2pListener); sessionManager = new Tomcat8DeltaSessionManager(); sessionManager.setEnableCommitValve(true); server.getRootContext().setManager(sessionManager); AuthConfigFactory.setFactory(null); servlet = server.addServlet("/test/*", "default", CommandServlet.class.getName()); server.startContainer(); region = sessionManager.getSessionCache().getSessionRegion(); sessionManager.getTheContext().setSessionTimeout(30); region.clear(); basicConnectivityCheck(); }
Source:
<code>public static void RefreshView () { Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .showView(PerfPlugin.SOURCE_DISASSEMBLY_VIEW_ID, <START> Integer.toString(new Object().hashCode()), <END> IWorkbenchPage.VIEW_CREATE); } catch (PartInitException e) { IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, e.getMessage(), e); PerfPlugin.getDefault().getLog().log(status); } } }); }</code><technical_language>Agreed, sense me</technical_language>

Target:
public static void RefreshView () { Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .showView(PerfPlugin.SOURCE_DISASSEMBLY_VIEW_ID, Integer.toString(SECONDARY_ID++), IWorkbenchPage.VIEW_CREATE); } catch (PartInitException e) { IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, e.getMessage(), e); PerfPlugin.getDefault().getLog().log(status); } } }); }
Source:
<code>public static List<String> getMetalinkUrls(String metalinkUrl) { HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); GetMethod getMethod = new GetMethod(metalinkUrl); List<String> urls = new ArrayList<>(); try { if (httpClient.executeMethod(getMethod) == HttpStatus.SC_OK) { <START> InputStream is = getMethod.getResponseBodyAsStream(); <END> Map<String, List<String>> metalinkUrlsMap = getMultipleValuesFromXML(is, new String[] {"url"}); if (metalinkUrlsMap.containsKey("url")) { List<String> metalinkUrls = metalinkUrlsMap.get("url"); urls.addAll(metalinkUrls); } } } catch (IOException e) { s_logger.warn(e.getMessage()); } return urls; }</code><technical_language>remark for try resource statement here. Currently inputstream close is missing</technical_language>

Target:
public static List<String> getMetalinkUrls(String metalinkUrl) { HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); GetMethod getMethod = new GetMethod(metalinkUrl); List<String> urls = new ArrayList<>(); try ( InputStream is = getMethod.getResponseBodyAsStream() ) { if (httpClient.executeMethod(getMethod) == HttpStatus.SC_OK) { Map<String, List<String>> metalinkUrlsMap = getMultipleValuesFromXML(is, new String[] {"url"}); if (metalinkUrlsMap.containsKey("url")) { List<String> metalinkUrls = metalinkUrlsMap.get("url"); urls.addAll(metalinkUrls); } } } catch (IOException e) { s_logger.warn(e.getMessage()); } return urls; }
Source:
<code>protected void prepareSynchronizer(final DiagramDescription description, final String diagramName) { sync = new DDiagramSynchronizer(interpreter, description, accessor); sync.initDiagram( semanticModel, new NullProgressMonitor()); <START> RepresentationsHelper.createDRepresentationDescriptor(sync.getDiagram(), (DAnalysisSessionImpl) session, semanticModel.eResource(), diagramName); <END> boolean syncOnCreation = Platform.getPreferencesService().getBoolean(DiagramPlugin.ID, SiriusDiagramInternalPreferencesKeys.PREF_SYNCHRONIZE_DIAGRAM_ON_CREATION.name(), false, null); sync.getDiagram().setSynchronized(syncOnCreation); }</code><technical_language>do a lot more</technical_language>

Target:
protected void prepareSynchronizer(final DiagramDescription description, final String diagramName) { sync = new DDiagramSynchronizer(interpreter, description, accessor); sync.initDiagram( semanticModel, new NullProgressMonitor()); boolean syncOnCreation = Platform.getPreferencesService().getBoolean(DiagramPlugin.ID, SiriusDiagramInternalPreferencesKeys.PREF_SYNCHRONIZE_DIAGRAM_ON_CREATION.name(), false, null); sync.getDiagram().setSynchronized(syncOnCreation); }
Source:
<code>public void define(WebService.NewController controller) { controller.createAction("info") .setDescription("Get detailed information about system configuration.<br/>" + "Requires 'Administer' permissions.<br/>" + "Since 5.5, this web service becomes internal in order to more easily update result.") .setSince("5.1") .setInternal(true) <START> .setResponseExample(getClass().getResource("/org/sonar/server/platform/ws/info-example.json")) <END> .setHandler(this); }</code><technical_language>Please update url removing "/org/sonar/server/platform/ws/"</technical_language>

Target:
public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("info") .setDescription("Get detailed information about system configuration.<br/>" + "Requires 'Administer' permissions.") .setSince("5.1") .setInternal(true) .setResponseExample(getClass().getResource("info-example.json")) .setHandler(this); action.setChangelog( new Change("5.5", "Becomes internal to easily update result") ); }
Source:
<code>private List<VM> getMigratableVmsRunningOnVds(final VmDao vmDao, final Guid hostId) { List<VM> vmsFromDB = vmDao.getAllRunningForVds(hostId); return vmsFromDB.stream() .filter( <START> v -> <END> v.getMigrationSupport() == MigrationSupport.MIGRATABLE && !v.getDedicatedVmForVdsList().contains(hostId) ).collect(Collectors.toList()); }</code><technical_language>while please rename v vm</technical_language>

Target:
private List<VM> getMigratableVmsRunningOnVds(final VmDao vmDao, final Guid hostId) { List<VM> vmsFromDB = vmDao.getAllRunningForVds(hostId); return vmsFromDB.stream() .filter( vm -> vm.getMigrationSupport() == MigrationSupport.MIGRATABLE && !vm.getDedicatedVmForVdsList().contains(hostId) ).collect(Collectors.toList()); }
Source:
<code>protected void doExecute(Task task, DeleteExpiredDataAction.Request request, ActionListener<DeleteExpiredDataAction.Response> listener) { logger.info("Deleting expired data"); Instant timeoutTime = Instant.now(clock).plus( request.getTimeout() == null ? DEFAULT_MAX_DURATION : Duration.ofMillis(request.getTimeout().millis()) ); jobConfigProvider.expandJobs(request.getJobId(), true, true, ActionListener.wrap( <START> jobBuilders -> { <END> Supplier<Boolean> isTimedOutSupplier = () -> Instant.now(clock).isAfter(timeoutTime); threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME).execute( () -> { List<Job> jobs = jobBuilders.stream().map(Job.Builder::build).collect(Collectors.toList()); deleteExpiredData(request, jobs, listener, isTimedOutSupplier); } ); }, listener::onFailure )); }</code><technical_language>IMO, if is > 10,000, cleanup is finish. This a simple throttle get for free</technical_language>

Target:
protected void doExecute(Task task, DeleteExpiredDataAction.Request request, ActionListener<DeleteExpiredDataAction.Response> listener) { logger.info("Deleting expired data"); Instant timeoutTime = Instant.now(clock).plus( request.getTimeout() == null ? DEFAULT_MAX_DURATION : Duration.ofMillis(request.getTimeout().millis()) ); Supplier<Boolean> isTimedOutSupplier = () -> Instant.now(clock).isAfter(timeoutTime); threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME).execute( () -> deleteExpiredData(request, listener, isTimedOutSupplier) ); }
Source:
<code>public void clientIdmultipleConnection() { Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); client2.auth("foobared"); client2.clientSetname("fancy_jedis_another_name"); long clientId1 = client.clientId(); long clientId2 = client2.clientId(); <START> Assert.assertTrue(clientId1 < clientId2); <END> client2.close(); }</code><technical_language>suggestion assertTrue(clientId1 < clientId2);</technical_language>

Target:
public void clientIdmultipleConnection() { Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); client2.auth("foobared"); client2.clientSetname("fancy_jedis_another_name"); long clientId1 = client.clientId(); long clientId2 = client2.clientId(); assertTrue(clientId1 < clientId2); client2.close(); }
Source:
<code>public Object getParent(Object element) { if (element instanceof IWorkingSet && element != workingSetRoot) return workingSetRoot; Object res = parents.get(element); if (res != null) { return res; } if <START> (unassignedProjects.contains(res)) <END> { return OTHERS_WORKING_SET; } return null; }</code><technical_language>res is null here. Do expect unassignedProjects contains null</technical_language>

Target:
public Object getParent(Object element) { if (element instanceof IWorkingSet && element != workingSetRoot) return workingSetRoot; Object res = parents.get(element); if (res != null) { return res; } if (unassignedProjects.contains(element)) { return OTHERS_WORKING_SET; } return null; }
Source:
<code>public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull("BPMN Model XML not found", bpmnModel); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); validateModel(parsedModel); <START> deployProcess(parsedModel); <END> }</code><technical_language>Is deployProcess() method something? if start rid of dead code</technical_language>

Target:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull("BPMN Model XML not found", bpmnModel); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); assertNotNull(parsedModel); validateModel(parsedModel); }
Source:
<code>protected Object executeWithSubject() throws Exception { Filter filter = getFilter(); transformer = getServiceByFilter( MetacardTransformer.class, String.format("(%s=%s)", "id", DEFAULT_TRANSFORMER_ID)) .orElseThrow( () -> new IllegalArgumentException( "Could not get " + DEFAULT_TRANSFORMER_ID + " transformer")); revisionFilter = initRevisionFilter(); final File outputFile = initOutputFile(output); checkFile(outputFile); if (delete && !force) { final String input = session.readLine( "This action will remove all exported metacards and content from the catalog. Are you sure you wish to continue? (y/N):", null); <START> if (!input.matches("^[yY][eE]?[sS]?$")) { <END> console.println("ABORTED EXPORT."); return null; } } SecurityLogger.audit("Called catalog:export command with path : {}", output); try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) { return doExport(outputFile, zipOutputStream, filter); } catch (FileNotFoundException e) { throw new FileNotFoundException( String.format( "ZipOutputStream could not be created for the path %s", outputFile.getPath())); } }</code><technical_language>I suggest Apache's BooleanUtils.toBooleanObject() do this test a) check length is >= 1 b) get charAt(0) c) check char == 'y' 'Y' problem BooleanUtils is match other inputs (e.g. 't', 'on', etc.) confusing. need for a regex here, weird this regex match string yE</technical_language>

Target:
protected Object executeWithSubject() throws Exception { Filter filter = getFilter(); transformer = getServiceByFilter( MetacardTransformer.class, String.format("(%s=%s)", "id", DEFAULT_TRANSFORMER_ID)) .orElseThrow( () -> new IllegalArgumentException( "Could not get " + DEFAULT_TRANSFORMER_ID + " transformer")); revisionFilter = initRevisionFilter(); final File outputFile = initOutputFile(output); checkFile(outputFile); if (delete && !force) { final String input = session.readLine( "This action will remove all exported metacards and content from the catalog. Are you sure you wish to continue? (y/N):", null); if (input.length() == 0 || Character.toLowerCase(input.charAt(0)) != 'y') { console.println("ABORTED EXPORT."); return null; } } SecurityLogger.audit("Called catalog:export command with path : {}", output); try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) { return doExport(outputFile, zipOutputStream, filter); } catch (FileNotFoundException e) { throw new FileNotFoundException( String.format( "ZipOutputStream could not be created for the path %s", outputFile.getPath())); } }
Source:
<code>public Optional<String> formatInitCond() { if (initCond == null) { return Optional.empty(); } if (stateTypeCodec == null) { LOG.debug( String.format( "Null codec for INITCOND for %s.%s, using toString instead. This often indicates use of a deserialized AggregateMetadata instance.", keyspace.asInternal(), signature.getName().asInternal())); return Optional.of(initCond.toString()); <START> } <END> try { return Optional.of(stateTypeCodec.format(initCond)); } catch (Throwable t) { LOG.warn( String.format( "Failed to format INITCOND for %s.%s, using toString instead", keyspace.asInternal(), signature.getName().asInternal())); return Optional.of(initCond.toString()); } }</code><technical_language>pre-compute result of formatInitCond() in constructor, store a field instead of codec. original intent in storing codec avoid formatting eagerly if used, a deserialized object describe correctly</technical_language>

Target:
public Optional<String> formatInitCond() { return Optional.ofNullable(this.formattedInitCond); }
Source:
<code>public void put(Object key, Object value) { <START> throw new RuntimeException("Not supported operation"); <END> }</code><technical_language>UnsupportedOperationException</technical_language>

Target:
public void put(Object key, Object value) { throw new UnsupportedOperationException("Not supported operation"); }
Source:
<code>public synchronized PinotResourceManagerResponse updateInstanceTags(String instanceIdToUpdate, String tags) { InstanceConfig instanceConfig = getHelixInstanceConfig(instanceIdToUpdate); if (instanceConfig == null) { return PinotResourceManagerResponse.failure("Instance " + instanceIdToUpdate + " does not exists"); } <START> String[] newTags = tags.split(","); List<String> existingTags = Lists.newArrayList(instanceConfig.getTags()); for (String tag : existingTags) { instanceConfig.removeTag(tag); } for (String tag : newTags) { instanceConfig.addTag(tag); } <END> if (!_helixDataAccessor.setProperty(_keyBuilder.instanceConfig(instanceIdToUpdate), instanceConfig)) { return PinotResourceManagerResponse.failure("Unable to update instance: " + instanceIdToUpdate); } return PinotResourceManagerResponse.SUCCESS; }</code><technical_language>simplified (not Helix provide setTags()), StringUtils.split() performance String.split() takes a regex suggestion List<String> tagList = Arrays.asList(StringUtils.split(tags, ',')); instanceConfig.getRecord().setListField(InstanceConfig.InstanceConfigProperty.TAG_LIST.name(), tagList);</technical_language>

Target:
public synchronized PinotResourceManagerResponse updateInstanceTags(String instanceIdToUpdate, String tags) { InstanceConfig instanceConfig = getHelixInstanceConfig(instanceIdToUpdate); if (instanceConfig == null) { return PinotResourceManagerResponse.failure("Instance " + instanceIdToUpdate + " does not exists"); } List<String> tagList = Arrays.asList(StringUtils.split(tags, ',')); instanceConfig.getRecord().setListField(InstanceConfig.InstanceConfigProperty.TAG_LIST.name(), tagList); if (!_helixDataAccessor.setProperty(_keyBuilder.instanceConfig(instanceIdToUpdate), instanceConfig)) { return PinotResourceManagerResponse .failure("Unable to update instance: " + instanceIdToUpdate + " to tags: " + tags); } return PinotResourceManagerResponse.SUCCESS; }
Source:
<code>public URI build() { try { URI optionsUri = pattern.construct(options); <START> StringBuilder uri = new StringBuilder(); <END> uri.append(isView ? VIEW_SCHEME : DATASET_SCHEME).append(":") .append(optionsUri.getScheme()).append(":") .append(optionsUri.getRawSchemeSpecificPart()); return new URI(uri.toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Could not build URI", e); } }</code><technical_language>work changes here? concatenate: java return new URI(isView ? VIEW_SCHEME : DATASET_SCHEME + ":" + pattern.construct(options).toString());</technical_language>

Target:
public URI build() { try { return new URI((isView ? VIEW_SCHEME : DATASET_SCHEME) + ":" + pattern.construct(options).toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Could not build URI", e); } }
Source:
<code>public void pulse() { super.pulse(); if (noDamageTicks > 0) { --noDamageTicks; } Material mat = getEyeLocation().getBlock().getType(); if (mat == Material.WATER || mat == Material.STATIONARY_WATER) { if (canTakeDamage(EntityDamageEvent.DamageCause.DROWNING)) { --airTicks; if (airTicks <= -20) { airTicks = 0; damage(1, EntityDamageEvent.DamageCause.DROWNING); } } } else { airTicks = maximumAir; } if (isTouchingMaterial(Material.CACTUS) && canTakeDamage(EntityDamageEvent.DamageCause.CONTACT)) { damage(1, EntityDamageEvent.DamageCause.CONTACT); } if (location.getY() < -64) { damage(4, EntityDamageEvent.DamageCause.VOID); } if (isWithinSolidBlock()) damage(1, EntityDamageEvent.DamageCause.SUFFOCATION); <START> <END> List<PotionEffect> effects = new ArrayList<>(potionEffects.values()); for (PotionEffect effect : effects) { PotionEffectType type = effect.getType(); GlowPotionEffect glowType = GlowPotionEffect.getEffect(type); if (glowType != null) { glowType.pulse(this, effect); } if (effect.getDuration() > 0) { addPotionEffect(new PotionEffect(type, effect.getDuration() - 1, effect.getAmplifier(), effect.isAmbient()), true); } else { removePotionEffect(type); } } }</code><technical_language>[You curly braces conditional statements' blocks.](<LINK_0></technical_language>

Target:
public void pulse() { super.pulse(); if (noDamageTicks > 0) { --noDamageTicks; } Material mat = getEyeLocation().getBlock().getType(); if (mat == Material.WATER || mat == Material.STATIONARY_WATER) { if (canTakeDamage(EntityDamageEvent.DamageCause.DROWNING)) { --airTicks; if (airTicks <= -20) { airTicks = 0; damage(1, EntityDamageEvent.DamageCause.DROWNING); } } } else { airTicks = maximumAir; } if (isTouchingMaterial(Material.CACTUS) && canTakeDamage(EntityDamageEvent.DamageCause.CONTACT)) { damage(1, EntityDamageEvent.DamageCause.CONTACT); } if (location.getY() < -64) { damage(4, EntityDamageEvent.DamageCause.VOID); } if (isWithinSolidBlock()) { damage(1, EntityDamageEvent.DamageCause.SUFFOCATION); } List<PotionEffect> effects = new ArrayList<>(potionEffects.values()); for (PotionEffect effect : effects) { PotionEffectType type = effect.getType(); GlowPotionEffect glowType = GlowPotionEffect.getEffect(type); if (glowType != null) { glowType.pulse(this, effect); } if (effect.getDuration() > 0) { addPotionEffect(new PotionEffect(type, effect.getDuration() - 1, effect.getAmplifier(), effect.isAmbient()), true); } else { removePotionEffect(type); } } }
Source:
<code>private RuntimeConfig(Context ctx) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { configurations = getRestrictions(ctx); isManaged = hasRestrictionsProvider(ctx); if(isManaged && configurations!=null && !configurations.isEmpty()){ SalesforceSDKManager.getInstance().registerUsedAppFeature(FEATURE_MDM); } <START> if(getBoolean(RuntimeConfig.ConfigKey.RequireCertAuth)){ <END> SalesforceSDKManager.getInstance().registerUsedAppFeature(FEATURE_CERT_AUTH); } final JSONObject attributes = new JSONObject(); try { attributes.put("mdmIsActive", isManaged); if (configurations != null) { final JSONObject mdmValues = new JSONObject(); final Set<String> keys = configurations.keySet(); for (final String key : keys) { mdmValues.put(key, JSONObject.wrap(configurations.get(key))); } attributes.put("mdmConfigs", mdmValues); } } catch (JSONException e) { Log.e(TAG, "Exception thrown while creating JSON", e); } EventBuilderHelper.createAndStoreEvent("mdmConfiguration", null, TAG, attributes); } }</code><technical_language>Move this if(isManaged && configurations!=null && !configurations.isEmpty()) block</technical_language>

Target:
private RuntimeConfig(Context ctx) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { configurations = getRestrictions(ctx); isManaged = hasRestrictionsProvider(ctx); if(isManaged && configurations!=null && !configurations.isEmpty()){ SalesforceSDKManager.getInstance().registerUsedAppFeature(FEATURE_MDM); if(getBoolean(RuntimeConfig.ConfigKey.RequireCertAuth)){ SalesforceSDKManager.getInstance().registerUsedAppFeature(FEATURE_CERT_AUTH); } } final JSONObject attributes = new JSONObject(); try { attributes.put("mdmIsActive", isManaged); if (configurations != null) { final JSONObject mdmValues = new JSONObject(); final Set<String> keys = configurations.keySet(); for (final String key : keys) { mdmValues.put(key, JSONObject.wrap(configurations.get(key))); } attributes.put("mdmConfigs", mdmValues); } } catch (JSONException e) { Log.e(TAG, "Exception thrown while creating JSON", e); } EventBuilderHelper.createAndStoreEvent("mdmConfiguration", null, TAG, attributes); } }
Source:
<code>protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception { ByteBuf decompressedContent = decompressContent(ctx, msg); <START> WebSocketFrame outMsg; <END> if (msg instanceof TextWebSocketFrame) { outMsg = new TextWebSocketFrame(msg.isFinalFragment(), newRsv(msg), decompressedContent); } else if (msg instanceof BinaryWebSocketFrame) { outMsg = new BinaryWebSocketFrame(msg.isFinalFragment(), newRsv(msg), decompressedContent); } else if (msg instanceof ContinuationWebSocketFrame) { outMsg = new ContinuationWebSocketFrame(msg.isFinalFragment(), newRsv(msg), decompressedContent); } else { throw new CodecException("unexpected frame type: " + msg.getClass().getName()); } out.add(outMsg); }</code><technical_language>final</technical_language>

Target:
protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception { final ByteBuf decompressedContent = decompressContent(ctx, msg); final WebSocketFrame outMsg; if (msg instanceof TextWebSocketFrame) { outMsg = new TextWebSocketFrame(msg.isFinalFragment(), newRsv(msg), decompressedContent); } else if (msg instanceof BinaryWebSocketFrame) { outMsg = new BinaryWebSocketFrame(msg.isFinalFragment(), newRsv(msg), decompressedContent); } else if (msg instanceof ContinuationWebSocketFrame) { outMsg = new ContinuationWebSocketFrame(msg.isFinalFragment(), newRsv(msg), decompressedContent); } else { throw new CodecException("unexpected frame type: " + msg.getClass().getName()); } out.add(outMsg); }