auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected byte[] doDecompress(byte[] compressedData) throws IOException { try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData); ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPInputStream gzipIS = new GZIPInputStream(bis)) { byte[] buffer = new byte[1024]; int len; while ((len = gzipIS.read(buffer)) != -1) { bos.write(buffer, 0, len); } return bos.toByteArray(); } catch (ZipException e) { throw new NotCompressedException("Content format not GZIP or compression method not supported.", e); } }

Target:
protected byte[] doDecompress(byte[] compressedData) throws IOException { if(compressedData != null && compressedData.length > 2 && compressedData[0] == (byte) 0x1f && compressedData[1] == (byte) 0x8b) { try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData); ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPInputStream gzipIS = new GZIPInputStream(bis)) { byte[] buffer = new byte[1024]; int len; while ((len = gzipIS.read(buffer)) != -1) { bos.write(buffer, 0, len); } return bos.toByteArray(); } } else { return compressedData; } }
Source:
public void selectByQuery_key_with_special_characters() { db.components().insertProjectAndSnapshot(ComponentTesting.newPrivateProjectDto(db.organizations().insert()).setDbKey("project-_%-key")); db.components().insertProjectAndSnapshot(ComponentTesting.newPrivateProjectDto(db.organizations().insert()).setDbKey("project-key-that-does-not-match")); ComponentQuery query = ComponentQuery.builder().setNameOrKeyQuery("project-_%-key").setQualifiers(Qualifiers.PROJECT).build(); List<ComponentDto> result = underTest.selectByQuery(dbSession, query, 0, 10); assertThat(result).hasSize(1); assertThat(result.get(0).getDbKey()).isEqualTo("project-_%-key"); }

Target:
public void selectByQuery_key_with_special_characters() { db.components().insertProjectAndSnapshot(newPrivateProjectDto(db.organizations().insert()).setDbKey("project-_%-key")); db.components().insertProjectAndSnapshot(newPrivateProjectDto(db.organizations().insert()).setDbKey("project-key-that-does-not-match")); ComponentQuery query = ComponentQuery.builder().setNameOrKeyQuery("project-_%-key").setQualifiers(Qualifiers.PROJECT).build(); List<ComponentDto> result = underTest.selectByQuery(dbSession, query, 0, 10); assertThat(result).hasSize(1); assertThat(result.get(0).getDbKey()).isEqualTo("project-_%-key"); }
Source:
protected Object[] getLocalizedMessageArguments() { return new Object[] { attribute.getName(), type, String.join("or", expectedTypes) }; }

Target:
protected Object[] getLocalizedMessageArguments() { return new Object[] { attribute.getName(), type, String.join(",", expectedTypes) }; }
Source:
public static Fixture prepareDirectoryAndPageCache( Class<?> testClass ) throws IOException { DefaultFileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); TestDirectory testDirectory = TestDirectory.testDirectory( testClass, fileSystem ); File dir = testDirectory.prepareDirectoryForTest( "test" ); fileSystem.mkdirs( dir ); PageCache pageCache = StandalonePageCacheFactory.createPageCache( fileSystem ); return new Fixture( pageCache, fileSystem, dir ); }

Target:
public static Fixture prepareDirectoryAndPageCache( Class<?> testClass ) throws IOException { DefaultFileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); TestDirectory testDirectory = TestDirectory.testDirectory( testClass, fileSystem ); File dir = testDirectory.prepareDirectoryForTest( "test" ); PageCache pageCache = StandalonePageCacheFactory.createPageCache( fileSystem ); return new Fixture( pageCache, fileSystem, dir ); }
Source:
public void test() { JavaCheckVerifier.verify("src/test/files/checks/spring/SpringSecurityDisableCSRFCheck.java", new SpringSecurityDisableCSRFCheck()); JavaCheckVerifier.verifyNoIssueWithoutSemantic("src/test/files/checks/spring/SpringSecurityDisableCSRFCheck.java", new SpringSecurityDisableCSRFCheck()); }

Target:
public void test() { JavaCheckVerifier.verify("src/test/files/checks/spring/SpringSecurityDisableCSRFCheck.java", new SpringSecurityDisableCSRFCheck()); }
Source:
protected String getModuleUrl(LibraryRequest request, String modulePath, ModuleType type) { if (logger.isLoggable(Level.FINEST)) { logger.entering(sourceClass, "getModuleUrl", new Object[] { request, modulePath }); } String jsUrl = ""; String moduleUrl = ""; switch (type) { case MODULE: jsUrl = request.getToolkitJsUrl(); break; case EXTENSION: jsUrl = request.getToolkitExtJsUrl(); break; case LIBRARY: jsUrl = request.getJsLibraryUrl(); break; default: moduleUrl = modulePath; break; } moduleUrl = moduleUrl.isEmpty() ? PathUtil.concat(jsUrl, modulePath, '/') : moduleUrl; if (logger.isLoggable(Level.FINEST)) { logger.exiting(sourceClass, "getModuleUrl", moduleUrl); } return moduleUrl; }

Target:
protected String getModuleUrl(LibraryRequest request, String modulePath, ModuleType type) { if (logger.isLoggable(Level.FINEST)) { logger.entering(sourceClass, "getModuleUrl", new Object[] { request, modulePath }); } String jsUrl = ""; String moduleUrl = ""; switch (type) { case SBT_MODULE: jsUrl = request.getToolkitJsUrl(); break; case SBTX_MODULE: jsUrl = request.getToolkitExtJsUrl(); break; case JS_LIBRARY: jsUrl = request.getJsLibraryUrl(); break; default: moduleUrl = modulePath; break; } moduleUrl = moduleUrl.isEmpty() ? PathUtil.concat(jsUrl, modulePath, '/') : moduleUrl; if (logger.isLoggable(Level.FINEST)) { logger.exiting(sourceClass, "getModuleUrl", moduleUrl); } return moduleUrl; }
Source:
public PeriodicMeterReadsAsyncResponse getPeriodicMeterReads( @OrganisationIdentification final String organisationIdentification, @RequestPayload final PeriodicMeterReadsRequest request) throws OsgpException { LOGGER.debug("Incoming PeriodicMeterReadsRequest for meter: {}.", request.getDeviceIdentification()); return (PeriodicMeterReadsAsyncResponse) this.getPeriodic(organisationIdentification, request); }

