auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected BlockWriteRequestContext createRequestContext(alluxio.grpc.WriteRequest msg) throws Exception { <START> BlockWriteRequestContext context = mBlockWriteHandler.createRequestContext(msg); <END> BlockWriteRequest request = context.getRequest(); Preconditions.checkState(request.hasCreateUfsBlockOptions()); context.setWritingToLocal(!request.getCreateUfsBlockOptions().getFallback()); if (context.isWritingToLocal()) { mWorker.createBlockRemote(request.getSessionId(), request.getId(), mStorageTierAssoc.getAlias(request.getTier()), request.getMediumType(), FILE_BUFFER_SIZE); } return context; }</code><technical_language>In BlockWriteHandler#createRequestContext() calls mWorker.createBlockRemote, in this method call mWorker.createBlockRemote. a problem? Instead, initialize counters correctly in this method</technical_language>

Target:
protected BlockWriteRequestContext createRequestContext(alluxio.grpc.WriteRequest msg) throws Exception { BlockWriteRequestContext context = new BlockWriteRequestContext(msg, FILE_BUFFER_SIZE); if (mDomainSocketEnabled) { context.setCounter(MetricsSystem.counter(WorkerMetrics.BYTES_WRITTEN_DOMAIN)); context.setMeter(MetricsSystem.meter(WorkerMetrics.BYTES_WRITTEN_DOMAIN_THROUGHPUT)); } else { context.setCounter(MetricsSystem.counter(WorkerMetrics.BYTES_WRITTEN_ALLUXIO)); context.setMeter(MetricsSystem.meter(WorkerMetrics.BYTES_WRITTEN_ALLUXIO_THROUGHPUT)); } BlockWriteRequest request = context.getRequest(); Preconditions.checkState(request.hasCreateUfsBlockOptions()); context.setWritingToLocal(!request.getCreateUfsBlockOptions().getFallback()); if (context.isWritingToLocal()) { mWorker.createBlockRemote(request.getSessionId(), request.getId(), mStorageTierAssoc.getAlias(request.getTier()), request.getMediumType(), FILE_BUFFER_SIZE); } return context; }
Source:
<code>static void runTasks(ModLoadingStage fromStage, Consumer<List<ModLoadingException>> errorHandler) { raisedExceptions.clear(); if (taskQueue.isEmpty()) return; LOGGER.info(LOADING, "Dispatching synchronous work after {}: jobs", fromStage, taskQueue.size()); StopWatch globalTimer = StopWatch.createStarted(); while (!taskQueue.isEmpty()) { TaskInfo taskinfo = taskQueue.poll(); Stopwatch timer = Stopwatch.createStarted(); taskinfo.task.run(); timer.stop(); <START> if (timer.elapsed(TimeUnit.SECONDS) > 5) { <END> LOGGER.warn(LOADING, "Mod '{}' took to run a deferred task.", taskinfo.owner.getDisplayName(), timer); } } LOGGER.info(LOADING, "Synchronous work queue completed in {}", globalTimer); errorHandler.accept(raisedExceptions); }</code><technical_language>1 more sufficient for deferred jobs</technical_language>

Target:
static void runTasks(ModLoadingStage fromStage, Consumer<List<ModLoadingException>> errorHandler) { raisedExceptions.clear(); if (taskQueue.isEmpty()) return; LOGGER.info(LOADING, "Dispatching synchronous work after {}: jobs", fromStage, taskQueue.size()); StopWatch globalTimer = StopWatch.createStarted(); while (!taskQueue.isEmpty()) { TaskInfo taskinfo = taskQueue.poll(); Stopwatch timer = Stopwatch.createStarted(); taskinfo.task.run(); timer.stop(); if (timer.elapsed(TimeUnit.SECONDS) >= 1) { LOGGER.warn(LOADING, "Mod '{}' took to run a deferred task.", taskinfo.owner.getModId(), timer); } } LOGGER.info(LOADING, "Synchronous work queue completed in {}", globalTimer); errorHandler.accept(raisedExceptions); }
Source:
<code>protected void executeQueryCommand() { List<Guid> ids = new ArrayList<Guid>(); ids.add(getUser().getUserId()); ids.addAll(GuidUtils.getGuidListFromString(getUser().getGroupIds())); List<Quota> quotaList = new ArrayList<Quota>(); for (Guid id : ids) { quotaList.addAll(getDbFacade() .getQuotaDao() <START> .getQuotaByAdElementId(id, null)); <END> } getQueryReturnValue().setReturnValue(QuotaManager.getInstance().generatePerUserUsageReport(quotaList)); }</code><technical_language>a fan of a db query a foreach. please consider replacing a single SP a user_id</technical_language>

Target:
protected void executeQueryCommand() { List<Quota> quotaList = getDbFacade().getQuotaDao().getQuotaByAdElementId(getUser().getUserId(), null, true); getQueryReturnValue().setReturnValue(QuotaManager.getInstance().generatePerUserUsageReport(quotaList)); }
Source:
<code>public static int getSessionTimeout() { <START> return Math.max(getInt(R.string.preference_key_session_timeout, SessionFunnel.DEFAULT_SESSION_TIMEOUT), 1); <END> }</code><technical_language>I tie default source. Consider moving min well</technical_language>

Target:
public static int getSessionTimeout() { return Math.max(getInt(R.string.preference_key_session_timeout, SessionFunnel.DEFAULT_SESSION_TIMEOUT), SessionFunnel.MIN_SESSION_TIMEOUT); }
Source:
<code>public void resolveArgumentWhenParameterTypeOAuth2AuthorizedClientAndCurrentAuthenticationNullThenThrowIllegalStateException() { this.authentication = null; MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); assertThatThrownBy(() -> resolveArgument(methodParameter)) .isInstanceOf(IllegalStateException.class) .hasMessage("Unable to resolve the Authorized Client with registration identifier \"client1\". " + <START> "An \"authenticated\" or \"anonymous\" request is required. " + <END> "To allow for anonymous access, ensure ServerHttpSecurity.anonymous() is configured."); }</code><technical_language>I this changed support anonymous</technical_language>

