auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void setSocketHostname(SSLSocket sslSocket, String hostname) { <START> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { <END> boolean ret = false; try { Method method = sslSocket.getClass().getMethod("setHostname", String.class); method.invoke(sslSocket, hostname); ret = true; } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { } catch (IllegalAccessException ex) { } if (!ret && LOG_ENABLED) { LogUtils.i(TAG, "setHostname isn't available for this socket."); } } }</code><technical_language>Suggestion: Drop this check. need API Level check (and @TargetApi annotation above). code is failing gracefully if setHostname method is there. this check, SNI get enabled older platforms if SSLSocket supports it</technical_language>

Target:
private void setSocketHostname(SSLSocket sslSocket, String hostname) { try { Method method = sslSocket.getClass().getMethod("setHostname", String.class); method.invoke(sslSocket, hostname); return; } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { } catch (IllegalAccessException ex) { } if (LOG_ENABLED) { LogUtils.i(TAG, "setHostname isn't available for this socket."); } }
Source:
<code>public static EntityManager getEntityManager() throws ApplicationSettingsException { if (factory == null) { String connectionProperties = "DriverClassName=" + readServerProperties(REPLICACATALOG_JDBC_DRIVER) + "," + "Url=" + readServerProperties(REPLICACATALOG_JDBC_URL) + "?autoReconnect=true," + "Username=" + readServerProperties(REPLICACATALOG_JDBC_USER) + "," + "Password=" + readServerProperties(REPLICACATALOG_JDBC_PWD) + ",validationQuery=" + readServerProperties(REPLICACATALOG_VALIDATION_QUERY); System.out.println(connectionProperties); Map<String, String> properties = new HashMap<>(); properties.put("openjpa.ConnectionDriverName", "org.apache.commons.dbcp.BasicDataSource"); properties.put("openjpa.ConnectionProperties", connectionProperties); properties.put("openjpa.DynamicEnhancementAgent", "true"); properties.put("openjpa.RuntimeUnenhancedClasses", "unsupported"); properties.put("openjpa.RemoteCommitProvider","sjvm"); properties.put("openjpa.Log","DefaultLevel=TRACE, Runtime=TRACE, Tool=TRACE, SQL=TRACE"); properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); <START> properties.put("openjpa.jdbc.QuerySQLCache", "false"); <END> properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72," + " PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=31536000, autoReconnect=true"); factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties); } dataCatEntityManager = factory.createEntityManager(); return dataCatEntityManager; }</code><technical_language>leave this INFO level</technical_language>

Target:
public static EntityManager getEntityManager() throws ApplicationSettingsException { if (factory == null) { String connectionProperties = "DriverClassName=" + readServerProperties(REPLICACATALOG_JDBC_DRIVER) + "," + "Url=" + readServerProperties(REPLICACATALOG_JDBC_URL) + "?autoReconnect=true," + "Username=" + readServerProperties(REPLICACATALOG_JDBC_USER) + "," + "Password=" + readServerProperties(REPLICACATALOG_JDBC_PWD) + ",validationQuery=" + readServerProperties(REPLICACATALOG_VALIDATION_QUERY); System.out.println(connectionProperties); Map<String, String> properties = new HashMap<>(); properties.put("openjpa.ConnectionDriverName", "org.apache.commons.dbcp.BasicDataSource"); properties.put("openjpa.ConnectionProperties", connectionProperties); properties.put("openjpa.DynamicEnhancementAgent", "true"); properties.put("openjpa.RuntimeUnenhancedClasses", "unsupported"); properties.put("openjpa.RemoteCommitProvider","sjvm"); properties.put("openjpa.Log","DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=INFO"); properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); properties.put("openjpa.jdbc.QuerySQLCache", "false"); properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72," + " PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=31536000, autoReconnect=true"); factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties); } dataCatEntityManager = factory.createEntityManager(); return dataCatEntityManager; }
Source:
<code>public void setButtonType(int buttonType) { if (buttonType == mButtonType) { return; } mButtonType = buttonType; mTextView.setText(getButtonTextResId(buttonType)); <START> if (buttonType == BUTTON_RETRY) { <END> mImageView.setImageResource(0); Resources resources = mImageView.getContext().getResources(); Drawable drawable = resources.getDrawable(getButtonIconResId(buttonType)); drawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(drawable, resources.getColor(R.color.blue_medium)); mImageView.setImageDrawable(drawable); } else { mImageView.setImageResource(getButtonIconResId(buttonType)); } }</code><technical_language>I do this for retry button (it other icons) - get a correctly sized tinted gridicon match others</technical_language>

Target:
public void setButtonType(int buttonType) { if (buttonType == mButtonType) { return; } mButtonType = buttonType; mTextView.setText(getButtonTextResId(buttonType)); mImageView.setImageResource(getButtonIconResId(buttonType)); }
Source:
<code>private Map<String, String> getStatusXml(Connection connection) throws SQLException { Map<String, String> result = new HashMap<>(); <START> PreparedStatement getStatusXml = connection.prepareStatement("SELECT s.runName, s.xml FROM Status AS s WHERE s.xml IS NOT NULL"); <END> ResultSet rs = getStatusXml.executeQuery(); while (rs.next()) { String key = rs.getString("runName"); String value = rs.getString("xml"); result.put(key, value); } return result; }</code><technical_language>of PreparedStatements in this class closed</technical_language>

Target:
private Map<String, String> getStatusXml(Connection connection) throws SQLException { Map<String, String> result = new HashMap<>(); PreparedStatement getStatusXml = connection.prepareStatement("SELECT s.runName, s.xml FROM Status AS s WHERE s.xml IS NOT NULL"); ResultSet rs = getStatusXml.executeQuery(); try { while (rs.next()) { String key = rs.getString("runName"); String value = rs.getString("xml"); result.put(key, value); } } finally { getStatusXml.close(); rs.close(); } return result; }
Source:
<code>public void registerServer(LoadBalanceZookeeperConf configuration, int pqsPort, String zookeeperConnectString, String pqsHost) throws Exception { this.client = CuratorFrameworkFactory.newClient(zookeeperConnectString, new ExponentialBackoffRetry(1000,10)); this.client.start(); HostAndPort hostAndPort = HostAndPort.fromParts(pqsHost,pqsPort); String path = configuration.getFullPathToNode(hostAndPort); String node = hostAndPort.toString(); this.client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path ,node.getBytes(StandardCharsets.UTF_8)); Stat stat = this.client.setACL().withACL(configuration.getAcls()).forPath(path); if (stat != null) { LOG.info(" node created with right ACL"); } else { LOG.error("could not create node with right ACL. So, system would exit now."); <START> System.exit(-1); <END> } }</code><technical_language>Calling System.exit(-1) is pretty brutal for integrate software :) Throwing a RuntimeException nicer</technical_language>