Target:
public PeriodicMeterReadsAsyncResponse getPeriodicMeterReads( @OrganisationIdentification final String organisationIdentification, @RequestPayload final PeriodicMeterReadsRequest request) throws OsgpException { LOGGER.debug("Incoming PeriodicMeterReadsRequest for meter: {}.", request.getDeviceIdentification()); return (PeriodicMeterReadsAsyncResponse) this.getPeriodicAsyncResponseForEandG(organisationIdentification, request); }
Source:
private static Predicate<ChangeData> equalsLabelPredicate(Args args, String label, int expVal) { if (args.accounts != null && !args.accounts.isEmpty()) { List<Predicate<ChangeData>> r = Lists.newArrayList(); for (Account.Id a : args.accounts) { r.add(new EqualsLabelPredicate(args, label, expVal, a)); } return or(r); } else if (args.group != null) { List<Predicate<ChangeData>> r = Lists.newArrayList(); r.add(new EqualsLabelPredicate(args, label, expVal, null)); return or(r); } else { return new EqualsLabelPredicate(args, label, expVal, null); } }

Target:
private static Predicate<ChangeData> equalsLabelPredicate(Args args, String label, int expVal) { if (args.accounts == null || args.accounts.isEmpty()) { return new EqualsLabelPredicate(args, label, expVal, null); } else { List<Predicate<ChangeData>> r = Lists.newArrayList(); for (Account.Id a : args.accounts) { r.add(new EqualsLabelPredicate(args, label, expVal, a)); } return or(r); } }
Source:
ZkJobCoordinator(Config config, MetricsRegistry metricsRegistry, ZkUtils zkUtils) { this.config = config; this.metrics = new ZkJobCoordinatorMetrics(metricsRegistry); this.processorId = createProcessorId(config); this.zkUtils = zkUtils; zkUtils.getZkClient().subscribeStateChanges(new ZkSessionStateChangedListener()); LeaderElector leaderElector = new ZkLeaderElector(processorId, zkUtils); leaderElector.setLeaderElectorListener(new LeaderElectorListenerImpl()); this.zkController = new ZkControllerImpl(processorId, zkUtils, this, leaderElector); this.barrier = new ZkBarrierForVersionUpgrade( zkUtils.getKeyBuilder().getJobModelVersionBarrierPrefix(), zkUtils, new ZkBarrierListenerImpl()); this.debounceTimeMs = new JobConfig(config).getDebounceTimeMs(); this.reporters = MetricsReporterLoader.getMetricsReporters(new MetricsConfig(config), processorId); debounceTimer = new ScheduleAfterDebounceTime(); debounceTimer.setScheduledTaskCallback(throwable -> { LOG.error("Received exception from in JobCoordinator Processing!", throwable); stop(); }); Map<String, SystemAdmin> systemAdminMap = new JavaSystemConfig(config).getSystemAdmins(); systemAdmins = new SystemAdmins(Util.javaMapAsScalaMap(systemAdminMap)); streamMetadataCache = new StreamMetadataCache(Util.javaMapAsScalaMap(systemAdminMap), METADATA_CACHE_TTL_MS, SystemClock.instance()); }

Target:
ZkJobCoordinator(Config config, MetricsRegistry metricsRegistry, ZkUtils zkUtils) { this.config = config; this.metrics = new ZkJobCoordinatorMetrics(metricsRegistry); this.processorId = createProcessorId(config); this.zkUtils = zkUtils; zkUtils.getZkClient().subscribeStateChanges(new ZkSessionStateChangedListener()); LeaderElector leaderElector = new ZkLeaderElector(processorId, zkUtils); leaderElector.setLeaderElectorListener(new LeaderElectorListenerImpl()); this.zkController = new ZkControllerImpl(processorId, zkUtils, this, leaderElector); this.barrier = new ZkBarrierForVersionUpgrade( zkUtils.getKeyBuilder().getJobModelVersionBarrierPrefix(), zkUtils, new ZkBarrierListenerImpl()); this.debounceTimeMs = new JobConfig(config).getDebounceTimeMs(); this.reporters = MetricsReporterLoader.getMetricsReporters(new MetricsConfig(config), processorId); debounceTimer = new ScheduleAfterDebounceTime(); debounceTimer.setScheduledTaskCallback(throwable -> { LOG.error("Received exception from in JobCoordinator Processing!", throwable); stop(); }); systemAdmins = new SystemAdmins(config); streamMetadataCache = new StreamMetadataCache(systemAdmins, METADATA_CACHE_TTL_MS, SystemClock.instance()); }
Source:
public Object[] getSelectableProducts(final IProgressMonitor monitor) throws XmlRpcException { return (new BugzillaXmlRpcOperation<Object[]>(this) { @Override public Object[] execute() throws XmlRpcException { Object[] result = null; HashMap<?, ?> response = (HashMap<?, ?>) call(monitor, XML_PRODUCT_GET_SELECTABLE, (token == null) ? null : new Object[] { new HashMap<String, Object>() { { put(XML_PARAMETER_TOKEN, token); } } }); result = response2ObjectArray(response, XML_RESPONSE_IDS); return result; } }).execute(); }

Target:
public Object[] getSelectableProducts(final IProgressMonitor monitor) throws XmlRpcException { return (new BugzillaXmlRpcOperation<Object[]>(this) { @Override public Object[] execute() throws XmlRpcException { Object[] result = null; HashMap<?, ?> response = (HashMap<?, ?>) call(monitor, XML_PRODUCT_GET_SELECTABLE, (token == null) ? null : new Object[] { Collections.singletonMap(XML_PARAMETER_TOKEN, token) }); result = response2ObjectArray(response, XML_RESPONSE_IDS); return result; } }).execute(); }
Source:
private void onGitRepositoryDeletedEventReceived(String projectPath) { try { ProjectManager projectManager = projectManagerProvider.get(); projectManager.removeType(projectPath, CONTRIBUTION_PROJECT_TYPE_ID); RegisteredProject project = projectManager.get(projectPath).get(); Map<String, List<String>> attributes = project.getAttributes(); attributes.remove(CONTRIBUTE_LOCAL_BRANCH_NAME); attributes.remove(CONTRIBUTE_TO_BRANCH_VARIABLE_NAME); NewProjectConfigImpl projectConfig = new NewProjectConfigImpl( project.getPath(), project.getType(), project.getMixins(), project.getName(), project.getDescription(), attributes, null, project.getSource()); projectManager.update(projectConfig); } catch (NotFoundException e) { LOG.error( "Project not found for removing type", projectPath, CONTRIBUTION_PROJECT_TYPE_ID, e); } catch (ServerException e) { e.printStackTrace(); } catch (ConflictException | BadRequestException | ForbiddenException ignore) { LOG.warn( "Usually should not occur. But exception occurred during removing project type", CONTRIBUTION_PROJECT_TYPE_ID, ignore); } }