Target:
public void resolveArgumentWhenParameterTypeOAuth2AuthorizedClientAndCurrentAuthenticationNullThenThrowIllegalStateException() { this.authentication = null; MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); assertThatThrownBy(() -> resolveArgument(methodParameter)) .isInstanceOf(IllegalStateException.class) .hasMessage("Unable to resolve the Authorized Client with registration identifier \"client1\". " + "An \"authenticated\" or \"unauthenticated\" session is required. " + "To allow for unauthenticated access, ensure ServerHttpSecurity.anonymous() is configured."); }
Source:
<code>public GoalConflictMessage updateLatestGoalConflictMessageForUser(GoalConflictMessage message, <START> MessageDestinationDTO destination) <END> { Message.getRepository().save(message); return message; }</code><technical_language>This way, need destination anymore, right</technical_language>

Target:
public GoalConflictMessage updateLatestGoalConflictMessageForUser(GoalConflictMessage message, MessageDestinationDTO destination) { return message; }
Source:
<code>public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException(){ idTokenDecoderFactory.setJwtValidatorFactory(null); <START> idTokenDecoderFactory.createDecoder(registration.build()); <END> }</code><technical_language>Please remove this line get called</technical_language>

Target:
public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException(){ assertThatThrownBy(()-> idTokenDecoderFactory.setJwtValidatorFactory(null)) .isInstanceOf(IllegalArgumentException.class); }
Source:
<code>public EmbeddedSubprocessExecutionSet(final @MapsTo("onEntryAction") OnEntryAction onEntryAction, final @MapsTo("onExitAction") OnExitAction onExitAction, final @MapsTo("isAsync") IsAsync isAsync, final @MapsTo("slaDueDate") SLADueDate slaDueDate) { <START> super(isAsync, slaDueDate); <END> this.onEntryAction = onEntryAction; this.onExitAction = onExitAction; }</code><technical_language>HashCode Equality test missing for this class</technical_language>

Target:
public EmbeddedSubprocessExecutionSet(final @MapsTo("onEntryAction") OnEntryAction onEntryAction, final @MapsTo("onExitAction") OnExitAction onExitAction, final @MapsTo("isAsync") IsAsync isAsync, final @MapsTo("slaDueDate") SLADueDate slaDueDate) { super(slaDueDate); this.onEntryAction = onEntryAction; this.onExitAction = onExitAction; this.isAsync = isAsync; }
Source:
<code>public HashMap<String, String> getHeaders() { HashMap<String, String> headers = new HashMap<String, String>(); <START> Log.e("X-AUTH-TOKEN", preferences.getString("authentication_token", "none")); <END> Log.e("X-AUTH-EMAIL", preferences.getString("email", "none")); headers.put("X-AUTH-TOKEN", preferences.getString("authentication_token", "none")); headers.put("X-AUTH-EMAIL", preferences.getString("email", "none")); return headers; }</code><technical_language>remove if for debugging</technical_language>

Target:
public HashMap<String, String> getHeaders() { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("X-AUTH-TOKEN", preferences.getString("authentication_token", "none")); headers.put("X-AUTH-EMAIL", preferences.getString("email", "none")); return headers; }
Source:
<code>protected boolean isPopulate() { List<String> populates = httpHeaders.getRequestHeader(POPULATE); if (populates != null && populates.size() > 0) { <START> return Boolean.valueOf(populates.get(0)); <END> } else { return false; } }</code><technical_language>please add .booleanValue() save boxing</technical_language>

Target:
protected boolean isPopulate() { List<String> populates = httpHeaders.getRequestHeader(POPULATE); if (populates != null && populates.size() > 0) { return Boolean.valueOf(populates.get(0)).booleanValue(); } else { return false; } }
Source:
<code>public final void init() { sessionIdGenerator.setSessionIdLength(SESSION_ID_LENGTH); Map<String, Map<String, Session>> sessions = loadSessions(); sessionExpiryChecker = Executors.newScheduledThreadPool(1); sessionExpiryChecker.scheduleAtFixedRate(() -> <START> sessions.values().forEach(entry -> entry.values().parallelStream() <END> .filter(session -> (System.currentTimeMillis() - session.getLastAccessedTime() >= session.getMaxInactiveInterval() * 60 * 1000)) .forEach(Session::invalidate)), 30, 30, TimeUnit.SECONDS); }</code><technical_language>this create a NPE in some cases, DefaultSessionManager</technical_language>

Target:
public final void init() { sessionIdGenerator.setSessionIdLength(SESSION_ID_LENGTH); Map<String, Map<String, Session>> sessions = loadSessions(); sessionExpiryChecker = Executors.newScheduledThreadPool(1); if (sessions != null) { sessionExpiryChecker.scheduleAtFixedRate(() -> sessions.values().forEach(entry -> entry.values().parallelStream() .filter(session -> (System.currentTimeMillis() - session.getLastAccessedTime() >= session.getMaxInactiveInterval() * 60 * 1000)) .forEach(Session::invalidate)), 30, 30, TimeUnit.SECONDS); } }
Source:
<code>public Configuration createCache(String cacheName, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) { validateFlags(flags); try { CacheState state = new CacheState(parserRegistry.serialize(cacheName, configuration), flags); <START> getStateCache().put(new ScopedState(CACHE_SCOPE, cacheName), state); <END> return configuration; } catch (Exception e) { throw log.configurationSerializationFailed(cacheName, configuration, e); } }</code><technical_language>putIfAbsent()</technical_language>

Target:
public Configuration createCache(String cacheName, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) { validateFlags(flags); try { CacheState state = new CacheState(parserRegistry.serialize(cacheName, configuration), flags); getStateCache().putIfAbsent(new ScopedState(CACHE_SCOPE, cacheName), state); return configuration; } catch (Exception e) { throw log.configurationSerializationFailed(cacheName, configuration, e); } }
Source:
<code>private String getSubmitter(String documentId) { String submitterPrincipalId = null; String principalId = workflowDocumentService.getRoutedByPrincipalIdByDocumentId(documentId); List<ActionTaken> actionTakenDTOs = workflowDocumentService.getActionsTaken(documentId); for (ActionTaken actionTaken : actionTakenDTOs) { <START> if (principalId.equals(actionTaken.getPrincipalId())) { <END> submitterPrincipalId = principalId; } } return submitterPrincipalId; }</code><technical_language>I suggest this principalId comparison in a null-safe way</technical_language>