Target:
public void registerServer(LoadBalanceZookeeperConf configuration, int pqsPort, String zookeeperConnectString, String pqsHost) throws Exception { this.client = CuratorFrameworkFactory.newClient(zookeeperConnectString, new ExponentialBackoffRetry(1000,10)); this.client.start(); HostAndPort hostAndPort = HostAndPort.fromParts(pqsHost,pqsPort); String path = configuration.getFullPathToNode(hostAndPort); String node = hostAndPort.toString(); this.client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path ,node.getBytes(StandardCharsets.UTF_8)); Stat stat = this.client.setACL().withACL(configuration.getAcls()).forPath(path); if (stat != null) { LOG.info(" node created with right ACL"); } else { LOG.error("could not create node with right ACL. So, system would exit now."); throw new RuntimeException(" Unable to connect to Zookeeper"); } }
Source:
<code>int computeNumTasks() { final int maxParallelism = Math.min(JvmUtils.getRuntimeInfo().getAvailableProcessors(), parallelism); final int utilizationEstimate = getPool().getRunningThreadCount() + getPool().getQueuedSubmissionCount(); <START> final int computedParallelism = Math.min(maxParallelism, getPool().getParallelism() - utilizationEstimate); <END> final int computedOptimalParallelism = Math.min( (int) Math.floor((double) sequences.size() / 2.0), computedParallelism - 1 ); return computedOptimalParallelism; }</code><technical_language>Is return a negative number getPool().getParallelism() - utilizationEstimate? If so, nicer, number is logged, force 1 minimum represent serial processing case</technical_language>

Target:
private int computeNumTasks() { final int runningThreadCount = getPool().getRunningThreadCount(); final int submissionCount = getPool().getQueuedSubmissionCount(); final int maxParallelism = Math.min(parallelism, getPool().getParallelism()); final int utilizationEstimate = runningThreadCount + submissionCount - 1; final int computedParallelismForUtilization = maxParallelism - utilizationEstimate; final int computedParallelismForSequences = (int) Math.floor(Math.sqrt(sequences.size())); final int computedOptimalParallelism = Math.min( computedParallelismForSequences, computedParallelismForUtilization - 1 ); final int computedNumParallelTasks = Math.max(computedOptimalParallelism, 1); LOG.debug("Computed parallel tasks: [%s]; ForkJoinPool details - sequence parallelism: [%s] " + "active threads: [%s] running threads: [%s] queued submissions: [%s] queued tasks: [%s] " + "pool parallelism: [%s] pool size: [%s] steal count: [%s]", computedNumParallelTasks, parallelism, getPool().getActiveThreadCount(), runningThreadCount, submissionCount, getPool().getQueuedTaskCount(), getPool().getParallelism(), getPool().getPoolSize(), getPool().getStealCount() ); return computedNumParallelTasks; }
Source:
<code>public void testOpenUdpEncapsulationSocketCallsSetSocketOwner() throws Exception { <START> int localport = findUnusedPort(); IpSecUdpEncapResponse udpEncapResp = mIpSecService.openUdpEncapsulationSocket(localport, new Binder()); <END> verify(mMockNetd).ipSecSetSocketOwner(anyObject(), eq(Os.getuid())); mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId); }</code><technical_language>Optional: is irrelevant this test, omit findUnusedPort() 0</technical_language>

Target:
public void testOpenUdpEncapsulationSocketCallsSetSocketOwner() throws Exception { IpSecUdpEncapResponse udpEncapResp = mIpSecService.openUdpEncapsulationSocket(0, new Binder()); verify(mMockNetd).ipSecSetSocketOwner(anyObject(), eq(Os.getuid())); mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId); }
Source:
<code>protected void onSetUpAfterOpeningDesignerPerspective() throws Exception { sessionAirdResource = new UIResource(designerProject, SESSION_FILE); localSession = designerPerspective.openSessionFromFile(sessionAirdResource, true); <START> diagramToPaste = localSession.getLocalSessionBrowser().perCategory().selectViewpoint(VIEWPOINT_NAME).selectRepresentation(REPRESENTATION_DESCRIPTION_NAME) <END> .selectRepresentationInstance(DIAGRAM_INSTANCE_TO_PASTE, UIDiagramRepresentation.class).open(); diagramToCopy = localSession.getLocalSessionBrowser().perCategory().selectViewpoint(VIEWPOINT_NAME).selectRepresentation(REPRESENTATION_DESCRIPTION_NAME) .selectRepresentationInstance(DIAGRAM_INSTANCE_TO_COPY, UIDiagramRepresentation.class).open(); }</code><technical_language>openRepresentation api method instead. This method sirius API open representation (it is more efficient)</technical_language>