Target:
private void onGitRepositoryDeletedEventReceived(String projectPath) { try { ProjectManager projectManager = projectManagerProvider.get(); projectManager.removeType(projectPath, CONTRIBUTION_PROJECT_TYPE_ID); RegisteredProject project = projectManager.get(projectPath).get(); Map<String, List<String>> attributes = project.getAttributes(); attributes.remove(CONTRIBUTE_LOCAL_BRANCH_NAME); attributes.remove(CONTRIBUTE_TO_BRANCH_VARIABLE_NAME); NewProjectConfigImpl projectConfig = new NewProjectConfigImpl( project.getPath(), project.getType(), project.getMixins(), project.getName(), project.getDescription(), attributes, null, project.getSource()); projectManager.update(projectConfig); } catch (NotFoundException e) { LOG.error( "Project not found for removing type", projectPath, CONTRIBUTION_PROJECT_TYPE_ID, e); } catch (ServerException e) { LOG.error( "Exception occurred during removing project type for project ", CONTRIBUTION_PROJECT_TYPE_ID, projectPath, e); } catch (ConflictException | BadRequestException | ForbiddenException ignore) { LOG.warn( "Usually should not occur. But exception occurred during removing project type", CONTRIBUTION_PROJECT_TYPE_ID, ignore); } }
Source:
@Override public CacheableLocator createLocator(AnnotatedElement annotatedElement) { TimeOutDuration customDuration; if (annotatedElement.isAnnotationPresent(WithTimeout.class)) { WithTimeout withTimeout = annotatedElement.getAnnotation(WithTimeout.class); customDuration = new TimeOutDuration(withTimeout.time(), withTimeout.unit()); } else { customDuration = duration; } builder.setAnnotated(annotatedElement); By byResult = builder.buildBy(); return ofNullable(byResult) .map(by -> new AppiumElementLocator(searchContext, by, builder.isLookupCached(), customDuration)) .orElse(null); }

Target:
@Override public @Nullable CacheableLocator createLocator(AnnotatedElement annotatedElement) { TimeOutDuration customDuration; if (annotatedElement.isAnnotationPresent(WithTimeout.class)) { WithTimeout withTimeout = annotatedElement.getAnnotation(WithTimeout.class); customDuration = new TimeOutDuration(withTimeout.time(), withTimeout.unit()); } else { customDuration = duration; } builder.setAnnotated(annotatedElement); By byResult = builder.buildBy(); return ofNullable(byResult) .map(by -> new AppiumElementLocator(searchContext, by, builder.isLookupCached(), customDuration)) .orElse(null); }
Source:
public CSVLexer(final Reader input, final char valueSeparator, final char textMarker, final boolean keepBeginningWhiteSpace) { this.input = new RewindableTextStream(input); this.separator = valueSeparator; this.textMarker = textMarker; this.builder = new LinkedList<Character>(); this.lastTokenType = TOKEN_ERROR; this.lastTokenValue = null; this.keepBeginningWhiteSpace = keepBeginningWhiteSpace; }

Target:
public CSVLexer(final Reader input, final char valueSeparator, final char textMarker, final boolean keepBeginningWhiteSpace) { this.input = new RewindableTextStream(input); this.separator = valueSeparator; this.textMarker = textMarker; this.builder = new StringBuilder(BUFFER_SIZE); this.lastTokenType = TOKEN_ERROR; this.lastTokenValue = null; this.keepBeginningWhiteSpace = keepBeginningWhiteSpace; }
Source:
public static void main(String[] args) { Config config = new Config(); config.getAdvancedNetworkConfig().setEnabled(true); config.getAdvancedNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); config.getAdvancedNetworkConfig().getJoin() .getTcpIpConfig().setEnabled(true).addMember("192.168.1.10,192.168.1.11,192.168.1.12"); config.getAdvancedNetworkConfig().setMemberEndpointConfig(createMemberEndpointConfig()); config.getAdvancedNetworkConfig().setClientEndpointConfig(createClientEndpointConfig()); config.getAdvancedNetworkConfig().addWanEndpointConfig(createWanEndpointConfig()); config.addWanReplicationConfig( new WanReplicationConfig() .setName("active-wan-replication") .addWanPublisherConfig( new WanPublisherConfig() .setGroupName("cluster-b") .setClassName("com.hazelcast.enterprise.wan.replication.WanBatchReplication") .setEndpoint("active-wan"))); config.addMapConfig( new MapConfig("wan-map") .setWanReplicationRef( new WanReplicationRef("active-wan-replication", "com.hazelcast.enterprise.wan.replication.WanBatchReplication", Collections.<String>emptyList(), false))); HazelcastInstance hz = Hazelcast.newHazelcastInstance(config); }

Target:
public static void main(String[] args) { Config config = new Config(); config.getAdvancedNetworkConfig().setEnabled(true); config.getAdvancedNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); config.getAdvancedNetworkConfig().getJoin() .getTcpIpConfig().setEnabled(true).addMember("192.168.1.10,192.168.1.11,192.168.1.12"); config.getAdvancedNetworkConfig().setMemberEndpointConfig(createMemberEndpointConfig()); config.getAdvancedNetworkConfig().setClientEndpointConfig(createClientEndpointConfig()); config.getAdvancedNetworkConfig().addWanEndpointConfig(createWanEndpointConfig()); WanPublisherConfig wanPublisherConfig = new WanPublisherConfig() .setGroupName("cluster-b") .setClassName("com.hazelcast.enterprise.wan.replication.WanBatchReplication") .setEndpoint("active-wan"); Map<String, Comparable> props = wanPublisherConfig.getProperties(); props.put("endpoints", "147.102.1.10:8443,147.102.1.11:8443,147.102.1.12:8443"); props.put("group.password", "clusterB-pass"); config.addWanReplicationConfig( new WanReplicationConfig() .setName("active-wan-replication") .addWanPublisherConfig(wanPublisherConfig)); config.addMapConfig( new MapConfig("wan-map") .setWanReplicationRef( new WanReplicationRef("active-wan-replication", "com.hazelcast.enterprise.wan.replication.WanBatchReplication", Collections.<String>emptyList(), false))); HazelcastInstance hz = Hazelcast.newHazelcastInstance(config); }
Source:
public String toString() { return "RefundEntity{" + "externalId='" + externalId + '\'' + ", reference='" + reference + '\'' + ", amount=" + amount + ", status='" + status + '\'' + ", refundedBy='" + refundedBy + '\'' + ", chargeEntity=" + chargeEntity + ", createdDate=" + createdDate + '}'; }