Target:
private String getSubmitter(String documentId) { String submitterPrincipalId = null; String principalId = workflowDocumentService.getRoutedByPrincipalIdByDocumentId(documentId); List<ActionTaken> actionTakenDTOs = workflowDocumentService.getActionsTaken(documentId); for (ActionTaken actionTaken : actionTakenDTOs) { if (StringUtils.equals(principalId, actionTaken.getPrincipalId())) { submitterPrincipalId = principalId; } } return submitterPrincipalId; }
Source:
<code>public static WebArchive createWebArchiveNoGw() { <START> logger.info("Packaging Test App"); <END> WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = ShrinkWrapMaven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + Version.getVersion()).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.delete("/WEB-INF/classes/application.conf"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("restcomm_for_SMSEndpointTest.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_pushNotificationServer", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); archive.addAsWebResource("dial-client-entry_wActionUrl.xml"); logger.info("Packaged Test App"); return archive; }</code><technical_language>call reconfigurePorts here. new utility ports mapped allow parallel testing in <LINK_0></technical_language>

Target:
public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm_for_SMSEndpointTest.xml", "restcomm.script_pushNotificationServer", replacements); }
Source:
<code>public void reauthentication() { ((GenericAccount)account).setId(USER_ID); StudyParticipant participant = new StudyParticipant.Builder().withEmail(RECIPIENT_EMAIL).build(); doReturn(CONSENTED_STATUS_MAP).when(consentService).getConsentStatuses(any()); doReturn(account).when(accountDao).reauthenticate(study, REAUTH_REQUEST); doReturn(participant).when(participantService).getParticipant(study, account, false); <START> service.reauthenticate(study, CONTEXT, REAUTH_REQUEST); <END> verify(accountDao).reauthenticate(study, REAUTH_REQUEST); verify(cacheProvider).removeSessionByUserId(USER_ID); verify(cacheProvider).setUserSession(sessionCaptor.capture()); UserSession captured = sessionCaptor.getValue(); assertEquals(RECIPIENT_EMAIL, captured.getParticipant().getEmail()); }</code><technical_language>Verify returned session contains reauthToken? Do need this test for signIn emailSignIn</technical_language>

Target:
public void reauthentication() { ((GenericAccount)account).setId(USER_ID); account.setReauthToken(REAUTH_TOKEN); StudyParticipant participant = new StudyParticipant.Builder().withEmail(RECIPIENT_EMAIL).build(); doReturn(CONSENTED_STATUS_MAP).when(consentService).getConsentStatuses(any()); doReturn(account).when(accountDao).reauthenticate(study, REAUTH_REQUEST); doReturn(participant).when(participantService).getParticipant(study, account, false); UserSession session = service.reauthenticate(study, CONTEXT, REAUTH_REQUEST); assertEquals(RECIPIENT_EMAIL, session.getParticipant().getEmail()); assertEquals(REAUTH_TOKEN, session.getReauthToken()); verify(accountDao).reauthenticate(study, REAUTH_REQUEST); verify(cacheProvider).removeSessionByUserId(USER_ID); verify(cacheProvider).setUserSession(sessionCaptor.capture()); UserSession captured = sessionCaptor.getValue(); assertEquals(RECIPIENT_EMAIL, captured.getParticipant().getEmail()); assertEquals(REAUTH_TOKEN, captured.getReauthToken()); }
Source:
<code>public void noTrailingSlashesInTarEntryNames() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("mappable-resource/test-resource.txt"); <START> final TarArchiveInputStream tais = intoTarArchive((taos) -> { <END> mountableFile.transferTo(taos, "/some/path.txt"); mountableFile.transferTo(taos, "/path.txt"); mountableFile.transferTo(taos, "path.txt"); }); ArchiveEntry entry; while ((entry = tais.getNextEntry()) != null) { assertFalse("no entries should have a trailing slash", entry.getName().endsWith("/")); } }</code><technical_language>@Cleanup</technical_language>

Target:
public void noTrailingSlashesInTarEntryNames() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("mappable-resource/test-resource.txt"); @Cleanup final TarArchiveInputStream tais = intoTarArchive((taos) -> { mountableFile.transferTo(taos, "/some/path.txt"); mountableFile.transferTo(taos, "/path.txt"); mountableFile.transferTo(taos, "path.txt"); }); ArchiveEntry entry; while ((entry = tais.getNextEntry()) != null) { assertFalse("no entries should have a trailing slash", entry.getName().endsWith("/")); } }
Source:
<code>public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next() <START> .publishOn(scheduler); <END> }</code><technical_language>I noticed this in other places, do publishOn(scheduler)? reached user code yet, need perform work scheduler in case is blocking</technical_language>

Target:
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); }
Source:
<code>public void startTestFor(Activity activity) { <START> Theme theme = new Random().nextBoolean() ? Theme.BLUE : Theme.WHITE; <END> activity.getWindow().setBackgroundDrawable(new ColorDrawable(theme.backgroundColor)); imageView = createImageView(activity, theme); getParent(activity).addView(imageView); explosionField = ExplosionField.attach2Window(activity); delayInitialAnimation(); delayExplosion(); }</code><technical_language>NovodaActivity.RANDOM</technical_language>