Target:
protected void onSetUpAfterOpeningDesignerPerspective() throws Exception { sessionAirdResource = new UIResource(designerProject, SESSION_FILE); localSession = designerPerspective.openSessionFromFile(sessionAirdResource, true); diagramToPaste = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), REPRESENTATION_DESCRIPTION_NAME, DIAGRAM_INSTANCE_TO_PASTE, DDiagram.class); diagramToCopy = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), REPRESENTATION_DESCRIPTION_NAME, DIAGRAM_INSTANCE_TO_COPY, DDiagram.class); }
Source:
<code>public Mono<Key> createKey(String name, KeyType keyType) { <START> return withContext(context -> createKey(name, keyType, Context.NONE)) <END> .flatMap(keyResponse -> Mono.justOrEmpty(keyResponse.value())); }</code><technical_language>suggestion return withContext(context -> createKey(name, keyType, context))</technical_language>

Target:
public Mono<Key> createKey(String name, KeyType keyType) { return withContext(context -> createKey(name, keyType, context)) .flatMap(FluxUtil::toMono); }
Source:
<code>public Element getSingleChild(String name) { checkNotRemoved(); requireNonNull(name, "Non-null child name required."); for (Element child : asElements(delegate.getChildNodes())) { if (name.equals(child.getName())) { if (child.hasSibling(name)) { throw new XMLTreeException( <START> "Element " + name + " has found more than one child with the name " + name); <END> } return child; } } return null; }</code><technical_language>I drop</technical_language>

Target:
public Element getSingleChild(String name) { checkNotRemoved(); requireNonNull(name, "Non-null child name required."); for (Element child : asElements(delegate.getChildNodes())) { if (name.equals(child.getName())) { if (child.hasSibling(name)) { throw new XMLTreeException( "Element " + name + " has more than one child with the name " + name); } return child; } } return null; }
Source:
<code>public Response threatCatalogue() { ThreatModelingUtils tmu = new ThreatModelingUtils(this.repository); <START> return Response.ok(tmu.getThreatCatalogue()).build(); <END> }</code><technical_language>need create response manually, return tmu.getThreatCataloge();. Jackson & Jersy handle else for automatically</technical_language>

Target:
public List<Threat> threatCatalogue() { ThreatModelingUtils tmu = new ThreatModelingUtils(this.repository); return tmu.getThreatCatalogue(); }
Source:
<code>public void addHook(TrainingHook trainingHook) { <START> <END> }</code><technical_language>TrainingHook *really* fit design here, do want throw UnsupportedOperationException? worried people knowing a no-op here</technical_language>

Target:
public void addHook(TrainingHook trainingHook) { throw new UnsupportedOperationException(); }
Source:
<code>public void throw_exception_if_no_field_by_given_index() { @SuppressWarnings("MagicNumber") <START> final TestMessageField field = new TestMessageField(256); <END> field.getValue(stringValue); }</code><technical_language>do 256 is big enough</technical_language>

Target:
public void throw_exception_if_no_field_by_given_index() { final TestMessageField field = new TestMessageField(Integer.MAX_VALUE); field.getValue(stringValue); }
Source:
<code><START> public List<N> getAllParents(N node) { <END> if (_tree.containsVertex(node) == false) return null; if (isRoot(node)) return null; List<N> parents = new ArrayList<>(); N child = node; N parent; while ((parent = getParent(child)) != null) { parents.add(parent); child = parent; } return new ImmutableList.Builder<N>().addAll(parents).build(); }</code><technical_language>is a method getAllParents(Node ) in a class Tree in name? i.e. is this method necessary, class called "DAG" "Graph" instead</technical_language>

Target:
public List<N> getAllParents(N node) { if (!_tree.containsVertex(node)) return null; if (isRoot(node)) return null; List<N> parents = new ArrayList<>(); N child = node; N parent; while ((parent = getParent(child)) != null) { parents.add(parent); child = parent; } return new ImmutableList.Builder<N>().addAll(parents).build(); }
Source:
<code>private void createProxyControls(final Composite proxyComp) { Label lblConnection = new Label(proxyComp, SWT.WRAP); lblConnection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); lblConnection.setText(Messages.JSchConnectionPage_SelectConnection); fProxyConnectionWidget = new RemoteConnectionWidget(proxyComp, SWT.NONE, null, 0, null); Label lblCommand = new Label(proxyComp, SWT.WRAP); lblCommand.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); lblCommand.setText(Messages.JSchConnectionPage_SelectCommand); fProxyCommandText = new Text(proxyComp, SWT.BORDER); fProxyCommandText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Link link = new Link(proxyComp, SWT.WRAP); final GridData linkLayoutData = new GridData(GridData.FILL_HORIZONTAL); link.setLayoutData(linkLayoutData); <START> final String PREFS_PAGE_ID_NET_PROXY = "org.eclipse.ui.net.NetPreferences"; END> link.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { PreferenceDialog dlg = PreferencesUtil.createPreferenceDialogOn(getShell(), PREFS_PAGE_ID_NET_PROXY, new String[] { PREFS_PAGE_ID_NET_PROXY }, null); dlg.open(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); linkLayoutData.widthHint = 400; link.setText(Messages.JSchConnectionPage_Help); }</code><technical_language>unusual this a local. a private final static field</technical_language>