Target:
public String toString() { return "RefundEntity{" + "externalId='" + externalId + '\'' + ", reference='" + reference + '\'' + ", amount=" + amount + ", status='" + status + '\'' + ", userExternalId='" + userExternalId + '\'' + ", chargeEntity=" + chargeEntity + ", createdDate=" + createdDate + '}'; }
Source:
private static String prependZeroes(String twoBytes) { StringBuilder builder = new StringBuilder(); int zeroLen = 4 - twoBytes.length(); for (int i = 0; i < zeroLen; i++) { builder.append(ZERO_STRING); } builder.append(twoBytes); return builder.toString(); }

Target:
private String prependZeroes(String twoBytes) { StringBuilder builder = new StringBuilder(); int zeroLen = 4 - twoBytes.length(); for (int i = 0; i < zeroLen; i++) { builder.append(ZERO_STRING); } builder.append(twoBytes); return builder.toString(); }
Source:
public int runCmd(CommandLine cmdLine) throws Exception { ClientConfiguration adminConf = new ClientConfiguration(bkConf); BookKeeperAdmin admin = new BookKeeperAdmin(adminConf); try { final String remoteBookieidToDecommission = cmdLine.getOptionValue("bookieid"); final BookieSocketAddress bookieAddressToDecommission = (StringUtils .isBlank(remoteBookieidToDecommission) ? Bookie.getBookieAddress(bkConf) : new BookieSocketAddress(remoteBookieidToDecommission)); admin.decommissionBookie(bookieAddressToDecommission); LOG.info("The ledgers stored in the given decommissioning bookie are properly replicated"); runFunctionWithRegistrationManager(bkConf, rm -> { try { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bookieAddressToDecommission); cookie.getValue().deleteFromRegistrationManager(rm, bookieAddressToDecommission, cookie.getVersion()); } catch (CookieNotFoundException nne) { LOG.warn("No cookie to remove, it could be deleted already : ", nne); } catch (BookieException be) { throw new UncheckedExecutionException(be.getMessage(), be); } return 0; }); LOG.info("Cookie of the decommissioned bookie: is deleted successfully", bookieAddressToDecommission); return 0; } catch (Exception e) { LOG.error("Received exception in DecommissionBookieCmd ", e); return -1; } finally { if (admin != null) { admin.close(); } } }

Target:
public int runCmd(CommandLine cmdLine) throws Exception { ClientConfiguration adminConf = new ClientConfiguration(bkConf); BookKeeperAdmin admin = new BookKeeperAdmin(adminConf); try { final String remoteBookieidToDecommission = cmdLine.getOptionValue("bookieid"); final BookieSocketAddress bookieAddressToDecommission = (StringUtils .isBlank(remoteBookieidToDecommission) ? Bookie.getBookieAddress(bkConf) : new BookieSocketAddress(remoteBookieidToDecommission)); admin.decommissionBookie(bookieAddressToDecommission); LOG.info("The ledgers stored in the given decommissioning bookie: are properly replicated", bookieAddressToDecommission); runFunctionWithRegistrationManager(bkConf, rm -> { try { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bookieAddressToDecommission); cookie.getValue().deleteFromRegistrationManager(rm, bookieAddressToDecommission, cookie.getVersion()); } catch (CookieNotFoundException nne) { LOG.warn("No cookie to remove for the decommissioning bookie: {}, it could be deleted already", bookieAddressToDecommission, nne); } catch (BookieException be) { throw new UncheckedExecutionException(be.getMessage(), be); } return 0; }); LOG.info("Cookie of the decommissioned bookie: is deleted successfully", bookieAddressToDecommission); return 0; } catch (Exception e) { LOG.error("Received exception in DecommissionBookieCmd ", e); return -1; } finally { if (admin != null) { admin.close(); } } }
Source:
public void onActivate(ActivateEvent event, EntityRef entity) { EntityRef attackingPlayer = event.getInstigator(); if (attackingPlayer.getComponent(CharacterHeldItemComponent.class).selectedItem.hasComponent(RaycastOnActivateComponent.class)) { if (entity.hasComponent(PlayerCharacterComponent.class) && entity.hasComponent(CharacterHeldItemComponent.class)) { CharacterHeldItemComponent characterHeldItemComponent = entity.getComponent(CharacterHeldItemComponent.class); EntityRef heldItem = characterHeldItemComponent.selectedItem; if (heldItem.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(BLACK_FLAG_URI) || heldItem.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(RED_FLAG_URI)) { Vector3f position = new Vector3f(attackingPlayer.getComponent(LocationComponent.class).getLocalPosition()); Vector3f direction = localPlayer.getViewDirection(); Vector3f newPosition = new Vector3f(position.x + direction.x * 1.5f, position.y + direction.y * 1.5f, position.z + direction.z * 1.5f ); Vector3f impulseVector = new Vector3f(direction); entity.send(new DropItemRequest(heldItem, entity, impulseVector, newPosition)); } } } }