Target:
public void startTestFor(Activity activity) { Theme theme = NovodaActivity.RANDOM.nextBoolean() ? Theme.BLUE : Theme.WHITE; setBackground(activity, theme); imageView = createImageView(activity, theme); getParent(activity).addView(imageView); explosionField = ExplosionField.attach2Window(activity); delayInitialAnimation(); delayExplosion(); }
Source:
<code>protected void buildVmCD() { Map<String, Object> struct; boolean hasPayload = vm.getVmPayload() != null && vm.getVmPayload().getType() == VmDeviceType.CDROM; if (hasPayload) { VmDevice vmDevice = new VmDevice(new VmDeviceId(Guid.newGuid(), vm.getId()), VmDeviceGeneralType.DISK, VmDeviceType.CDROM.getName(), <START> "", <END> 0, vm.getVmPayload().getSpecParams(), true, true, true, "", null, null, null); struct = new HashMap<String, Object>(); addCdDetails(vmDevice, struct, vm); addDevice(struct, vmDevice, ""); } if (vm.isRunOnce() && !StringUtils.isEmpty(vm.getCdPath())) { VmDevice vmDevice = new VmDevice(new VmDeviceId(Guid.newGuid(), vm.getId()), VmDeviceGeneralType.DISK, VmDeviceType.CDROM.getName(), "", 0, null, true, true, true, "", null, null, null); struct = new HashMap<String, Object>(); addCdDetails(vmDevice, struct, vm); addDevice(struct, vmDevice, vm.getCdPath()); } else { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdTypeAndDevice(vm.getId(), VmDeviceGeneralType.DISK, VmDeviceType.CDROM.getName()); for (VmDevice vmDevice : vmDevices) { if (!vmDevice.getIsManaged()) { continue; } if (VmPayload.isPayload(vmDevice.getSpecParams())) { continue; } struct = new HashMap<String, Object>(); String cdPath = vm.getCdPath(); addCdDetails(vmDevice, struct, vm); addAddress(vmDevice, struct); addDevice(struct, vmDevice, cdPath == null ? "" : cdPath); } } }</code><technical_language>need address in case payload in db run-once</technical_language>

Target:
protected void buildVmCD() { Map<String, Object> struct; boolean hasPayload = vm.getVmPayload() != null && vm.getVmPayload().getDeviceType() == VmDeviceType.CDROM; if (hasPayload) { VmDevice vmDevice = new VmDevice(new VmDeviceId(Guid.newGuid(), vm.getId()), VmDeviceGeneralType.DISK, VmDeviceType.CDROM.getName(), "", 0, vm.getVmPayload().getSpecParams(), true, true, true, "", null, null, null); struct = new HashMap<String, Object>(); addCdDetails(vmDevice, struct, vm); addDevice(struct, vmDevice, ""); } if (vm.isRunOnce() && !StringUtils.isEmpty(vm.getCdPath())) { VmDevice vmDevice = new VmDevice(new VmDeviceId(Guid.newGuid(), vm.getId()), VmDeviceGeneralType.DISK, VmDeviceType.CDROM.getName(), "", 0, null, true, true, true, "", null, null, null); struct = new HashMap<String, Object>(); addCdDetails(vmDevice, struct, vm); addDevice(struct, vmDevice, vm.getCdPath()); } else { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdTypeAndDevice(vm.getId(), VmDeviceGeneralType.DISK, VmDeviceType.CDROM.getName()); for (VmDevice vmDevice : vmDevices) { if (!vmDevice.getIsManaged()) { continue; } if (VmPayload.isPayload(vmDevice.getSpecParams())) { continue; } struct = new HashMap<String, Object>(); String cdPath = vm.getCdPath(); addCdDetails(vmDevice, struct, vm); addAddress(vmDevice, struct); addDevice(struct, vmDevice, cdPath == null ? "" : cdPath); } } }
Source:
<code>public TemplateService get() { <START> Logger.info("execute ViewServiceProvider.get()"); <END> return HandlebarsTemplateService.of(defaultLoader(), overrideLoader()); }</code><technical_language>I this belongs more Logger.debug level</technical_language>

Target:
public TemplateService get() { Logger.debug("Provide TemplateService"); return HandlebarsTemplateService.of(defaultLoader(), overrideLoader()); }
Source:
<code>private void validateDependencies(final List<FlowTriggerDependency> dependencies) { Preconditions.checkNotNull(dependencies); Preconditions.checkArgument(!dependencies.isEmpty(), "no dependencies found"); Set<String> seen = Sets.newHashSet(); for (final FlowTriggerDependency dep : dependencies) { Preconditions.checkArgument(seen.add(dep.getName()), String.format("duplicate dependency" + ".name %s found, dependency.name should be unique", dep.getName())); } seen = Sets.newHashSet(); for (final FlowTriggerDependency dep : dependencies) { final Props props = dep.getPropsCopy(); <START> Preconditions.checkArgument(seen.add(dep.getType() + ":" + props.toString()), String.format <END> ("duplicate " + "dependency" + "config %s found, dependency config should be unique", dep.getName())); } }</code><technical_language>Consider adding a common utility method check for duplicates in a list. I find a standard library do a quick google search. considered overriding FlowTriggerDependency's equals method hashCode method a generic duplicate checking method</technical_language>

Target:
private void validateDependencies(final List<FlowTriggerDependency> dependencies) { validateDepNameUniqueness(dependencies); validateDepDefinitionUniqueness(dependencies); }
Source:
<code>public static void main(String[] args) throws Exception { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("SyslogdTests-context.xml", SyslogdTests.class); System.out.println("Hit enter to terminate"); System.in.read(); <START> ctx.close(); <END> ctx.destroy(); }</code><technical_language>more time: invoke close() directly, if destroy() same? 'd' letter in name of this (and similar for tcp) test class? invoke close() in similar test for tcp? :smile:</technical_language>