Target:
private void createProxyControls(final Composite proxyComp) { Label lblConnection = new Label(proxyComp, SWT.WRAP); lblConnection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); lblConnection.setText(Messages.JSchConnectionPage_SelectConnection); fProxyConnectionWidget = new RemoteConnectionWidget(proxyComp, SWT.NONE, null, 0, null); Label lblCommand = new Label(proxyComp, SWT.WRAP); lblCommand.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); lblCommand.setText(Messages.JSchConnectionPage_SelectCommand); fProxyCommandText = new Text(proxyComp, SWT.BORDER); fProxyCommandText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Link link = new Link(proxyComp, SWT.WRAP); final GridData linkLayoutData = new GridData(GridData.FILL_HORIZONTAL); link.setLayoutData(linkLayoutData); link.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { PreferenceDialog dlg = PreferencesUtil.createPreferenceDialogOn(getShell(), PREFS_PAGE_ID_NET_PROXY, new String[] { PREFS_PAGE_ID_NET_PROXY }, null); dlg.open(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); linkLayoutData.widthHint = 400; link.setText(Messages.JSchConnectionPage_Help); }
Source:
<code>private SslSessionData getSslSessionData() { SslSessionData sslSessionData = (SslSessionData)_session.getValue(SslSessionData.ATTR); if (sslSessionData == null) { String cipherSuite = _session.getCipherSuite(); int keySize = SslContextFactory.deduceKeyLength(cipherSuite); X509Certificate[] certs = getCertChain(_request.getHttpChannel().getConnector(), _session); byte[] bytes = _session.getId(); String idStr = TypeUtil.toHexString(bytes); sslSessionData = new SslSessionData(keySize, certs, idStr); _session.putValue(SslSessionData.ATTR, sslSessionData); } <START> return sslSessionData; <END> }</code><technical_language>This method is user of SslSessionData.ATTR. need constant in another class. do beginning of method: String key = SslSessionData.class.getName() key ATTR</technical_language>

Target:
private SslSessionData getSslSessionData() { String key = SslSessionData.class.getName(); SslSessionData sslSessionData = (SslSessionData)_session.getValue(key); if (sslSessionData == null) { String cipherSuite = _session.getCipherSuite(); int keySize = SslContextFactory.deduceKeyLength(cipherSuite); X509Certificate[] certs = getCertChain(_request.getHttpChannel().getConnector(), _session); byte[] bytes = _session.getId(); String idStr = TypeUtil.toHexString(bytes); sslSessionData = new SslSessionData(keySize, certs, idStr); _session.putValue(key, sslSessionData); } return sslSessionData; }
Source:
<code>private ProcessHandler startTestProcess(TestExecutionContext context) { File suiteFile = createSuite(context); if (suiteFile == null) { throw new RuntimeException("Can't create TestNG suite xml file."); } JavaParameters parameters = new JavaParameters(); parameters.setJavaExecutable(System.getProperty("java.home") + "/bin/java"); parameters.setMainClassName("org.testng.CheTestNGLauncher"); String outputDirectory = getOutputDirectory(context); parameters.getParametersList().add("-d", outputDirectory); parameters.setWorkingDirectory(workspacePath + context.getProjectPath()); List<String> classPath = new ArrayList<>(); List<String> resolvedClassPaths = getResolvedClassPaths(context); <START> classPath.addAll(resolvedClassPaths); <END> classPath.add(ClasspathUtil.getJarPathForClass(org.testng.CheTestNG.class)); classPath.add(ClasspathUtil.getJarPathForClass(JCommander.class)); parameters.getClassPath().addAll(classPath); parameters.getParametersList().add("-suiteFile", suiteFile.getAbsolutePath()); if (context.isDebugModeEnable()) { generateDebuggerPort(); parameters.getVmParameters().add("-Xdebug"); parameters .getVmParameters() .add("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=" + getDebugPort()); } CommandLine command = parameters.createCommand(); try { return new ProcessHandler(command.createProcess()); } catch (ExecutionException e) { LOG.error("Can't run TestNG JVM", e); } return null; }</code><technical_language>Personally, I ExecutionException propagate this method instead of returning null</technical_language>

Target:
private ProcessHandler startTestProcess(TestExecutionContext context) throws ExecutionException { File suiteFile = createSuite(context); if (suiteFile == null) { throw new RuntimeException("Can't create TestNG suite xml file."); } JavaParameters parameters = new JavaParameters(); parameters.setJavaExecutable(System.getProperty("java.home") + "/bin/java"); parameters.setMainClassName("org.testng.CheTestNGLauncher"); String outputDirectory = getOutputDirectory(context); parameters.getParametersList().add("-d", outputDirectory); parameters.setWorkingDirectory(workspacePath + context.getProjectPath()); List<String> classPath = new ArrayList<>(); List<String> resolvedClassPaths = getResolvedClassPaths(context); classPath.addAll(resolvedClassPaths); classPath.add(ClasspathUtil.getJarPathForClass(org.testng.CheTestNG.class)); classPath.add(ClasspathUtil.getJarPathForClass(JCommander.class)); parameters.getClassPath().addAll(classPath); parameters.getParametersList().add("-suiteFile", suiteFile.getAbsolutePath()); if (context.isDebugModeEnable()) { generateDebuggerPort(); parameters.getVmParameters().add("-Xdebug"); parameters .getVmParameters() .add("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=" + getDebugPort()); } CommandLine command = parameters.createCommand(); return new ProcessHandler(command.createProcess()); }
Source:
<code>private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) throws InterruptedException { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, <START> clusterManagerAdapter, discoveryServiceCallback);; <END> return discoveryServiceCallback; }</code><technical_language>typo --> ;;</technical_language>

Target:
private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, clusterManagerAdapter, discoveryServiceCallback); replicationDiscoveryService.start(); return discoveryServiceCallback; }
Source:
<code>public static void respond(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) { <START> res.setHeader("Access-Control-Allow-Origin", Configuration.getInstance().getStringProperty(CoreConfig.CORS_ALLOWED_ORIGINS)); <END> if (res.getContent() != null) { setContentLength(res, res.getContent().readableBytes()); } ChannelFuture f = ctx.getChannel().write(res); if (req == null || !isKeepAlive(req)) { f.addListener(ChannelFutureListener.CLOSE); } }</code><technical_language>If invalid, spec, send empty Access-Control-Allow-Origin, put this in if statement? I.e: sends header if config empty configuration</technical_language>