Target:
public void onActivate(ActivateEvent event, EntityRef entity) { EntityRef attackingPlayer = event.getInstigator(); if (attackingPlayer.getComponent(CharacterHeldItemComponent.class).selectedItem.hasComponent(RaycastOnActivateComponent.class)) { if (entity.hasComponent(PlayerCharacterComponent.class) && entity.hasComponent(CharacterHeldItemComponent.class)) { CharacterHeldItemComponent characterHeldItemComponent = entity.getComponent(CharacterHeldItemComponent.class); EntityRef heldItem = characterHeldItemComponent.selectedItem; if (heldItem.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(LASUtils.BLACK_FLAG_URI) || heldItem.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(LASUtils.RED_FLAG_URI)) { Vector3f position = new Vector3f(attackingPlayer.getComponent(LocationComponent.class).getLocalPosition()); Vector3f direction = localPlayer.getViewDirection(); Vector3f newPosition = new Vector3f(position.x + direction.x * NEW_DIRECTION_MODIFIER, position.y + direction.y * NEW_DIRECTION_MODIFIER, position.z + direction.z * NEW_DIRECTION_MODIFIER ); Vector3f impulseVector = new Vector3f(direction); entity.send(new DropItemRequest(heldItem, entity, impulseVector, newPosition)); } } } }
Source:
private void initTunedProfiles() { this.startProgress(null); Frontend.getInstance().runQuery(VdcQueryType.GetGlusterTunedProfiles, new VdcQueryParametersBase(), new AsyncQuery(new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { ClusterModel.this.stopProgress(); List<String> glusterTunedProfiles = new ArrayList<>(); if (((VdcQueryReturnValue) returnValue).getSucceeded()) { glusterTunedProfiles.addAll((List<String>)(((VdcQueryReturnValue) returnValue).getReturnValue())); } glusterTunedProfile.setItems(glusterTunedProfiles); } })); glusterTunedProfile.setIsAvailable(glusterTunedProfile.getItems().size() > 0 && ApplicationModeHelper.isModeSupported(ApplicationMode.GlusterOnly)); }

Target:
public void initTunedProfiles() { this.startProgress(null); Frontend.getInstance().runQuery(VdcQueryType.GetGlusterTunedProfiles, new VdcQueryParametersBase(), new AsyncQuery(new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { ClusterModel.this.stopProgress(); List<String> glusterTunedProfiles = new ArrayList<>(); if (((VdcQueryReturnValue) returnValue).getSucceeded()) { glusterTunedProfiles.addAll((List<String>)(((VdcQueryReturnValue) returnValue).getReturnValue())); } glusterTunedProfile.setItems(glusterTunedProfiles, glusterTunedProfile.getSelectedItem()); glusterTunedProfile.setIsAvailable(glusterTunedProfile.getItems().size() > 0); } })); }
Source:
private List<AccountInfo> suggestAccountFullTextSearch( VisibilityControl visibilityControl) throws OrmException { String str = query.toLowerCase(); LinkedHashMap<Account.Id, AccountInfo> accountMap = Maps.newLinkedHashMap(); List<Account> fullNameMatches = Lists.newArrayList(); List<Account> emailMatches = Lists.newArrayList(); for (Account a : dbProvider.get().accounts().all()) { if (a.getFullName() != null && a.getFullName().toLowerCase().contains(str)) { fullNameMatches.add(a); } else if (a.getPreferredEmail() != null && emailMatches.size() < fullTextMaxMatches && a.getPreferredEmail().toLowerCase().contains(str)) { emailMatches.add(a); } if (fullNameMatches.size() >= fullTextMaxMatches) { break; } } for (Account a : fullNameMatches) { addSuggestion(accountMap, a, new AccountInfo(a.getId()), visibilityControl); if (accountMap.size() >= limit) { break; } } if (accountMap.size() < limit) { for (Account a : emailMatches) { addSuggestion(accountMap, a, new AccountInfo(a.getId()), visibilityControl); if (accountMap.size() >= limit) { break; } } } return Lists.newArrayList(accountMap.values()); }

Target:
private List<AccountInfo> suggestAccountFullTextSearch( VisibilityControl visibilityControl) throws OrmException { String str = query.toLowerCase(); LinkedHashMap<Account.Id, AccountInfo> accountMap = Maps.newLinkedHashMap(); List<Account> fullNameMatches = Lists.newArrayList(); List<Account> emailMatches = Lists.newArrayList(); for (Account a : reviewerSuggestionCache.get()) { if (a.getFullName() != null && a.getFullName().toLowerCase().contains(str)) { fullNameMatches.add(a); } else if (a.getPreferredEmail() != null && emailMatches.size() < fullTextMaxMatches && a.getPreferredEmail().toLowerCase().contains(str)) { emailMatches.add(a); } if (fullNameMatches.size() >= fullTextMaxMatches) { break; } } for (Account a : fullNameMatches) { addSuggestion(accountMap, a, new AccountInfo(a.getId()), visibilityControl); if (accountMap.size() >= limit) { break; } } if (accountMap.size() < limit) { for (Account a : emailMatches) { addSuggestion(accountMap, a, new AccountInfo(a.getId()), visibilityControl); if (accountMap.size() >= limit) { break; } } } return Lists.newArrayList(accountMap.values()); }
Source:
public static PrioritizedExecutorService create(Lifecycle lifecycle, DruidProcessingConfig config) { final PrioritizedExecutorService service = new PrioritizedExecutorService( new ThreadPoolExecutor( config.getNumThreads(), config.getNumThreads(), 0L, TimeUnit.MILLISECONDS, config.isFifo() ? PrioritizedTaskBlockingQueue.create(config) : new PriorityBlockingQueue<Runnable>(config.getNumThreads()), new ThreadFactoryBuilder().setDaemon(true).setNameFormat(config.getFormatString()).build() ) ); lifecycle.addHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { } @Override public void stop() { service.shutdownNow(); } } ); return service; }

Target:
public static PrioritizedExecutorService create(Lifecycle lifecycle, DruidProcessingConfig config) { final PrioritizedExecutorService service = new PrioritizedExecutorService( new ThreadPoolExecutor( config.getNumThreads(), config.getNumThreads(), 0L, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), new ThreadFactoryBuilder().setDaemon(true).setNameFormat(config.getFormatString()).build() ), config ); lifecycle.addHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { } @Override public void stop() { service.shutdownNow(); } } ); return service; }
Source:
public Tournament replaceTournament(Tournament tournament) { if (getTournaments() .stream() .noneMatch(dbTournament -> dbTournament.getId().equals(tournament.getId()))) { throw new TournamentNotFoundException(); } return tournamentRepository.save(tournament); }