Target:
public static void main(String[] args) throws Exception { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("SyslogdTests-context.xml", SyslogdTests.class); System.out.println("Hit enter to terminate"); System.in.read(); ctx.close(); }
Source:
<code>public void drawGradientRect(int par1, int par2, int par3, int par4, int par5, int par6) { float f = (float) (par5 >> 24 & 255) / 255.0F; float f1 = (float) (par5 >> 16 & 255) / 255.0F; float f2 = (float) (par5 >> 8 & 255) / 255.0F; float f3 = (float) (par5 & 255) / 255.0F; float f4 = (float) (par6 >> 24 & 255) / 255.0F; float f5 = (float) (par6 >> 16 & 255) / 255.0F; float f6 = (float) (par6 >> 8 & 255) / 255.0F; float f7 = (float) (par6 & 255) / 255.0F; GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glShadeModel(GL11.GL_SMOOTH); <START> tessellator.startDrawingQuads(); tessellator.setColorRGBA_F(f1, f2, f3, f); tessellator.addVertex((double) par3, (double) par2, 0); tessellator.addVertex((double) par1, (double) par2, 0); tessellator.setColorRGBA_F(f5, f6, f7, f4); tessellator.addVertex((double) par1, (double) par4, 0); tessellator.addVertex((double) par3, (double) par4, 0); <END> tessellator.draw(); GL11.glShadeModel(GL11.GL_FLAT); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_TEXTURE_2D); }</code><technical_language>Errr, @Baughn</technical_language>

Target:
public void drawGradientRect(int par1, int par2, int par3, int par4, int par5, int par6) { float f = (float) (par5 >> 24 & 255) / 255.0F; float f1 = (float) (par5 >> 16 & 255) / 255.0F; float f2 = (float) (par5 >> 8 & 255) / 255.0F; float f3 = (float) (par5 & 255) / 255.0F; float f4 = (float) (par6 >> 24 & 255) / 255.0F; float f5 = (float) (par6 >> 16 & 255) / 255.0F; float f6 = (float) (par6 >> 8 & 255) / 255.0F; float f7 = (float) (par6 & 255) / 255.0F; GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glShadeModel(GL11.GL_SMOOTH); tessellator.draw(); GL11.glShadeModel(GL11.GL_FLAT); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glEnable(GL11.GL_TEXTURE_2D); }
Source:
<code>private static Response performRequest( final RestClient restClient, final String method, final String endpoint, final Map<String, String> params, final HttpEntity entity) throws DBException { try { final Header[] headers; if (entity != null) { headers = new Header[]{new BasicHeader("content-type", ContentType.APPLICATION_JSON.toString())}; } else { headers = emptyHeaders; } return restClient.performRequest( method, endpoint, params, entity, headers); } catch (final IOException e) { <START> e.printStackTrace(); <END> throw new DBException(e); } }</code><technical_language>Exception#printStackTrace stderr default</technical_language>

Target:
private static Response performRequest( final RestClient restClient, final String method, final String endpoint, final Map<String, String> params, final HttpEntity entity) throws DBException { try { final Header[] headers; if (entity != null) { headers = new Header[]{new BasicHeader("content-type", ContentType.APPLICATION_JSON.toString())}; } else { headers = EMPTY_HEADERS; } return restClient.performRequest( method, endpoint, params, entity, headers); } catch (final IOException e) { e.printStackTrace(); throw new DBException(e); } }
Source:
<code>public void findByCredentialsKeyValue_shouldFindGatewayAccount() { String paymentProvider = "test provider"; databaseTestHelper.addGatewayAccount(anAddGatewayAccountParams() .withAccountId(String.valueOf(gatewayAccountId)) .withPaymentGateway(paymentProvider) .withServiceName("service name") .build()); var credMap = Map.of("some_payment_provider_account_id", "accountid"); final Optional<GatewayAccountEntity> maybeGatewayAccount = gatewayAccountDao.findById(gatewayAccountId); assertThat(maybeGatewayAccount.isPresent(), is(true)); GatewayAccountEntity gatewayAccount = maybeGatewayAccount.get(); <START> gatewayAccount.setCredentials(credMap); <END> gatewayAccountDao.merge(gatewayAccount); Optional<GatewayAccountEntity> serviceAccountMaybe = gatewayAccountDao.findByCredentialsKeyValue("some_payment_provider_account_id", "accountid"); assertThat(serviceAccountMaybe.isPresent(), is(true)); Map<String, String> credentialsMap = serviceAccountMaybe.get().getCredentials(); assertThat(credentialsMap, hasEntry("some_payment_provider_account_id", "accountid")); }</code><technical_language>set creds initially insert databaseTestHelper</technical_language>

Target:
public void findByCredentialsKeyValue_shouldFindGatewayAccount() { var credMap = Map.of("some_payment_provider_account_id", "accountid"); databaseTestHelper.addGatewayAccount(anAddGatewayAccountParams() .withAccountId(String.valueOf(gatewayAccountId)) .withPaymentGateway("test provider") .withServiceName("service name") .withCredentials(credMap) .build()); Optional<GatewayAccountEntity> maybeGatewayAccount = gatewayAccountDao.findByCredentialsKeyValue("some_payment_provider_account_id", "accountid"); assertThat(maybeGatewayAccount.isPresent(), is(true)); Map<String, String> credentialsMap = maybeGatewayAccount.get().getCredentials(); assertThat(credentialsMap, hasEntry("some_payment_provider_account_id", "accountid")); }
Source:
<code><START> public static List<String> getVirtioScsiControllersForEntity(Guid id) { <END> return VmHelper.getInstance().getEntity(List.class, VdcQueryType.GetVirtioScsiControllers, new IdQueryParameters(id), "GetVirtioScsiControllers", true); }</code><technical_language>ummm... is this is a singleton, this simply instance method</technical_language>

Target:
public List<String> getVirtioScsiControllersForEntity(Guid id) { return getEntity(List.class, VdcQueryType.GetVirtioScsiControllers, new IdQueryParameters(id), "GetVirtioScsiControllers", true); }
Source:
<code>public void testProcessCssStyles() { FontState defaultState = new FontState(); FontState state = new FontState(); processCssStyles(state, defaultState, "font-size: 14px;color: rgb(3,3,3);font-style: italic bold;text-decoration: underline; background-color: blue;"); String number = NumberFormat.getInstance().format(1.273); <START> assertEquals(number, String.format("%1.3f", state.sizeFactor)); <END> assertEquals(new RGB(0, 0, 255), state.background); assertEquals(new RGB(3, 3, 3), state.foreground); assertTrue(state.isBold()); assertTrue(state.isItalic()); assertTrue(state.isUnderline()); }</code><technical_language>format a string test for this: number >= 1.273f && number < 1.274f</technical_language>