Target:
public static void respond(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) { if (CORS_ENABLED) { res.setHeader("Access-Control-Allow-Origin", CORS_ALLOWED_ORIGINS); } if (res.getContent() != null) { setContentLength(res, res.getContent().readableBytes()); } ChannelFuture f = ctx.getChannel().write(res); if (req == null || !isKeepAlive(req)) { f.addListener(ChannelFutureListener.CLOSE); } }
Source:
<code>protected void operations(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { <START> Map<String, String> changedHandles = Maps.filterEntries(handles, new Predicate<Entry<String, String>>() { <END> @Override public boolean apply(Entry<String, String> entry) { return !entry.getKey().equals(entry.getValue()); } }); if (changedHandles.isEmpty()) { return; } try { refactorMetaContextHandles(changedHandles, monitor); TasksUiPlugin.getTaskActivityMonitor().reloadActivityTime(); } finally { monitor.done(); } }</code><technical_language>handles.entriesSet().stream().filter(doFilter()).findAny()</technical_language>

Target:
protected void operations(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { Map<String, String> changedHandles = handles.entrySet() .stream() .filter(e -> !e.getKey().equals(e.getValue())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); if (changedHandles.isEmpty()) { return; } try { refactorMetaContextHandles(changedHandles, monitor); TasksUiPlugin.getTaskActivityMonitor().reloadActivityTime(); } finally { monitor.done(); } }
Source:
<code>public static WatchDog map(VmWatchdog entity, WatchDog template) { WatchDog model = template == null ? new WatchDog() : template; <START> model.setAction(entity.getAction() == null ? null : entity.getAction().name().toLowerCase()); <END> model.setId(entity.getId().toString()); model.setModel(entity.getModel() == null ? null : entity.getModel().name()); return model; }</code><technical_language>mapping /api/restapi/types/WatchdogAction backend enum</technical_language>

Target:
public static WatchDog map(VmWatchdog entity, WatchDog template) { WatchDog model = template == null ? new WatchDog() : template; if (entity.getAction() != null) { WatchdogAction action = map(entity.getAction(), null); if (action != null) { model.setAction(action.name().toLowerCase()); } } if (entity.getModel() != null) { WatchdogModel wdModel = map(entity.getModel(), null); if (wdModel != null) { model.setModel(wdModel.name().toLowerCase()); } } model.setId(entity.getId().toString()); return model; }
Source:
<code>public boolean equals( Value value ) { <START> if ( value instanceof org.neo4j.values.storable.UTF8StringValue ) <END> { return Arrays.equals( bytes, ((org.neo4j.values.storable.UTF8StringValue) value).bytes ); } else { return super.equals( value ); } }</code><technical_language>strange need a fully qualified name here</technical_language>

Target:
public boolean equals( Value value ) { if ( value instanceof UTF8StringValue ) { return Arrays.equals( bytes, ((org.neo4j.values.storable.UTF8StringValue) value).bytes ); } else { return super.equals( value ); } }
Source:
<code>private List<String> splitToLength(String text, int subStringSize) { <START> List<String> substrings = new ArrayList<String>(text.length() + subStringSize -1 / subStringSize); <END> for (int idx = 0; idx < text.length(); idx += subStringSize) { String substring = text.substring(idx, Math.min(text.length(), idx + subStringSize)); substrings.add(substring); } return substrings; }</code><technical_language>mistake is here. Div operator precedence</technical_language>

Target:
private List<String> splitToLength(String text, int subStringSize) { List<String> substrings = new ArrayList<String>((text.length() + subStringSize -1) / subStringSize); for (int idx = 0; idx < text.length(); idx += subStringSize) { String substring = text.substring(idx, Math.min(text.length(), idx + subStringSize)); substrings.add(substring); } return substrings; }
Source:
<code>private void showSyncOptionDialogWhenLogout() { if (ReadingListDbHelper.instance().getRandomPage() != null) { ReadingListCheckSetupStatusTask checkSetupStatusTask = new ReadingListCheckSetupStatusTask() { @Override <START> public void onFinish(@Nullable Void result) { <END> Prefs.setReadingListsLastSyncTime(null); ReadingListSyncBehaviorDialogs.removeExistListsDialog(getActivity(), () -> logoutAndShowMessage()); } @Override public void onCatch(Throwable caught) { logoutAndShowMessage(); } }; checkSetupStatusTask.execute(); } else { logoutAndShowMessage(); } }</code><technical_language>check for isAdded()</technical_language>

Target:
private void showSyncOptionDialogWhenLogout() { if (ReadingListDbHelper.instance().getRandomPage() != null) { ReadingListCheckSetupStatusTask checkSetupStatusTask = new ReadingListCheckSetupStatusTask() { @Override public void onFinish(@Nullable Void result) { if (!isAdded()) { return; } Prefs.setReadingListsLastSyncTime(null); ReadingListSyncBehaviorDialogs.removeExistListsDialog(getActivity(), () -> logoutAndShowMessage()); } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } logoutAndShowMessage(); } }; checkSetupStatusTask.execute(); } else { logoutAndShowMessage(); } }
Source:
<code>static Scheduler callRequireNonNull(Callable<Scheduler> s) { try { return ObjectHelper.requireNonNull(s.call(), "Scheduler Callable result can't be null"); } catch (Throwable ex) { <START> throw ExceptionHelper.wrapOrThrow(ex); <END> } }</code><technical_language>Inline this implementation</technical_language>

Target:
static Scheduler callRequireNonNull(Callable<Scheduler> s) { try { Scheduler scheduler = s.call(); if (scheduler == null) { throw new NullPointerException("Scheduler Callable returned null"); } return scheduler; } catch (Throwable ex) { throw Exceptions.propagate(ex); } }
Source:
<code>public void testParallelNoThrottle() throws Exception { final int numThreads = 50; final LearnerSyncThrottler throttler = <START> new LearnerSyncThrottler(numThreads, syncType); <END> ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); final CountDownLatch threadStartLatch = new CountDownLatch(numThreads); final CountDownLatch syncProgressLatch = new CountDownLatch(numThreads); List<Future<Boolean>> results = new ArrayList<Future<Boolean>>(numThreads); for (int i = 0; i < numThreads; i++) { results.add(threadPool.submit(new Callable<Boolean>() { @Override public Boolean call() { threadStartLatch.countDown(); try { threadStartLatch.await(); throttler.beginSync(false); syncProgressLatch.countDown(); syncProgressLatch.await(); throttler.endSync(); } catch (Exception e) { return false; } return true; } })); } for (Future<Boolean> result : results) { Assert.assertTrue(result.get()); } }</code><technical_language>Please shutdown this pool in a finally block</technical_language>