Target:
public Tournament replaceTournament(Tournament tournament) { if (tournamentRepository.findOne(tournament.getId()) == null) { throw new TournamentNotFoundException(); } return tournamentRepository.save(tournament); }
Source:
public Iterator<IPPollAddress> getExcludingInterator(final Iterator<IPPollAddress> it) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize(it, ORDERED | IMMUTABLE), false ) .filter(item -> { return !isExcluded(item.getAddress());}) .iterator(); }

Target:
public Iterator<IPPollAddress> getExcludingInterator(final Iterator<IPPollAddress> it) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize(it, ORDERED | IMMUTABLE), false ) .filter(item -> !isExcluded(item.getAddress())) .iterator(); }
Source:
private static void openTrace() { final Exception exception[] = new Exception[1]; exception[0] = null; UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { try { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(TRACE_PROJECT_NAME); TmfTraceFolder destinationFolder = TmfProjectRegistry.getProject(project).getTracesFolder(); TmfOpenTraceHelper.openTraceFromPath(destinationFolder, ctt.getPath(), PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "org.eclipse.linuxtools.lttng2.kernel.tracetype"); } catch (CoreException e) { exception[0] = e; } } }); if (exception[0] != null) { fail(exception[0].getMessage()); } SWTBotUtil.delay(1000); SWTBotUtil.waitForJobs(); }

Target:
private static void openTrace() { final Exception exception[] = new Exception[1]; exception[0] = null; UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { try { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(TRACE_PROJECT_NAME); TmfTraceFolder destinationFolder = TmfProjectRegistry.getProject(project, true).getTracesFolder(); TmfOpenTraceHelper.openTraceFromPath(destinationFolder, ctt.getPath(), PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "org.eclipse.linuxtools.lttng2.kernel.tracetype"); } catch (CoreException e) { exception[0] = e; } } }); if (exception[0] != null) { fail(exception[0].getMessage()); } SWTBotUtil.delay(1000); SWTBotUtil.waitForJobs(); }
Source:
public List<ObserverSpecification> getObserverSpecifications() { List<ObserverSpecification> configList = new ArrayList<>(); Iterator<String> iter = getKeys(); while (iter.hasNext()) { String key = iter.next(); if (!key.startsWith(FluoConfiguration.OBSERVER_PROVIDER) && key.startsWith(FluoConfiguration.OBSERVER_PREFIX)) { String value = getString(key).trim(); if (value.isEmpty()) { throw new IllegalArgumentException(key + " is set to empty value"); } String[] fields = value.split(","); if (fields.length == 0) { throw new IllegalArgumentException(key + " has bad value: " + value); } String className = fields[0]; if (className.isEmpty()) { throw new IllegalArgumentException(key + " has empty class name: " + className); } Map<String, String> params = new HashMap<>(); for (int i = 1; i < fields.length; i++) { String[] kv = fields[i].split("="); if (kv.length != 2) { throw new IllegalArgumentException(key + " has invalid param. Expected 'key=value' but encountered '" + fields[i] + "'"); } if (kv[0].isEmpty() || kv[1].isEmpty()) { throw new IllegalArgumentException(key + " has empty key or value in param: " + fields[i]); } params.put(kv[0], kv[1]); } ObserverSpecification observerSpecification = new ObserverSpecification(className, params); configList.add(observerSpecification); } } return configList; }

Target:
public List<ObserverSpecification> getObserverSpecifications() { List<ObserverSpecification> configList = new ArrayList<>(); Iterator<String> iter = getKeys(); while (iter.hasNext()) { String key = iter.next(); if (key.startsWith(FluoConfiguration.OBSERVER_PREFIX) && !key.equals(FluoConfiguration.OBSERVER_PROVIDER)) { String value = getString(key).trim(); if (value.isEmpty()) { throw new IllegalArgumentException(key + " is set to empty value"); } String[] fields = value.split(","); if (fields.length == 0) { throw new IllegalArgumentException(key + " has bad value: " + value); } String className = fields[0]; if (className.isEmpty()) { throw new IllegalArgumentException(key + " has empty class name: " + className); } Map<String, String> params = new HashMap<>(); for (int i = 1; i < fields.length; i++) { String[] kv = fields[i].split("="); if (kv.length != 2) { throw new IllegalArgumentException(key + " has invalid param. Expected 'key=value' but encountered '" + fields[i] + "'"); } if (kv[0].isEmpty() || kv[1].isEmpty()) { throw new IllegalArgumentException(key + " has empty key or value in param: " + fields[i]); } params.put(kv[0], kv[1]); } ObserverSpecification observerSpecification = new ObserverSpecification(className, params); configList.add(observerSpecification); } } return configList; }
Source:
public void sendFile(File file, HttpHeaders headers) throws IOException { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); addContentTypeIfMissing(response.headers().add(headers), OCTET_STREAM_TYPE); HttpUtil.setTransferEncodingChunked(response, false); HttpUtil.setContentLength(response, file.length()); RandomAccessFile raf = new RandomAccessFile(file, "r"); try { checkNotResponded(); channel.write(response); if (sslEnabled) { channel.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 8192))); } else { FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, file.length()); channel.write(region); channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } } catch (Throwable t) { try { raf.close(); } catch (IOException ex) { } throw (IOException) t; } }

Target:
public void sendFile(File file, HttpHeaders headers) throws Throwable { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); addContentTypeIfMissing(response.headers().add(headers), OCTET_STREAM_TYPE); HttpUtil.setTransferEncodingChunked(response, false); HttpUtil.setContentLength(response, file.length()); RandomAccessFile raf = new RandomAccessFile(file, "r"); try { checkNotResponded(); channel.write(response); if (sslEnabled) { channel.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 8192))); } else { FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, file.length()); channel.write(region); channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } } catch (Throwable t) { try { raf.close(); } catch (IOException ex) { } throw t; } }
Source:
public void cancel(Subscription subscription, StreamObserver<Response> responseObserver) { log().debug("Incoming cancel request for the subscription topic: {}", subscription); final BoundedContext boundedContext = selectBoundedContext(subscription); try { final Stand stand = boundedContext.getStand(); stand.cancel(subscription); responseObserver.onNext(Responses.ok()); } catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) { log().error("Error processing cancel subscription request", e); responseObserver.onError(e); responseObserver.onCompleted(); } }