Target:
public void testProcessCssStyles() { FontState defaultState = new FontState(); FontState state = new FontState(); processCssStyles(state, defaultState, "font-size: 14px;color: rgb(3,3,3);font-style: italic bold;text-decoration: underline; background-color: blue;"); assertEquals(1.273f, state.sizeFactor, 0.001f); assertEquals(new RGB(0, 0, 255), state.background); assertEquals(new RGB(3, 3, 3), state.foreground); assertTrue(state.isBold()); assertTrue(state.isItalic()); assertTrue(state.isUnderline()); }
Source:
<code>public int removeChainFiles(String fromVersion, String toVersion) throws SQLException { int resCount = 0; ChainFiles cf = null; String getChainFiles = "SELECT * FROM Chain_File NATURAL JOIN Chain_File_Files " + "WHERE (FromVersion ~~* ?)" + " AND (ToVersion ~~* ?)"; PreparedStatement getChainFilesStmt = conn.prepareStatement(getChainFiles); getChainFilesStmt.setString(1, fromVersion); getChainFilesStmt.setString(2, toVersion); ResultSet getChainFilesRs = getChainFilesStmt.executeQuery(); if (getChainFilesRs.next()) { cf = new ChainFiles(getChainFilesRs); <START> } <END> getChainFilesStmt.close(); if (cf == null) { return 0; } String filePath = cf.folderPath; String query = "DELETE FROM Chain_File WHERE (FromVersion ~~* ?)" + " AND (ToVersion ~~* ?)"; File chainFile = new File(filePath); File chainFolder = chainFile.getParentFile(); if (chainFolder.exists()) { recursiveDelete(chainFolder); } PreparedStatement deleteStatement = conn.prepareStatement(query); deleteStatement.setString(1, fromVersion); deleteStatement.setString(2, toVersion); resCount = deleteStatement.executeUpdate(); deleteStatement.close(); return resCount; }</code><technical_language>A tuple in Chain_File table is uniquely identified FromVersion ToVersion attributes. in Chain_File_Files, attributes (which a foreign reference Chain_File) fileName attribute. a query return tuples, clause specifies of identifiers. I a single next() statement result set, supposed be? file is handled rest ignored</technical_language>

Target:
public int removeChainFiles(String fromVersion, String toVersion) throws SQLException { int resCount; String getChainFiles = "SELECT FolderPath FROM Chain_File NATURAL JOIN Chain_File_Files " + "WHERE (FromVersion ~~* ?)" + " AND (ToVersion ~~* ?)"; PreparedStatement getChainFilesStmt = conn.prepareStatement(getChainFiles); getChainFilesStmt.setString(1, fromVersion); getChainFilesStmt.setString(2, toVersion); ResultSet getChainFilesRs = getChainFilesStmt.executeQuery(); String filePath; if (getChainFilesRs.next()) { filePath = getChainFilesRs.getString("FolderPath"); } else { getChainFilesStmt.close(); return 0; } getChainFilesStmt.close(); removeChainFileFiles(fromVersion, toVersion); String query = "DELETE FROM Chain_File WHERE (FromVersion ~~* ?)" + " AND (ToVersion ~~* ?)"; File chainFile = new File(filePath); File chainFolder = chainFile.getParentFile(); if (chainFolder.exists()) { recursiveDelete(chainFolder); } PreparedStatement deleteStatement = conn.prepareStatement(query); deleteStatement.setString(1, fromVersion); deleteStatement.setString(2, toVersion); resCount = deleteStatement.executeUpdate(); deleteStatement.close(); return resCount; }
Source:
<code>RelNode changeTraitsUsingConverters( RelNode rel, RelTraitSet toTraits) { final RelTraitSet fromTraits = rel.getTraitSet(); assert fromTraits.size() >= toTraits.size(); final boolean allowInfiniteCostConverters = CalciteSystemProperty.ALLOW_INFINITE_COST_CONVERTERS.value(); RelNode converted = rel; Convention conventionTrait = null; for (RelTrait trait : toTraits) { if (trait instanceof Convention) { conventionTrait = (Convention) trait; break; } <START> } <END> for (int i = 0; (converted != null) && (i < toTraits.size()); i++) { RelTrait fromTrait = converted.getTraitSet().getTrait(i); final RelTraitDef traitDef = fromTrait.getTraitDef(); RelTrait toTrait = toTraits.getTrait(i); if (toTrait == null) { continue; } assert traitDef == toTrait.getTraitDef(); if (fromTrait.equals(toTrait)) { continue; } rel = traitDef.convert( this, converted, toTrait, conventionTrait, allowInfiniteCostConverters); if (rel != null) { assert rel.getTraitSet().getTrait(traitDef).satisfies(toTrait); register(rel, converted); } converted = rel; } if (converted != null) { assert converted.getTraitSet().satisfies(toTraits); } return converted; }</code><technical_language>toTraits.getTrait() get convention</technical_language>

Target:
RelNode changeTraitsUsingConverters( RelNode rel, RelTraitSet toTraits) { final RelTraitSet fromTraits = rel.getTraitSet(); assert fromTraits.size() >= toTraits.size(); final boolean allowInfiniteCostConverters = CalciteSystemProperty.ALLOW_INFINITE_COST_CONVERTERS.value(); RelNode converted = rel; for (int i = 0; (converted != null) && (i < toTraits.size()); i++) { RelTrait fromTrait = converted.getTraitSet().getTrait(i); final RelTraitDef traitDef = fromTrait.getTraitDef(); RelTrait toTrait = toTraits.getTrait(i); if (toTrait == null) { continue; } assert traitDef == toTrait.getTraitDef(); if (fromTrait.equals(toTrait)) { continue; } rel = traitDef.convert( this, converted, toTrait, allowInfiniteCostConverters); if (rel != null) { assert rel.getTraitSet().getTrait(traitDef).satisfies(toTrait); register(rel, converted); } converted = rel; } if (converted != null) { assert converted.getTraitSet().satisfies(toTraits); } return converted; }
Source:
<code>protected void modifySearchResultLinkTitle(SearchResult result, final HttpServletRequest httpServletRequest, final IPortletWindowId portletWindowId) { if (result.getType().size() > 0 && result.getTitle().contains("${")) { final IPortletWindow portletWindow = this.portletWindowRegistry.getPortletWindow(httpServletRequest, portletWindowId); final IPortletEntity portletEntity = portletWindow.getPortletEntity(); final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition(); final SpELEnvironmentRoot spelEnvironment = new SpELEnvironmentRoot(portletDefinition); try { result.setTitle(spELService.getValue(result.getTitle(), spelEnvironment)); } catch (SpelParseException e) { <START> result.setTitle("Invalid Spring EL expression '" + result.getTitle()+"'"); <END> } } }</code><technical_language>Hmm. failure case show this message users title of a search result? failure logged search result fall some kind of best-under-the-circumstances title ("(Unknown content title)")</technical_language>