Target:
public void testParallelNoThrottle() { final int numThreads = 50; final LearnerSyncThrottler throttler = new LearnerSyncThrottler(numThreads, syncType); ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); final CountDownLatch threadStartLatch = new CountDownLatch(numThreads); final CountDownLatch syncProgressLatch = new CountDownLatch(numThreads); List<Future<Boolean>> results = new ArrayList<Future<Boolean>>(numThreads); for (int i = 0; i < numThreads; i++) { results.add(threadPool.submit(new Callable<Boolean>() { @Override public Boolean call() { threadStartLatch.countDown(); try { threadStartLatch.await(); throttler.beginSync(false); syncProgressLatch.countDown(); syncProgressLatch.await(); throttler.endSync(); } catch (Exception e) { return false; } return true; } })); } try { for (Future<Boolean> result : results) { Assert.assertTrue(result.get()); } } catch (Exception e){ } finally { threadPool.shutdown(); } }
Source:
<code>protected final void assignArguments(List<?> args, Env e) { for (int i=0; i< Math.min(args.size(),parameters.size()); i++) { <START> Class argClass = args.get(i) != null ? args.get(i).getClass() : Object.class; <END> e.declareVariable(argClass, parameters.get(i)); e.setLocalVariable(parameters.get(i), args.get(i)); } }</code><technical_language>This is wrong. do a invocation declared type is supposed be. I need Object in cases</technical_language>

Target:
protected final void assignArguments(List<?> args, Env e) { for (int i=0; i< Math.min(args.size(),parameters.size()); i++) { e.declareVariable(Object.class, parameters.get(i)); e.setLocalVariable(parameters.get(i), args.get(i)); } }
Source:
<code><START> protected boolean isAlternativePresent(final String alternative) { <END> if (alternatives == null) { return false; } for (String alt : alternatives) { if (alt.equals(alternative)) { return true; } } return false; }</code><technical_language>This private. similar isFlagPresent method private too, released protected I want reduce visibility. this is new lock down</technical_language>

Target:
private boolean isAlternativePresent(final String alternative) { if (alternatives == null) { return false; } for (String alt : alternatives) { if (alt.equals(alternative)) { return true; } } return false; }
Source:
<code>public void testShowColumnsFromPartitions() { String tableName = "test_show_columns_from_partitions"; @Language("SQL") String createTable = "" + "CREATE TABLE " + tableName + " " + "(" + " foo VARCHAR," + " part1 BIGINT," + " part2 VARCHAR" + ") " + "WITH (" + "partitioned_by = ARRAY[ 'part1', 'part2' ]" + ") "; assertUpdate(getSession(), createTable); TableMetadata tableMetadata = getTableMetadata(catalog, TPCH_SCHEMA, tableName); <START> assertEquals(tableMetadata.getMetadata().getProperties().get(PARTITIONED_BY_PROPERTY), ImmutableList.of("part1", "part2")); <END> assertQuery( getSession(), "SHOW COLUMNS FROM \"" + tableName + "$partitions\"", "VALUES ('part1', 'bigint', '', ''), ('part2', 'varchar', '', '')"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"$partitions\"", ".*Table 'hive.tpch.\\$partitions' does not exist"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"orders$partitions\"", ".*Table 'hive.tpch.orders\\$partitions' does not exist"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"blah$partitions\"", ".*Table 'hive.tpch.blah\\$partitions' does not exist"); }</code><technical_language>redundant</technical_language>

Target:
public void testShowColumnsFromPartitions() { String tableName = "test_show_columns_from_partitions"; @Language("SQL") String createTable = "" + "CREATE TABLE " + tableName + " " + "(" + " foo VARCHAR," + " part1 BIGINT," + " part2 VARCHAR" + ") " + "WITH (" + "partitioned_by = ARRAY[ 'part1', 'part2' ]" + ") "; assertUpdate(getSession(), createTable); assertQuery( getSession(), "SHOW COLUMNS FROM \"" + tableName + "$partitions\"", "VALUES ('part1', 'bigint', '', ''), ('part2', 'varchar', '', '')"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"$partitions\"", ".*Table 'hive.tpch.\\$partitions' does not exist"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"orders$partitions\"", ".*Table 'hive.tpch.orders\\$partitions' does not exist"); assertQueryFails( getSession(), "SHOW COLUMNS FROM \"blah$partitions\"", ".*Table 'hive.tpch.blah\\$partitions' does not exist"); }
Source:
<code>protected void setSplitterPosition(int leftWidth, int rightWidth) { try { if (lockSplitter.acquire()) { <START> double total = leftWidth + rightWidth; <END> if (total > 0) { double d = leftWidth / total; getSwingContainer().setDividerLocation(d); getSwingContainer().setResizeWeight(d); } } } finally { lockSplitter.release(); } }</code><technical_language>leftWidth negative</technical_language>

Target:
protected void setSplitterPosition(int leftWidth, int rightWidth) { if (leftWidth < 0 || rightWidth < 0) { return; } try { if (lockSplitter.acquire()) { double total = leftWidth + rightWidth; if (total > 0) { double d = leftWidth / total; getSwingContainer().setDividerLocation(d); getSwingContainer().setResizeWeight(d); } } } finally { lockSplitter.release(); } }
Source:
<code>public void setReader(final Reader reader) { if(! closed.get()) { if (reader == null) { readerCaller = null; } else { synchronized(readerLock) { readerCaller = () -> reader.onRead(this); if (this.getReadBufferSize() > 0) { callReader(false); } else { <START> callReader(false); <END> } } } } }</code><technical_language>This sense me? If this is expected, a conditional all</technical_language>