Target:
public void cancel(Subscription subscription, StreamObserver<Response> responseObserver) { log().debug("Incoming cancel request for the subscription topic: {}", subscription); final BoundedContext boundedContext = selectBoundedContext(subscription); try { final Stand stand = boundedContext.getStand(); stand.cancel(subscription); responseObserver.onNext(Responses.ok()); responseObserver.onCompleted(); } catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) { log().error("Error processing cancel subscription request", e); responseObserver.onError(e); } }
Source:
public List<Variant> create(String fileId, String studyId, String line) throws IllegalArgumentException { String[] fields = line.split("\t"); if (fields.length < 8) { throw new IllegalArgumentException("Not enough fields provided (min 8)"); } String chromosome = getChromosomeWithoutPrefix(fields); int position = getPosition(fields); Set<String> ids = getIds(fields); String reference = getReference(fields); String[] alternateAlleles = getAlternateAlleles(fields, chromosome, position, reference); float quality = getQuality(fields); String filter = getFilter(fields); String info = getInfo(fields); String format = getFormat(fields); List<VariantKeyFields> generatedKeyFields = buildVariantKeyFields(chromosome, position, reference, alternateAlleles); List<Variant> variants = new LinkedList<>(); for (int altAlleleIdx = 0; altAlleleIdx < alternateAlleles.length; altAlleleIdx++) { VariantKeyFields keyFields = generatedKeyFields.get(altAlleleIdx); Variant variant = new Variant(chromosome, keyFields.getStart(), keyFields.getEnd(), keyFields.getReference(), keyFields.getAlternate()); String[] secondaryAlternates = getSecondaryAlternates(altAlleleIdx, alternateAlleles); VariantSourceEntry file = new VariantSourceEntry(fileId, studyId, secondaryAlternates, format, null, null, null); variant.addSourceEntry(file); parseSplitSampleData(variant, fileId, studyId, fields, alternateAlleles, secondaryAlternates, altAlleleIdx); setOtherFields(variant, fileId, studyId, ids, quality, filter, info, format, altAlleleIdx, alternateAlleles, line); variants.add(variant); } return variants; }

Target:
public List<Variant> create(String fileId, String studyId, String line) throws IllegalArgumentException { String[] fields = line.split("\t"); if (fields.length < 8) { throw new IllegalArgumentException("Not enough fields provided (min 8)"); } String chromosome = getChromosomeWithoutPrefix(fields); int position = getPosition(fields); Set<String> ids = getIds(fields); String reference = getReference(fields); String[] alternateAlleles = getAlternateAlleles(fields, chromosome, position, reference); float quality = getQuality(fields); String filter = getFilter(fields); String info = getInfo(fields); String format = getFormat(fields); List<VariantCoreFields> generatedKeyFields = buildVariantCoreFields(chromosome, position, reference, alternateAlleles); List<Variant> variants = new LinkedList<>(); for (int altAlleleIdx = 0; altAlleleIdx < alternateAlleles.length; altAlleleIdx++) { VariantCoreFields keyFields = generatedKeyFields.get(altAlleleIdx); Variant variant = new Variant(chromosome, keyFields.getStart(), keyFields.getEnd(), keyFields.getReference(), keyFields.getAlternate()); String[] secondaryAlternates = getSecondaryAlternates(altAlleleIdx, alternateAlleles); VariantSourceEntry file = new VariantSourceEntry(fileId, studyId, secondaryAlternates, format); variant.addSourceEntry(file); parseSplitSampleData(variant, fileId, studyId, fields, alternateAlleles, secondaryAlternates, altAlleleIdx); setOtherFields(variant, fileId, studyId, ids, quality, filter, info, format, altAlleleIdx, alternateAlleles, line); variants.add(variant); } return variants; }
Source:
public FilterSimpleExpression(String field, ConditionOperator operator, @Nullable String value) { fField = field; fOperator = operator; fOriginalValue = value; Pattern pattern = null; if (operator == ConditionOperator.MATCHES) { try { pattern = Pattern.compile(String.valueOf(value)); } catch (PatternSyntaxException e) { } } if (pattern != null) { fValue = new Pair<>(pattern, ConditionOperator.prepareValue(value)); } else { fValue = ConditionOperator.prepareValue(value); } }

Target:
public FilterSimpleExpression(String field, ConditionOperator operator, @Nullable String value) { fField = field; fOperator = operator; fOriginalValue = value; fValue = ConditionOperator.prepareValue(operator, value); }
Source:
public void shouldReturnJSON() throws ServletException, IOException { MockHttpServletResponse mockResponse = new MockHttpServletResponse(); MockHttpServletRequest mockRequest = new MockHttpServletRequest(); mockRequest.addHeader("x-requested-with","XMLHttpRequest"); MotechUser user = new MotechUser(); user.setUserName("testUser"); user.setFailureLoginCounter(3); when(authentication.getName()).thenReturn("testUser"); when(motechUsersDao.findByUserName("testUser")).thenReturn(user); motechLoginSuccessHandler.onAuthenticationSuccess(mockRequest, mockResponse, authentication); assertEquals("SUCCESS", mockResponse.getContentAsString()); }

Target:
public void shouldReturnJSON() throws ServletException, IOException { MockHttpServletResponse mockResponse = new MockHttpServletResponse(); MockHttpServletRequest mockRequest = new MockHttpServletRequest(); mockRequest.addHeader("x-requested-with","XMLHttpRequest"); MotechUser user = new MotechUser(); user.setUserName("testUser"); user.setFailureLoginCounter(3); when(authentication.getName()).thenReturn("testUser"); when(motechUsersDao.findByUserName("testUser")).thenReturn(user); motechLoginSuccessHandler.onAuthenticationSuccess(mockRequest, mockResponse, authentication); MotechJsonMessage message = new MotechJsonMessage("SUCCESS"); assertEquals(message.toJson(), mockResponse.getContentAsString()); }
Source:
private static boolean canUpdateCube(@Nonnull Cube cube) { BlockPos cubeCenter = getCubeCenter(cube); return cube.getCubicWorld().testForCubes(cubeCenter, UPDATE_RADIUS, Objects::nonNull, Requirement.GET_WATCHED); }