Target:
protected void modifySearchResultLinkTitle(SearchResult result, final HttpServletRequest httpServletRequest, final IPortletWindowId portletWindowId) { if (result.getType().size() > 0 && result.getTitle().contains("${")) { final IPortletWindow portletWindow = this.portletWindowRegistry.getPortletWindow(httpServletRequest, portletWindowId); final IPortletEntity portletEntity = portletWindow.getPortletEntity(); final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition(); final SpELEnvironmentRoot spelEnvironment = new SpELEnvironmentRoot(portletDefinition); try { result.setTitle(spELService.getValue(result.getTitle(), spelEnvironment)); } catch (SpelParseException | SpelEvaluationException e) { result.setTitle("(Invalid portlet title) - see details in log file"); logger.error("Invalid Spring EL expression in search result portlet title", result.getTitle(), e); } } }
Source:
<code>private void rememberAliases(IPreferenceStore ps) { if (fStructureViewerAliases == null) return; StringBuffer buffer= new StringBuffer(); <START> Iterator<String> iter= fStructureViewerAliases.keySet().iterator(); <END> while (iter.hasNext()) { String key= iter.next(); String alias= fStructureViewerAliases.get(key); buffer.append(key); buffer.append('.'); buffer.append(alias); buffer.append(' '); } ps.setValue(STRUCTUREVIEWER_ALIASES_PREFERENCE_NAME, buffer.toString()); }</code><technical_language>modern for loop construct</technical_language>

Target:
private void rememberAliases(IPreferenceStore ps) { if (fStructureViewerAliases == null) return; StringBuilder buffer= new StringBuilder(); for (Map.Entry<String, String> entry : fStructureViewerAliases.entrySet()) { String key= entry.getKey(); String alias= entry.getValue(); buffer.append(key); buffer.append('.'); buffer.append(alias); buffer.append(' '); } ps.setValue(STRUCTUREVIEWER_ALIASES_PREFERENCE_NAME, buffer.toString()); }
Source:
<code>public String renderAfterConstructorJs() { StringBuilder builder = new StringBuilder(); if (getStyle() != null) { <START> builder.append(getJsId() + ".setStyle(new " + getStyle().getJsType() + "(" + getStyle().renderJs() + "));"); <END> } return builder.toString(); }</code><technical_language>idea of a builder is a bit :-)</technical_language>

Target:
public String renderAfterConstructorJs() { StringBuilder builder = new StringBuilder(); if (getStyle() != null) { builder.append(getJsId()); builder.append(".setStyle(new "); builder.append(getStyle().getJsType()); builder.append("(" + getStyle().renderJs() + "));"); } return builder.toString(); }
Source:
<code>public void byteEquivalenceTest(final List<Byte> values) { <START> codecPairTestForByte(values, this::writeByteForByte, this::readIntegerForByte); <END> codecPairTestForByte(values, this::writeByteForByte, this::readLongForByte); codecPairTestForByte(values, this::writeIntegerForByte, this::readByteForByte); codecPairTestForByte(values, this::writeIntegerForByte, this::readLongForByte); codecPairTestForByte(values, this::writeLongForByte, this::readByteForByte); codecPairTestForByte(values, this::writeLongForByte, this::readIntegerForByte); }</code><technical_language>Yeah, FunctionalInterface->Object conversion well</technical_language>

Target:
public void byteEquivalenceTest(final List<Byte> values) { codecPairTest(values, this::externalByteCodecWrite, this::externalIntegerCodecRead); codecPairTest(values, this::externalByteCodecWrite, this::externalLongCodecRead); codecPairTest(values, this::externalIntegerCodecWrite, this::externalByteCodecRead); codecPairTest(values, this::externalIntegerCodecWrite, this::externalLongCodecRead); codecPairTest(values, this::externalLongCodecWrite, this::externalByteCodecRead); codecPairTest(values, this::externalLongCodecWrite, this::externalIntegerCodecRead); }
Source:
<code>private void checkForMaxLength(Case caseForBlock) throws InvalidStructureException { if (caseForBlock.getTypeId().length() > 255) { throw new InvalidStructureException( <START> "case_type is longer than 255 chars for case with ID: " + caseForBlock.getCaseId() + " and case_type " + caseForBlock.getTypeId(), <END> parser); } else if (caseForBlock.getUserId().length() > 255) { throw new InvalidStructureException( "owner_id is longer than 255 chars for case with ID: " + caseForBlock.getCaseId() + " and owner_id " + caseForBlock.getUserId(), parser); } else if (caseForBlock.getName().length() > 255) { throw new InvalidStructureException( "case_name is longer than 255 chars for case with ID: " + caseForBlock.getCaseId() + " and case_name " + caseForBlock.getName(), parser); } else if (caseForBlock.getExternalId()!=null && caseForBlock.getExternalId().length() > 255) { throw new InvalidStructureException( "external_id is longer than 255 chars for case with ID: " + caseForBlock.getCaseId() + " and external_id " + caseForBlock.getExternalId(), parser); } }</code><technical_language>rephrase based action encode IE: "Invalid <case_type>, 256 characters less"</technical_language>