Target:
public void setReader(final Reader reader) { if(! closed.get()) { if (reader == null) { readerCaller = null; } else { synchronized(readerLock) { readerCaller = () -> reader.onRead(this); if (this.getReadBufferSize() > 0) { callReader(false); } } } } }
Source:
<code>public int hashCode() { return Objects.hash( id, hostName, consoleAddress, name, otpValidity, pmEnabled, pmKdumpDetection, port, protocol, sshPort, sshUsername, serverSslEnabled, uniqueId, clusterId, vdsStrength, vdsType, disablePowerManagementPolicy, hostProviderId, <START> hostProviderId, <END> currentKernelCmdline, kernelCmdlineParsable, lastStoredKernelCmdline, kernelCmdlineIommu, kernelCmdlineKvmNested, kernelCmdlinePciRealloc, kernelCmdlineUnsafeInterrupts ); }</code><technical_language>a mistake, right</technical_language>

Target:
public int hashCode() { return Objects.hash( id, hostName, consoleAddress, name, otpValidity, pmEnabled, pmKdumpDetection, port, protocol, sshPort, sshUsername, serverSslEnabled, uniqueId, clusterId, vdsStrength, vdsType, disablePowerManagementPolicy, hostProviderId, currentKernelCmdline, kernelCmdlineParsable, lastStoredKernelCmdline, kernelCmdlineIommu, kernelCmdlineKvmNested, kernelCmdlinePciRealloc, kernelCmdlineUnsafeInterrupts ); }
Source:
<code>public void open(final ProjectDiagram diagram) { final Graph graph = diagram.getGraph(); final AutomaticLayoutService.Layout layout = layoutService.getLayout(graph); this.graphLayout.applyLayout(layout, graph); super.open(diagram); <START> } <END></code><technical_language>I miss coverage in DMNDiagramEditorTest class</technical_language>

Target:
public void open(final ProjectDiagram diagram) { this.layoutHelper.applyLayout(diagram.getGraph()); super.open(diagram); }
Source:
<code>public DataStallDetectionStats build() { return new DataStallDetectionStats(mCellularInfo, mWifiInfo, <START> mDnsReturnCode.stream().mapToInt(i -> i).toArray(), <END> mDnsTimeStamp.stream().mapToLong(i -> i).toArray(), mEvaluationType, mNetworkType, mSeqNo); }</code><technical_language>this path is performance-sensitive, nice in NetworkStackUtils similar com.android.internal.util.ArrayUtils.convertToIntArray, stream overhead</technical_language>

Target:
public DataStallDetectionStats build() { return new DataStallDetectionStats(mCellularInfo, mWifiInfo, NetworkStackUtils.convertToIntArray(mDnsReturnCode), NetworkStackUtils.convertToLongArray(mDnsTimeStamp), mEvaluationType, mNetworkType); }
Source:
<code>private void createEmptyFolderUntracked() throws Exception { File path = new File(db.getWorkTree(), UNTRACKED_FOLDER); assertTrue(path.mkdir()); <START> assertTrue(path.isDirectory()); <END> }</code><technical_language>Replace asserts FileUtils.mkDirs</technical_language>

Target:
private void createEmptyFolderUntracked() throws Exception { File path = new File(db.getWorkTree(), UNTRACKED_FOLDER); FileUtils.mkdir(path); }
Source:
<code>public List<JudgmentData.Judge> toJudges(List<Judge> judges) { if(judges == null) judges = Collections.emptyList(); <START> <END> List<JudgmentData.Judge> judgesView = new ArrayList<>(); for(Judge judge : judges){ List<Judge.JudgeRole> judgeRoles = judge.getSpecialRoles(); if(judgeRoles == null) { judgeRoles = Collections.emptyList(); } List<String> rolesNames = judgeRoles.stream() .map(role -> role.name()) .collect(Collectors.toList()); JudgmentData.Judge judgeView = new JudgmentData.Judge(); judgeView.setName(judge.getName()); judgeView.setSpecialRoles(rolesNames); judgesView.add(judgeView); } return judgesView; }</code><technical_language>Missing {}</technical_language>

Target:
public List<JudgmentData.Judge> toJudges(List<Judge> judges) { if(judges == null) { judges = Collections.emptyList(); } List<JudgmentData.Judge> judgesView = new ArrayList<>(); for(Judge judge : judges){ List<Judge.JudgeRole> judgeRoles = judge.getSpecialRoles(); if(judgeRoles == null) { judgeRoles = Collections.emptyList(); } List<String> rolesNames = judgeRoles.stream() .map(role -> role.name()) .collect(Collectors.toList()); JudgmentData.Judge judgeView = new JudgmentData.Judge(); judgeView.setName(judge.getName()); judgeView.setSpecialRoles(rolesNames); judgesView.add(judgeView); } return judgesView; }
Source:
<code>protected void initQcowVersionForDisks(Guid imageGroupId) { try { <START> List<DiskImage> diskVolumes = diskImageDao.getAllSnapshotsForImageGroup(imageGroupId); for (DiskImage volume : diskVolumes) { setQcowCompat(volume); } <END> } catch (Exception e) { log.error("Could not set qcow compat version for imported disk"); } }</code><technical_language>forEach</technical_language>

Target:
protected void initQcowVersionForDisks(Guid imageGroupId) { List<DiskImage> diskVolumes = diskImageDao.getAllSnapshotsForImageGroup(imageGroupId); diskVolumes.stream().forEach(volume -> { try { setQcowCompat(volume); } catch (Exception e) { log.error("Could not set qcow compat version for disk '{} with id '{}/{}'", volume.getDiskAlias(), volume.getId(), volume.getImageId()); } }); }
Source:
<code>private void updateBricksFromHost() { VDS selectedServer = getServers().getSelectedItem(); AsyncDataProvider.getInstance().getUnusedBricksFromServer(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { List<StorageDevice> bricks = (List<StorageDevice>) returnValue; List<String> lvNames = new ArrayList<String>(); for (StorageDevice brick : bricks) { if (brick.getMountPoint() != null && !brick.getMountPoint().isEmpty()) { lvNames.add(brick.getMountPoint()); } <START> else { <END> lvNames.add("None - " + brick.getName()); } } getBricksFromServer().setItems(lvNames); } }), selectedServer.getId()); }</code><technical_language>this happen</technical_language>