Target:
private static boolean canUpdateCube(@Nonnull Cube cube) { BlockPos cubeCenter = getCubeCenter(cube); return cube.getCubicWorld().testForCubes(cubeCenter, UPDATE_RADIUS, Objects::nonNull); }
Source:
public void cleanup() { final float waitStart = System.currentTimeMillis(); synchronizer.globalBarrier(); final float cleanupStart = System.currentTimeMillis(); resetTracers(); pullModels(); computeTracer.start(); final Map<Long, Pair<Vector, Integer>> workloadMap = memoryStore.getAll(); final List<Pair<Vector, Integer>> data = new ArrayList<>(workloadMap.values()); final int numInstances = data.size(); final Tuple3<Double, Double, Float> lossRegLossAccuracy = computeLoss(numInstances, data); computeTracer.end(numInstances); final float cleanupEnd = System.currentTimeMillis(); LOG.log(Level.INFO, "Number of instances: {0}", numInstances); LOG.log(Level.INFO, "Prediction accuracy on training dataset: {0}", lossRegLossAccuracy.getThird()); LOG.log(Level.INFO, "Cleanup Samples: {0}, Avg Comp Per Row: {1}, Sum Comp: {2}, Avg Pull: {3}, Sum Pull: {4}, " + "Elapsed Time: {5}, Wait Time: {6}, Sample Loss Avg: {7}", new Object[]{numInstances, computeTracer.avg(), computeTracer.sum(), pullTracer.avg(), pullTracer.sum(), cleanupEnd - waitStart, cleanupStart - waitStart, lossRegLossAccuracy.getFirst()}); }

Target:
public void cleanup() { final float waitStart = System.currentTimeMillis(); synchronizer.globalBarrier(); final float cleanupStart = System.currentTimeMillis(); resetTracers(); pullModels(); computeTracer.start(); final Map<Long, Pair<Vector, Integer>> workloadMap = memoryStore.getAll(); final List<Pair<Vector, Integer>> data = new ArrayList<>(workloadMap.values()); final int entireDatasetSize = data.size(); final Tuple3<Double, Double, Float> lossRegLossAccuracy = computeLoss(entireDatasetSize, data); computeTracer.end(data.size()); final float cleanupEnd = System.currentTimeMillis(); LOG.log(Level.INFO, "Number of instances: {0}", entireDatasetSize); LOG.log(Level.INFO, "Prediction accuracy on training dataset: {0}", lossRegLossAccuracy.getThird()); LOG.log(Level.INFO, "Cleanup Samples: {0}, Avg Comp Per Row: {1}, Sum Comp: {2}, Avg Pull: {3}, Sum Pull: {4}, " + "Elapsed Time: {5}, Wait Time: {6}, Sample Loss Avg: {7}", new Object[]{entireDatasetSize, computeTracer.avg(), computeTracer.sum(), pullTracer.avg(), pullTracer.sum(), cleanupEnd - waitStart, cleanupStart - waitStart, lossRegLossAccuracy.getFirst()}); }
Source:
public Payment toDerivative(ZonedDateTime dateTime, DoubleTimeSeries<ZonedDateTime> fxFixingHts) { ArgumentChecker.notNull(dateTime, "date"); LocalDate conversionDate = dateTime.toLocalDate(); LocalDate fixingDate = _fxFixingDate.toLocalDate(); double paymentTime = TimeCalculator.getTimeBetween(dateTime, getPaymentDate()); if (conversionDate.isAfter(fixingDate)) { ZonedDateTime rezonedFixingDate = _fxFixingDate.toLocalDate().atStartOfDay(ZoneOffset.UTC); Double fxRate = fxFixingHts.getValue(rezonedFixingDate); if (fxRate == null) { throw new OpenGammaRuntimeException("Could not get fixing value for date " + _fxFixingDate); } double notional = getNotional() * fxRate; return new CouponFixed(getCurrency(), paymentTime, getPaymentYearFraction(), notional, _rate); } if (conversionDate.equals(fixingDate)) { ZonedDateTime rezonedFixingDate = _fxFixingDate.toLocalDate().atStartOfDay(ZoneOffset.UTC); Double fxRate = fxFixingHts.getValue(rezonedFixingDate); if (fxRate != null) { double notional = getNotional() * fxRate; return new CouponFixed(getCurrency(), paymentTime, getPaymentYearFraction(), notional, _rate); } } double fixingTime = TimeCalculator.getTimeBetween(dateTime, _fxFixingDate); double deliveryTime = TimeCalculator.getTimeBetween(dateTime, _fxDeliveryDate); return new CouponFixedFxReset(getCurrency(), paymentTime, getPaymentYearFraction(), getNotional(), _rate, _referenceCurrency, fixingTime, deliveryTime); }

Target:
public Coupon toDerivative(ZonedDateTime dateTime, DoubleTimeSeries<ZonedDateTime> fxFixingHts) { ArgumentChecker.notNull(dateTime, "date"); ArgumentChecker.notNull(fxFixingHts, "time series of FX resets"); LocalDate conversionDate = dateTime.toLocalDate(); LocalDate fixingDate = _fxFixingDate.toLocalDate(); double paymentTime = TimeCalculator.getTimeBetween(dateTime, getPaymentDate()); if (conversionDate.isAfter(fixingDate)) { ZonedDateTime rezonedFixingDate = _fxFixingDate.toLocalDate().atStartOfDay(ZoneOffset.UTC); Double fxRate = fxFixingHts.getValue(rezonedFixingDate); if (fxRate == null) { throw new OpenGammaRuntimeException("Could not get fixing value for date " + _fxFixingDate); } double notional = getNotional() * fxRate; return new CouponFixed(getCurrency(), paymentTime, getPaymentYearFraction(), notional, _rate); } if (conversionDate.equals(fixingDate)) { ZonedDateTime rezonedFixingDate = _fxFixingDate.toLocalDate().atStartOfDay(ZoneOffset.UTC); Double fxRate = fxFixingHts.getValue(rezonedFixingDate); if (fxRate != null) { double notional = getNotional() * fxRate; return new CouponFixed(getCurrency(), paymentTime, getPaymentYearFraction(), notional, _rate); } } double fixingTime = TimeCalculator.getTimeBetween(dateTime, _fxFixingDate); double deliveryTime = TimeCalculator.getTimeBetween(dateTime, _fxDeliveryDate); return new CouponFixedFxReset(getCurrency(), paymentTime, getPaymentYearFraction(), getNotional(), _rate, _referenceCurrency, fixingTime, deliveryTime); }