Target:
private void checkForMaxLength(Case caseForBlock) throws InvalidStructureException { if (caseForBlock.getTypeId().length() > 255) { throw new InvalidCasePropertyLengthException("case_type"); } else if (caseForBlock.getUserId().length() > 255) { throw new InvalidCasePropertyLengthException("owner_id"); } else if (caseForBlock.getName().length() > 255) { throw new InvalidCasePropertyLengthException("case_name"); } else if (caseForBlock.getExternalId()!=null && caseForBlock.getExternalId().length() > 255) { throw new InvalidCasePropertyLengthException("external_id"); } }
Source:
<code>public NewsSet getNewsSet(String fname, PortletRequest request) { PortletSession session = request.getPortletSession(); String userId = request.getRemoteUser(); if (userId == null) { userId = "guest"; } NewsSet set; Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { log.debug("Got Mutex: "+mutex); set = newsStore.getNewsSet(userId, fname); if (set == null) { log.debug("No existing set found for "+userId+", creating and saving new set."); set = new NewsSet(); set.setUserId(userId); set.setName(fname); newsStore.storeNewsSet(set); } if (session.getAttribute("setId", PortletSession.PORTLET_SCOPE) == null) { log.debug("re-initalising loaded newsSet "+set.getName()); @SuppressWarnings("unchecked") Set<String> roles = (Set<String>) session.getAttribute("userRoles", PortletSession.PORTLET_SCOPE); newsStore.initNews(set, roles); newsStore.storeNewsSet(set); session.setAttribute("setId", set.getId(), PortletSession.PORTLET_SCOPE); <START> } <END> } return set; }</code><technical_language>Minor, indent lines 70 - 77 off. level 69</technical_language>

Target:
public NewsSet getNewsSet(String fname, PortletRequest request) { PortletSession session = request.getPortletSession(); String userId = request.getRemoteUser(); if (userId == null) { userId = "guest"; } NewsSet set; Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { log.debug("Got Mutex: "+mutex); set = newsStore.getNewsSet(userId, fname); if (set == null) { log.debug("No existing set found for "+userId+", creating and saving new set."); set = new NewsSet(); set.setUserId(userId); set.setName(fname); newsStore.storeNewsSet(set); } if (session.getAttribute("setId", PortletSession.PORTLET_SCOPE) == null) { log.debug("re-initalising loaded newsSet "+set.getName()); @SuppressWarnings("unchecked") Set<String> roles = (Set<String>) session.getAttribute("userRoles", PortletSession.PORTLET_SCOPE); if(roles != null) { newsStore.initNews(set, roles); newsStore.storeNewsSet(set); session.setAttribute("setId", set.getId(), PortletSession.PORTLET_SCOPE); } } } return set; }
Source:
<code>public double evaluate(double... values) throws EvaluationException { for (int i = 0; i < values.length; ++i) { final String variableName = variableNames[i]; final RValue invokable = variables.get(variableName); if (!(invokable instanceof Variable)) { throw new EvaluationException(invokable.getPosition(), "Tried to assign constant " + variableName + "."); } ((Variable) invokable).value = values[i]; } pushInstance(); try { Future<Double> result = evalThread.submit(new Callable<Double>() { @Override public Double call() throws Exception { return root.getValue(); } }); try { return result.get(WorldEdit.getInstance().getConfiguration().calculationTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { <START> Thread.currentThread().interrupt(); <END> throw new RuntimeException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof ReturnException) { return ((ReturnException) cause).getValue(); } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(cause); } catch (TimeoutException e) { result.cancel(true); throw new EvaluationException(-1, "Calculations exceeded time limit."); } } finally { popInstance(); } }</code><technical_language>I worked futures much, this exception get thrown main thread? I Future.get(...) interrupt thread task is run? I totally wrong though</technical_language>

Target:
public double evaluate(double... values) throws EvaluationException { for (int i = 0; i < values.length; ++i) { final String variableName = variableNames[i]; final RValue invokable = variables.get(variableName); if (!(invokable instanceof Variable)) { throw new EvaluationException(invokable.getPosition(), "Tried to assign constant " + variableName + "."); } ((Variable) invokable).value = values[i]; } Future<Double> result = evalThread.submit(new Callable<Double>() { @Override public Double call() throws Exception { pushInstance(); try { return root.getValue(); } finally { popInstance(); } } }); try { return result.get(WorldEdit.getInstance().getConfiguration().calculationTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof ReturnException) { return ((ReturnException) cause).getValue(); } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(cause); } catch (TimeoutException e) { result.cancel(true); throw new EvaluationException(-1, "Calculations exceeded time limit."); } }
Source:
<code>private List<JSONPathParser.FieldSpec> convertFieldSpecs(List<JSONPathFieldSpec> druidFieldSpecs) { List<JSONPathParser.FieldSpec> newSpecs = new ArrayList<>(); for(JSONPathFieldSpec druidSpec : druidFieldSpecs) { JSONPathParser.FieldType type; <START> if (druidSpec.getType() == JSONPathFieldType.ROOT) { <END> type = JSONPathParser.FieldType.ROOT; } else { type = JSONPathParser.FieldType.NESTED; } JSONPathParser.FieldSpec newSpec = new JSONPathParser.FieldSpec(type, druidSpec.getName(), druidSpec.getExpr()); newSpecs.add(newSpec); } return newSpecs; }</code><technical_language>this is enum this a switch</technical_language>

Target:
private List<JSONPathParser.FieldSpec> convertFieldSpecs(List<JSONPathFieldSpec> druidFieldSpecs) { List<JSONPathParser.FieldSpec> newSpecs = new ArrayList<>(); for (JSONPathFieldSpec druidSpec : druidFieldSpecs) { JSONPathParser.FieldType type; switch (druidSpec.getType()) { case ROOT: type = JSONPathParser.FieldType.ROOT; break; case PATH: type = JSONPathParser.FieldType.PATH; break; default: throw new IllegalArgumentException("Invalid type for field " + druidSpec.getName()); } JSONPathParser.FieldSpec newSpec = new JSONPathParser.FieldSpec( type, druidSpec.getName(), druidSpec.getExpr() ); newSpecs.add(newSpec); } return newSpecs; }