Target:
private void updateBricksFromHost() { VDS selectedServer = getServers().getSelectedItem(); AsyncDataProvider.getInstance().getUnusedBricksFromServer(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { List<StorageDevice> bricks = (List<StorageDevice>) returnValue; List<String> lvNames = new ArrayList<String>(); for (StorageDevice brick : bricks) { if (brick.getMountPoint() != null && !brick.getMountPoint().isEmpty()) { lvNames.add(brick.getMountPoint()); } } getBricksFromServer().setItems(lvNames); } }), selectedServer.getId()); }
Source:
<code>public Map<String, String> getSchema(GetSchemaRequest request, EndpointPluginContext pluginContext) throws SQLException, InstantiationException, IllegalAccessException { JDBCDriverShim driverShim = loadPluginClassAndGetDriver(request, pluginContext); try { Connection connection = getConnection(request.connectionString, request.user, request.password); <START> Map<String, String> resultSchema = new HashMap<>(); <END> try { Statement statement = connection.createStatement(); String query = request.importQuery; statement.setMaxRows(1); ResultSetMetaData resultSetMetaData = statement.executeQuery(query).getMetaData(); for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) { resultSchema.put(resultSetMetaData.getColumnName(i), resultSetMetaData.getColumnTypeName(i)); } } finally { connection.close(); } return resultSchema; } catch (SQLException e) { LOG.error("Exception while trying to get schema in a database for query {}.", request.importQuery, e); throw Throwables.propagate(e); } finally { DBUtils.deregisterShim(driverShim); } }</code><technical_language>a HashMap, a LinkedHashMap ordering of insertion is maintained (which is ordering of fields in table)</technical_language>

Target:
public Schema getSchema(GetSchemaRequest request, EndpointPluginContext pluginContext) throws SQLException, InstantiationException, IllegalAccessException, BadRequestException { DriverCleanup driverCleanup = loadPluginClassAndGetDriver(request, pluginContext); try { try (Connection connection = getConnection(request.connectionString, request.user, request.password)) { Statement statement = connection.createStatement(); statement.setMaxRows(1); ResultSet resultSet = statement.executeQuery(request.query); return Schema.recordOf("outputSchema", DBUtils.getSchemaFields(resultSet)); } } catch (SQLSyntaxErrorException e) { throw new BadRequestException(e.getMessage()); } finally { driverCleanup.destroy(); } }
Source:
<code>public String processElement(ParserContext handlerManager, Element element) throws ConfigurationException { <START> String executeBefore = element.getTextContent(); <END> return executeBefore; }</code><technical_language>Need throw a validation exception if this is missing. (Like existing handlers.)</technical_language>

Target:
public String processElement(ParserContext handlerManager, Element element) throws ConfigurationException { String executeBefore = element.getTextContent(); if(executeBefore == null || executeBefore.equals("")) { throw new WindupXMLRulesetParsingException("The '" + EXECUTE_BEFORE_ELEMENT + "' must contain non-empty text value"); } return executeBefore; }
Source:
<code>@Override Bitmap decode(Request data) throws IOException { <START> <END> String part = data.uri.getSchemeSpecificPart(); if(!part.startsWith(MIME_PREFIX)) throw new IOException("Malformed data uri"); part = part.substring(MIME_PREFIX.length()); if(!part.matches("^(gif|jpe?g|png);base64,.[A-Za-z0-9+/=]*$")) throw new IOException("Unsupported content type"); part = part.substring(part.indexOf(SPLITTER) + SPLITTER.length()); return decodeBase64(part); }</code><technical_language>remove empty line</technical_language>

Target:
@Override Bitmap decode(Request data) throws IOException { String part = data.uri.getSchemeSpecificPart(); if (!part.startsWith(MIME_PREFIX)) { throw new IOException("Malformed data uri"); } part = part.substring(MIME_PREFIX.length()); if (!part.matches("^(gif|jpe?g|png);base64,.[A-Za-z0-9+/=]*$")) { throw new IOException("Unsupported content type"); } part = part.substring(part.indexOf(SPLITTER) + SPLITTER.length()); return decodeBase64(part); }
Source:
<code>public <T extends Annotation> T getConfig(FrameworkMethod method, Class<T> type) { <START> if (method != null) { <END> T config = method.getAnnotation(type); if (config != null) { return config; } } return getConfig(type); }</code><technical_language>In cases happen</technical_language>

Target:
public <T extends Annotation> T getConfig(FrameworkMethod method, Class<T> type) { T config = method.getAnnotation(type); if (config != null) { return config; } return getConfig(type); }
Source:
<code>private void printUsingRegex(String regex) { for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger .hasMoreElements();) { Logger log = logger.nextElement(); if (log.getName().matches(regex)) { stdout.println(log.getName() + <START> " : " + <END> log.getEffectiveLevel()); } } }</code><technical_language>": "</technical_language>

Target:
private void printUsingRegex(String regex) { if (regex.startsWith("^")) { regex = regex.substring(1); if (regex.endsWith("$") && !regex.endsWith("\\$")) { regex = regex.substring(0, regex.length() - 1); } } final RunAutomaton a = new RunAutomaton(new RegExp(regex).toAutomaton()); for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger .hasMoreElements();) { Logger log = logger.nextElement(); if (a.run(log.getName())) { stdout.println(log.getName() + ": " + log.getEffectiveLevel()); } } }