auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void trigger() { final CloseableHttpClient httpclient = HttpClients.createDefault(); LOG.debug("Sending '" + event + "' event to IFTTT."); try { final HttpPost httpPost = new HttpPost(String.format(IFTTT_URL, event, key)); httpPost.setHeader("Content-type", "application/json"); final StringEntity stringEntity = new StringEntity(String.format(IFTTT_JSON, value1, value2, value3)); httpPost.setEntity(stringEntity); final CloseableHttpResponse closeableHttpResponse = httpclient.execute(httpPost); final int statusCode = closeableHttpResponse.getStatusLine().getStatusCode(); if (statusCode != 200) { LOG.warn("Received HTTP Status for request to with body {}", statusCode, httpPost.getURI(), httpPost.getEntity()); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } }

Target:
public void trigger() { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { LOG.debug("Sending '" + event + "' event to IFTTT."); final HttpPost httpPost = new HttpPost(String.format(IFTTT_URL, event, key)); httpPost.setHeader("Content-type", "application/json"); final StringEntity stringEntity = new StringEntity(String.format(IFTTT_JSON, value1, value2, value3)); httpPost.setEntity(stringEntity); final CloseableHttpResponse closeableHttpResponse = httpclient.execute(httpPost); final int statusCode = closeableHttpResponse.getStatusLine().getStatusCode(); if (statusCode != 200) { LOG.warn("Received HTTP Status for request to with body {}", statusCode, httpPost.getURI(), httpPost.getEntity()); } } catch (IOException e) { LOG.error("Error invoking request: {}", e); } }
Source:
public void testEval() throws Exception { JdbcRowDataLookupFunction lookupFunction = buildRowDataLookupFunction(); lookupFunction.open(null); ListOutputCollector collector = new ListOutputCollector(); lookupFunction.setCollector(collector); lookupFunction.eval(1, StringData.fromString("1")); List<String> result = Lists.newArrayList(collector.getOutputs()).stream() .map(row -> { return String.format("%d,%s,%s,%s", row.getInt(0), row.getString(1), row.getString(2), row.getString(3)); }) .sorted() .collect(Collectors.toList()); List<String> expected = new ArrayList<>(); expected.add("1,1,11-c1-v1,11-c2-v1"); expected.add("1,1,11-c1-v2,11-c2-v2"); Collections.sort(expected); assertEquals(expected, result); }

Target:
public void testEval() throws Exception { JdbcRowDataLookupFunction lookupFunction = buildRowDataLookupFunction(); ListOutputCollector collector = new ListOutputCollector(); lookupFunction.setCollector(collector); lookupFunction.open(null); lookupFunction.eval(1, StringData.fromString("1")); lookupFunction.getDbConnection().close(); lookupFunction.eval(2, StringData.fromString("3")); List<String> result = Lists.newArrayList(collector.getOutputs()).stream() .map(RowData::toString) .sorted() .collect(Collectors.toList()); List<String> expected = new ArrayList<>(); expected.add("+I(1,1,11-c1-v1,11-c2-v1)"); expected.add("+I(1,1,11-c1-v2,11-c2-v2)"); expected.add("+I(2,3,null,23-c2)"); Collections.sort(expected); assertEquals(expected, result); }
Source:
private void checkNoExternalDependencyExposed(DetailAST methodDefToken) { final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (!accessModifier.equals(AccessModifier.PUBLIC) && !accessModifier.equals(AccessModifier.PROTECTED)) { return; } final DetailAST typeToken = methodDefToken.findFirstToken(TokenTypes.TYPE); if (typeToken != null) { getInvalidReturnTypes(typeToken).forEach( (token, returnTypeName) -> log(token, String.format("Class ''%s'', is a class from external dependency. You should not use it as a return type.", returnTypeName))); } final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS); if (parametersToken != null) { getInvalidParameterTypes(parametersToken).forEach( (token, parameterTypeName) -> log(token, String.format("Class ''%s'', is a class from external dependency. You should not use it as a method argument type.", parameterTypeName))); } }

Target:
private void checkNoExternalDependencyExposed(DetailAST methodDefToken) { final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (!accessModifier.equals(AccessModifier.PUBLIC) && !accessModifier.equals(AccessModifier.PROTECTED)) { return; } final DetailAST typeToken = methodDefToken.findFirstToken(TokenTypes.TYPE); if (typeToken != null) { getInvalidReturnTypes(typeToken).forEach( (token, returnTypeName) -> log(token, String.format(EXTERNAL_DEPENDENCY_ERROR, returnTypeName, "return"))); } final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS); if (parametersToken != null) { getInvalidParameterTypes(parametersToken).forEach( (token, parameterTypeName) -> log(token, String.format(EXTERNAL_DEPENDENCY_ERROR, parameterTypeName, "method argument"))); } }
Source:
private static KeyStore getKeyStore(File keyStore, String keyStorePassword) throws KeyStoreLoadException { InputStream inputStream = null; KeyStore ks = null; try { ks = KeyStore.getInstance("JKS"); inputStream = new FileInputStream(keyStore); ks.load(inputStream, keyStorePassword.toCharArray()); } catch (FileNotFoundException e) { throw new KeyStoreLoadException(e); } catch (CertificateException e) { throw new KeyStoreLoadException(e); } catch (NoSuchAlgorithmException e) { throw new KeyStoreLoadException(e); } catch (KeyStoreException e) { throw new KeyStoreLoadException(e); } catch (IOException e) { throw new KeyStoreLoadException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LOG.error("Failed to close an input stream: {}", e); } } } return ks; }

Target:
private static KeyStore getKeyStore(File keyStore, String keyStorePassword) throws IOException { KeyStore ks = null; InputStream is = new FileInputStream(keyStore); try { ks = KeyStore.getInstance("JKS"); ks.load(is, keyStorePassword.toCharArray()); } catch (Exception ex) { if (ex instanceof RuntimeException) { throw ((RuntimeException) ex); } throw new IOException(ex); } finally { Closeables.closeQuietly(is); } return ks; }
Source:
public TaskStateModelFactory(HelixManager manager, Map<String, TaskFactory> taskFactoryRegistry) { this(manager, taskFactoryRegistry, null); }

Target:
public TaskStateModelFactory(HelixManager manager, Map<String, TaskFactory> taskFactoryRegistry) { this(manager, taskFactoryRegistry, Executors.newScheduledThreadPool(TaskUtil .getTargetThreadPoolSize(createZkClient(manager), manager.getClusterName(), manager.getInstanceName()), new ThreadFactory() { private AtomicInteger threadId = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "TaskStateModelFactory-task_thread-" + threadId.getAndIncrement()); } })); }
Source:
public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashSet) { final HashSet<T> that = (HashSet<T>) o; return this.iterator().equals(that.iterator()); } else { return false; } }

Target:
public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashSet) { final HashSet<?> that = (HashSet<?>) o; return this.length() == that.length() && ((HashSet<Object>) this).containsAll(that); } else { return false; } }
Source:
public void testJobOverviewHandler() throws Exception { assertTrue(getRunningJobs(CLUSTER.getClusterClient()).isEmpty()); final JobVertex sender = new JobVertex("Sender"); sender.setParallelism(2); sender.setInvokableClass(BlockingInvokable.class); final JobGraph jobGraph = new JobGraph("Stoppable streaming test job", sender); final JobID jid = jobGraph.getJobID(); ClusterClient<?> clusterClient = CLUSTER.getClusterClient(); clusterClient.submitJob(jobGraph).get(); while (getRunningJobs(CLUSTER.getClusterClient()).isEmpty()) { Thread.sleep(10); } BlockingInvokable.latch.await(); final Duration testTimeout = Duration.ofMinutes(2); final LocalTime deadline = LocalTime.now().plus(testTimeout); String json = TestBaseUtils.getFromHTTP("http://localhost:" + getRestPort() + "/jobs/overview"); ObjectMapper mapper = new ObjectMapper(); JsonNode parsed = mapper.readTree(json); ArrayNode jsonJobs = (ArrayNode) parsed.get("jobs"); assertEquals(1, jsonJobs.size()); assertThat("Duration must be positive", jsonJobs.get(0).get("duration").asInt() > 0); clusterClient.cancel(jobGraph.getJobID()).get(); while (!getRunningJobs(CLUSTER.getClusterClient()).isEmpty()) { Thread.sleep(20); } BlockingInvokable.reset(); }

Target:
public void testJobOverviewHandler() throws Exception { assertTrue(getRunningJobs(CLUSTER.getClusterClient()).isEmpty()); final JobVertex sender = new JobVertex("Sender"); sender.setParallelism(2); sender.setInvokableClass(BlockingInvokable.class); final JobGraph jobGraph = new JobGraph("Stoppable streaming test job", sender); ClusterClient<?> clusterClient = CLUSTER.getClusterClient(); clusterClient.submitJob(jobGraph).get(); while (getRunningJobs(CLUSTER.getClusterClient()).isEmpty()) { Thread.sleep(10); } BlockingInvokable.latch.await(); final Duration testTimeout = Duration.ofMinutes(2); String json = TestBaseUtils.getFromHTTP("http://localhost:" + getRestPort() + "/jobs/overview"); ObjectMapper mapper = new ObjectMapper(); JsonNode parsed = mapper.readTree(json); ArrayNode jsonJobs = (ArrayNode) parsed.get("jobs"); assertEquals(1, jsonJobs.size()); assertThat("Duration must be positive", jsonJobs.get(0).get("duration").asInt() > 0); clusterClient.cancel(jobGraph.getJobID()).get(); while (!getRunningJobs(CLUSTER.getClusterClient()).isEmpty()) { Thread.sleep(20); } BlockingInvokable.reset(); }
Source:
private void insert(final Long id, final Integer sortKey, final Integer firmwareVersion, final Boolean isPublic) { handle.execute(String.format( "Insert INTO file_info (id, sort_key, firmware_version, is_public, type, path, sha, uri, preview_uri, name)\n" + "VALUES (%s, %s, %s, %s, 'SLEEP_SOUND', '', '', '', '', '');", id, sortKey, firmwareVersion, isPublic)); }

Target:
private void insert(final Long id, final Integer sortKey, final Integer firmwareVersion, final Boolean isPublic) { final String insertStatement = "Insert INTO file_info (id, sort_key, firmware_version, is_public, type, path, sha, uri, preview_uri, name)\n" + "VALUES (:id, :sort_key, :firmware_version, :is_public, 'SLEEP_SOUND', '', '', '', '', '');"; handle.createStatement(insertStatement) .bind("id", id) .bind("sort_key", sortKey) .bind("firmware_version", firmwareVersion) .bind("is_public", isPublic) .execute(); }
Source:
private Object getInheritedProperty(Resource resource, String propertyName, Type declaredType, Integer maxLevel) { List<Resource> parentResources = new ArrayList<>(); int count = 0; Resource parentResource = resource.getParent(); do { if (parentResource != null && !parentResource.getResourceType().equals(NameConstants.NT_PAGE)) { parentResources.add(resource.getParent()); count++; } else { break; } parentResource = parentResource.getParent(); } while (count < maxLevel || maxLevel <= 0); return new MergedValueMap(parentResources).get(propertyName, (Class<?>) declaredType); }

Target:
private Object getInheritedProperty(Resource resource, String propertyName, Type declaredType, Integer maxLevel) { int count = 0; Resource parentResource = resource.getParent(); do { if (parentResource != null && !parentResource.getResourceType().equals(NameConstants.NT_PAGE)) { Object value = parentResource.getValueMap().get(propertyName, (Class<?>)declaredType); if (ObjectUtils.anyNotNull(value)) { return value; } count++; } else { break; } parentResource = parentResource.getParent(); } while (count < maxLevel || maxLevel <= 0); return null; }
Source:
public void rollbackCreateTable(Table table) throws MetaException { final Path segmentDescriptorDir = new Path(table.getSd().getLocation()); try { List<DataSegment> dataSegmentList = DruidStorageHandlerUtils .getPublishedSegments(segmentDescriptorDir, getConf()); for (DataSegment dataSegment : dataSegmentList) { try { deleteSegment(dataSegment); } catch (SegmentLoadingException e) { LOG.error(String.format("Error while trying to clean the segment [%s]", dataSegment), e); } } } catch (IOException e) { LOG.error("Exception while rollback", e); Throwables.propagate(e); } }

Target:
public void rollbackCreateTable(Table table) throws MetaException { if (MetaStoreUtils.isExternalTable(table)) { return; } final Path segmentDescriptorDir = getSegmentDescriptorDir(); try { List<DataSegment> dataSegmentList = DruidStorageHandlerUtils .getPublishedSegments(segmentDescriptorDir, getConf()); for (DataSegment dataSegment : dataSegmentList) { try { deleteSegment(dataSegment); } catch (SegmentLoadingException e) { LOG.error(String.format("Error while trying to clean the segment [%s]", dataSegment), e); } } } catch (IOException e) { LOG.error("Exception while rollback", e); throw Throwables.propagate(e); } finally { cleanWorkingDir(); } }
Source:
private boolean useGridMenu(String menuId) { if(menuId == null) { menuId = org.commcare.suite.model.Menu.ROOT_MENU_ID; } if(DeveloperPreferences.isGridMenuEnabled()) { return true; } String commonDisplayStyle = platform.getMenuDisplayStyle(menuId); if("grid".equals(commonDisplayStyle)) { return true; } return false; }

Target:
private boolean useGridMenu(String menuId) { if(menuId == null) { menuId = org.commcare.suite.model.Menu.ROOT_MENU_ID; } if(DeveloperPreferences.isGridMenuEnabled()) { return true; } String commonDisplayStyle = platform.getMenuDisplayStyle(menuId); return MENU_STYLE_GRID.equals(commonDisplayStyle); }
Source:
void handleBody(InputStream payload) throws IOException, MessageFormatException { if (!successfullyDeserialized) { BlobData blobData = MessageFormatRecord.deserializeBlob(payload); BlobType blobType = blobData.getBlobType(); chunkIndexToBuffer = new TreeMap<>(); if (blobType == BlobType.MetadataBlob) { ByteBuffer serializedMetadataContent = blobData.getStream().getByteBuffer(); CompositeBlobInfo compositeBlobInfo = MetadataContentSerDe.deserializeMetadataContentRecord(serializedMetadataContent, blobIdFactory); chunkSize = compositeBlobInfo.getChunkSize(); totalSize = compositeBlobInfo.getTotalSize(); try { List<StoreKey> keys = compositeBlobInfo.getKeys(); if (hasRange) { validatedByteRange = new ValidatedByteRange(options.getRange(), totalSize); firstChunkIndexInRange = (int) (validatedByteRange.getStartOffset() / chunkSize); int lastChunkIndexInByteRange = (int) (validatedByteRange.getEndOffset() / chunkSize); keys = keys.subList(firstChunkIndexInRange, lastChunkIndexInByteRange + 1); } chunkIdIterator = keys.listIterator(); numChunksTotal = keys.size(); dataChunks = new GetChunk[Math.min(keys.size(), NonBlockingRouter.MAX_IN_MEM_CHUNKS)]; for (int i = 0; i < dataChunks.length; i++) { dataChunks[i] = new GetChunk(chunkIdIterator.nextIndex(), (BlobId) chunkIdIterator.next()); } } catch (InvalidByteRangeException e) { onInvalidRange(e.getMessage()); } } else { totalSize = blobData.getSize(); try { if (hasRange) { validatedByteRange = new ValidatedByteRange(options.getRange(), totalSize); } chunkIdIterator = null; dataChunks = null; chunkIndex = 0; numChunksTotal = 1; chunkIndexToBuffer.put(0, filterChunkToRange(blobData)); numChunksRetrieved = 1; } catch (InvalidByteRangeException e) { onInvalidRange(e.getMessage()); } } successfullyDeserialized = true; state = ChunkState.Complete; } else { } }

Target:
void handleBody(InputStream payload) throws IOException, MessageFormatException { if (!successfullyDeserialized) { BlobData blobData = MessageFormatRecord.deserializeBlob(payload); BlobType blobType = blobData.getBlobType(); chunkIndexToBuffer = new TreeMap<>(); if (blobType == BlobType.MetadataBlob) { handleMetadataBlob(blobData); } else { handleSimpleBlob(blobData); } successfullyDeserialized = true; state = ChunkState.Complete; } else { } }
Source:
private HandlerRegistration addListener() { final JavaScriptObject functor = addEventListener(callback_, monitoredElement_); return new HandlerRegistration() { public void removeHandler() { invokeFunctor(functor); } }; }

Target:
private HandlerRegistration addListener() { final JavaScriptObject function = addEventListener(callback_, monitoredElement_); return new HandlerRegistration() { public void removeHandler() { invokeJavaScriptFunction(function); } }; }
Source:
public void close() { super.close(); try { ipfs.getClient().close(); } catch (IOException e) { LOG.info("Couldn't successfully close the ipfsClient"); } executorService.shutdown(); }

Target:
public void close() { super.close(); try { ipfs.getClient().close(); } catch (IOException e) { LOG.info("Couldn't successfully close the ipfsClient", e); } executorService.shutdown(); }
Source:
protected Mono<VirtualNetworkGatewayInner> createInner() { final VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final Mono<Resource> pipObservable; if (defaultIPConfig.publicIPAddressId() == null) { pipObservable = Utils .<PublicIPAddress>rootResource(ensureDefaultPipDefinition().createAsync().last()) .map( publicIPAddress -> { defaultIPConfig.withExistingPublicIPAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { networkObservable = Mono.empty(); } else { assert creatableNetwork != null; networkObservable = Utils .<Network>rootResource(creatableNetwork.createAsync().last()) .map( network -> { defaultIPConfig.withExistingSubnet(network, GATEWAY_SUBNET); return network; }); } return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap( resource -> VirtualNetworkGatewayImpl .this .manager() .inner() .virtualNetworkGateways() .createOrUpdateAsync(resourceGroupName(), name(), inner())); }

Target:
protected Mono<VirtualNetworkGatewayInner> createInner() { final VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final Mono<Resource> pipObservable; if (defaultIPConfig.publicIPAddressId() == null) { pipObservable = Utils .<PublicIPAddress>rootResource(ensureDefaultPipDefinition().createAsync().last()) .map( publicIPAddress -> { defaultIPConfig.withExistingPublicIPAddress(publicIPAddress); return publicIPAddress; }); } else { pipObservable = Mono.empty(); } final Mono<Resource> networkObservable; if (defaultIPConfig.subnetName() != null) { networkObservable = Mono.empty(); } else if (creatableNetwork != null) { networkObservable = Utils .<Network>rootResource(creatableNetwork.createAsync().last()) .map( network -> { defaultIPConfig.withExistingSubnet(network, GATEWAY_SUBNET); return network; }); } else { throw logger.logExceptionAsError(new IllegalStateException("Creatable Network should not be null")); } return Flux .merge(networkObservable, pipObservable) .last(Resource.DUMMY) .flatMap( resource -> VirtualNetworkGatewayImpl .this .manager() .inner() .virtualNetworkGateways() .createOrUpdateAsync(resourceGroupName(), name(), inner())); }
Source:
private static void validateCharacterVal( ReadableConfig tableOptions, ConfigOption<String> option) { if (tableOptions.getOptional(option).isPresent()) { if (tableOptions.get(option).length() != 1) { throw new ValidationException(String.format("Option [%s.%s] must be a Character.", IDENTIFIER, option.key())); } } }

Target:
private static void validateCharacterVal( ReadableConfig tableOptions, ConfigOption<String> option) { if (tableOptions.getOptional(option).isPresent()) { if (tableOptions.get(option).length() != 1) { throw new ValidationException( String.format("Option '%s.%s' must be a string with single character, but was: %s", IDENTIFIER, option.key(), tableOptions.get(option))); } } }
Source:
private static String executeProcess(final CliCommandBuilder commandBuilder, final boolean logFailure, final Map<String, String> env) { Process cliProc = null; try { cliProc = Launcher.of(commandBuilder) .addEnvironmentVariables(env) .launch(); } catch (IOException e) { fail("Failed to start CLI process: " + e.getLocalizedMessage()); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream err = new ByteArrayOutputStream(); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getInputStream(), out); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getErrorStream(), err); boolean wait = true; int runningTime = 0; int exitCode = Integer.MIN_VALUE; try { boolean finished = cliProc.waitFor(CLI_PROC_TIMEOUT, TimeUnit.MILLISECONDS); if (finished) { exitCode = cliProc.exitValue(); } } catch (InterruptedException e1) { new RuntimeException("Interupted while waiting", e1); } finally { cliProc.destroy(); } final String cliOutput = out.toString(); if (logFailure && exitCode != 0) { LOGGER.info("Command's output: '" + cliOutput + "'"); if (err.size() > 0) { LOGGER.info("Command's error log: '" + err.toString() + "'"); } else { LOGGER.info("No output data for the command."); } } return exitCode + ": " + cliOutput; }

Target:
private static String executeProcess(final CliCommandBuilder commandBuilder, final boolean logFailure, final Map<String, String> env) { Process cliProc = null; try { cliProc = Launcher.of(commandBuilder) .addEnvironmentVariables(env) .launch(); } catch (IOException e) { fail("Failed to start CLI process: " + e.getLocalizedMessage()); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream err = new ByteArrayOutputStream(); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getInputStream(), out); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getErrorStream(), err); int exitCode = Integer.MIN_VALUE; try { boolean finished = cliProc.waitFor(CLI_PROC_TIMEOUT, TimeUnit.MILLISECONDS); if (finished) { exitCode = cliProc.exitValue(); } else { LOGGER.info("A timeout has occurred while invoking CLI command."); } } catch (InterruptedException e1) { Assert.fail("Interupted while waiting. Error Message" + e1.getMessage()); } finally { cliProc.destroyForcibly(); } final String cliOutput = out.toString(); if (logFailure && exitCode != 0) { LOGGER.info("Command's output: '" + cliOutput + "'"); if (err.size() > 0) { LOGGER.info("Command's error log: '" + err.toString() + "'"); } else { LOGGER.info("No output data for the command."); } } return exitCode + ": " + cliOutput; }
Source:
boolean update(RawPacket pkt) { boolean changed = false; int seqNum = pkt.getSequenceNumber(); byte[] buf = pkt.getBuffer(); int off = pkt.getOffset(), len = pkt.getLength(); MediaStreamImpl stream = rtpEncoding.getMediaStreamTrack() .getMediaStreamTrackReceiver().getStream(); boolean isSOF = stream.isStartOfFrame(buf, off, len); if (minSeen == -1 || RTPUtils.sequenceNumberDiff(minSeen, seqNum) > 0) { changed = true; inOrder = isSOF; minSeen = seqNum; } if (maxSeen == -1 || RTPUtils.sequenceNumberDiff(maxSeen, seqNum) < 0) { changed = true; maxSeen = seqNum; } if (end == -1 && stream.isEndOfFrame(buf, off, len)) { changed = true; end = seqNum; } if (start == -1 && isSOF) { changed = true; start = seqNum; independent = stream.isKeyFrame(buf, off, len); if (independent) { logger.debug("keyframe,stream=" + stream.hashCode() + " ssrc=" + rtpEncoding.getPrimarySSRC() + "," + toString()); } } return changed; }

Target:
boolean update(RawPacket pkt) { boolean changed = false; int seqNum = pkt.getSequenceNumber(); byte[] buf = pkt.getBuffer(); int off = pkt.getOffset(), len = pkt.getLength(); MediaStreamImpl stream = rtpEncoding.getMediaStreamTrack() .getMediaStreamTrackReceiver().getStream(); boolean isSOF = stream.isStartOfFrame(buf, off, len); if (sofInOrder == null) { sofInOrder = isSOF; } if (minSeen == -1 || RTPUtils.sequenceNumberDiff(minSeen, seqNum) > 0) { changed = true; minSeen = seqNum; } if (maxSeen == -1 || RTPUtils.sequenceNumberDiff(maxSeen, seqNum) < 0) { changed = true; maxSeen = seqNum; } if (end == -1 && stream.isEndOfFrame(buf, off, len)) { changed = true; end = seqNum; } if (start == -1 && isSOF) { changed = true; start = seqNum; independent = stream.isKeyFrame(buf, off, len); if (independent) { if (logger.isInfoEnabled()) { logger.info("keyframe,stream=" + stream.hashCode() + " ssrc=" + rtpEncoding.getPrimarySSRC() + "," + toString()); } } } return changed; }
Source:
public <T extends TopLevelItem> T renameTo(final String newName) { open(); String oldName = name; control(by.href("/job/" + oldName + "/confirm-rename")).click(); WebElement renameButton = waitFor(by.button("Rename")); control(by.name("newName")).set(newName); renameButton.click(); try { return (T) newInstance(getClass(), injector, new URL(url.toExternalForm().replace(oldName, newName)), newName); } catch (MalformedURLException e) { throw new AssertionError("Not a valid url: " + newName, e); } }

Target:
public <T extends TopLevelItem> T renameTo(final String newName) { String oldName = name; if (getJenkins().getVersion().isOlderThan(new VersionNumber("2.110"))) { configure(); control("/name").set(newName); save(); waitFor(by.button("Yes")).click(); } else { open(); control(by.href("/job/" + oldName + "/confirm-rename")).click(); WebElement renameButton = waitFor(by.button("Rename"), 5); control(by.name("newName")).set(newName); renameButton.click(); } try { return (T) newInstance(getClass(), injector, new URL(url.toExternalForm().replace(oldName, newName)), newName); } catch (MalformedURLException e) { throw new AssertionError("Not a valid url: " + newName, e); } }
Source:
private static void checkRfsMatchConfig(KsDef ks, CassandraKeyValueServiceConfig config, Set<String> dcs, Map<String, String> strategyOptions) { for (String dataCenter : dcs) { if (Integer.parseInt(strategyOptions.get(dataCenter)) != config.replicationFactor()) { throw new UnsupportedOperationException("Your current Cassandra keyspace (" + ks.getName() + ") has a replication factor not matching your Atlas Cassandra configuration." + " Change them to match, but be mindful of what steps you'll need to" + " take to correctly repair or cleanup existing data in your cluster."); } } }

Target:
private static void checkRfsMatchConfig(KsDef ks, CassandraKeyValueServiceConfig config, Set<String> dcs, Map<String, String> strategyOptions) { for (String datacenter : dcs) { if (Integer.parseInt(strategyOptions.get(datacenter)) != config.replicationFactor()) { throw new UnsupportedOperationException("Your current Cassandra keyspace (" + ks.getName() + ") has a replication factor not matching your Atlas Cassandra configuration." + " Change them to match, but be mindful of what steps you'll need to" + " take to correctly repair or cleanup existing data in your cluster."); } } }
Source:
public long getAgentUpdateExitTimeout() { long value = m_preferences.getLong(AgentConfigurationConstants.AGENT_UPDATE_EXIT_TIMEOUT_MSECS, AgentConfigurationConstants.DEFAULT_AGENT_UPDATE_EXIT_TIMEOUT_MSECS); return value; }

Target:
public long getAgentUpdateExitTimeout() { return m_preferences.getLong(AgentConfigurationConstants.AGENT_UPDATE_EXIT_TIMEOUT_MSECS, AgentConfigurationConstants.DEFAULT_AGENT_UPDATE_EXIT_TIMEOUT_MSECS); }
Source:
public void testWaitForMemoryAvailable() throws Exception { final GlobalMemoryManager gmm = spy(new GlobalMemoryManager(100, 80)); final ChildMemoryManager rmm1 = new ChildMemoryManager(gmm,100); final ChildMemoryManager rmm2 = new ChildMemoryManager(gmm,100); final CountDownLatch latch = new CountDownLatch(2); Thread t1 = new Thread() { @Override public void run() { MemoryChunk c1 = rmm1.allocate(50); MemoryChunk c2 = rmm1.allocate(50); sleepFor(40); c1.close(); sleepFor(20); c2.close(); latch.countDown(); } }; Thread t2 = new Thread() { @Override public void run() { sleepFor(20); Stopwatch watch = new Stopwatch().start(); MemoryChunk c3 = rmm2.allocate(50); Mockito.verify(gmm, atLeastOnce()).waitForBytesToFree(anyLong(), anyLong()); c3.close(); latch.countDown(); } }; t2.start(); t1.start(); latch.await(1, TimeUnit.SECONDS); ChildMemoryManager rmm = new ChildMemoryManager(gmm,100); MemoryChunk c = rmm.allocate(100); c.close(); assertTrue(rmm.getAvailableMemory() == rmm.getMaxMemory()); assertTrue(rmm1.getAvailableMemory() == rmm1.getMaxMemory()); assertTrue(rmm2.getAvailableMemory() == rmm2.getMaxMemory()); }

Target:
public void testWaitForMemoryAvailable() throws Exception { final GlobalMemoryManager gmm = spy(new GlobalMemoryManager(100, 80)); final ChildMemoryManager rmm1 = new ChildMemoryManager(gmm,100); final ChildMemoryManager rmm2 = new ChildMemoryManager(gmm,100); final CountDownLatch latch = new CountDownLatch(2); Thread t1 = new Thread() { @Override public void run() { MemoryChunk c1 = rmm1.allocate(50); MemoryChunk c2 = rmm1.allocate(50); sleepFor(40); c1.close(); sleepFor(20); c2.close(); latch.countDown(); } }; Thread t2 = new Thread() { @Override public void run() { sleepFor(20); MemoryChunk c3 = rmm2.allocate(50); Mockito.verify(gmm, atLeastOnce()).waitForBytesToFree(anyLong(), anyLong()); c3.close(); latch.countDown(); } }; t2.start(); t1.start(); latch.await(1, TimeUnit.SECONDS); ChildMemoryManager rmm = new ChildMemoryManager(gmm,100); MemoryChunk c = rmm.allocate(100); c.close(); assertTrue(rmm.getAvailableMemory() == rmm.getMaxMemory()); assertTrue(rmm1.getAvailableMemory() == rmm1.getMaxMemory()); assertTrue(rmm2.getAvailableMemory() == rmm2.getMaxMemory()); }
Source:
public Map<String, Object> saveExistingQuestionGroups( @RequestBody QuestionGroupListPayload payLoad) { final Map<String, Object> response = new HashMap<String, Object>(); RestStatusDto statusDto = new RestStatusDto(); statusDto.setStatus("failed"); statusDto.setMessage("No question groups to change"); final List<QuestionGroupDto> requestList = payLoad.getQuestion_groups(); if (requestList != null && requestList.size() > 0) { for (final QuestionGroupDto questionGroupDto : requestList) { if (questionGroupDto != null) { Long keyId = questionGroupDto.getKeyId(); QuestionGroup qg; if (keyId != null) { qg = questionGroupDao.getByKey(keyId); if (qg != null) { BeanUtils.copyProperties(questionGroupDto, qg, new String[] {"createdDateTime", "status"}); qg = questionGroupDao.save(qg); } else { statusDto.setMessage("Cannot change unknown question group " + keyId); response.put("meta", statusDto); return response; } } else { statusDto.setMessage("Cannot change question group without id"); response.put("meta", statusDto); return response; } } } statusDto.setStatus("ok"); statusDto.setMessage(""); } response.put("meta", statusDto); return response; }

Target:
public Map<String, Object> saveExistingQuestionGroups( @RequestBody QuestionGroupListPayload payLoad) { final Map<String, Object> response = new HashMap<String, Object>(); RestStatusDto statusDto = new RestStatusDto(); statusDto.setStatus("failed"); statusDto.setMessage("No question groups to change"); List<QuestionGroup> saveList = new ArrayList<>(); final List<QuestionGroupDto> requestList = payLoad.getQuestion_groups(); if (requestList != null && requestList.size() > 0) { for (final QuestionGroupDto questionGroupDto : requestList) { if (questionGroupDto != null) { Long keyId = questionGroupDto.getKeyId(); QuestionGroup qg; if (keyId != null) { qg = questionGroupDao.getByKey(keyId); if (qg != null) { BeanUtils.copyProperties(questionGroupDto, qg, new String[] {"createdDateTime", "status"}); saveList.add(qg); } else { statusDto.setMessage("Cannot change unknown question group " + keyId); response.put("meta", statusDto); return response; } } else { statusDto.setMessage("Cannot change question group without id"); response.put("meta", statusDto); return response; } } } questionGroupDao.save(saveList); statusDto.setStatus("ok"); statusDto.setMessage(""); } response.put("meta", statusDto); return response; }
Source:
private List<ConstraintViolation> validateListTypeField(Schema schema, List<PathNode> path, Field field, Object value) { assert field.getType().isListType(); List<ConstraintViolation> violations = new ArrayList<ConstraintViolation>(); Collection<?> castedValue = null; if (!field.isNillable() && value == null) { addNotNullViolation(violations, schema, path); } if (value instanceof List) { castedValue = (Collection<?>) value; } else if (value instanceof Object[]) { castedValue = Arrays.asList((Object[]) value); } if (castedValue != null) { if (!field.isNillable() && castedValue.size() < 1) { addNotNullViolation(violations, schema, path); } ListType listType = (ListType) field.getType(); Field listField = listType.getField(); int index = 0; for (Object item : castedValue) { List<PathNode> subPath = new ArrayList<PathNode>(path); subPath.add(new PathNode(listField, index)); violations.addAll(validateAnyTypeField(schema, subPath, listField, item, true)); index++; } return violations; } return violations; }

Target:
private List<ConstraintViolation> validateListTypeField(Schema schema, List<PathNode> path, Field field, Object value) { assert field.getType().isListType(); List<ConstraintViolation> violations = new ArrayList<ConstraintViolation>(); Collection<?> castedValue = null; if (!field.isNillable() && value == null) { addNotNullViolation(violations, schema, path); } if (value instanceof List) { castedValue = (Collection<?>) value; } else if (value instanceof Object[]) { castedValue = Arrays.asList((Object[]) value); } if (castedValue != null) { if (!field.isNillable() && castedValue.isEmpty()) { addNotNullViolation(violations, schema, path); } ListType listType = (ListType) field.getType(); Field listField = listType.getField(); int index = 0; for (Object item : castedValue) { List<PathNode> subPath = new ArrayList<PathNode>(path); subPath.add(new PathNode(listField, index)); violations.addAll(validateAnyTypeField(schema, subPath, listField, item, true)); index++; } return violations; } return violations; }
Source:
private List<AlgorithmModel> filterInclusivelyByAllOrSpecificDataType(List<AlgorithmModel> algorithmModels, DataType dataType) { return (dataType == DataType.All) ? algorithmModels : algorithmModels.stream() .filter(e -> { for (DataType dt : e.getAlgorithm().getAnnotation().dataType()) { if (!(dt == DataType.All || dt == dataType)) { return false; } } return true; }) .collect(Collectors.toList()); }

Target:
private List<AlgorithmModel> filterInclusivelyByAllOrSpecificDataType(List<AlgorithmModel> algorithmModels, DataType dataType) { return (dataType == DataType.All) ? algorithmModels : algorithmModels.stream() .filter(e -> { for (DataType dt : e.getAlgorithm().getAnnotation().dataType()) { if (dt == DataType.All || dt == dataType) { return true; } } return false; }) .collect(Collectors.toList()); }
Source:
public CustomizedStateProvider buildCustomizedStateProvider(String instanceName) { if (_helixManager == null) { throw new HelixException("Helix Manager has not been set yet."); } else { return buildCustomizedStateProvider(_helixManager, instanceName); } }

Target:
public CustomizedStateProvider buildCustomizedStateProvider(String instanceName) { if (_helixManager == null) { throw new HelixException("Helix Manager has not been set yet."); } return buildCustomizedStateProvider(_helixManager, instanceName); }
Source:
public CompletableFuture<Collection<V>> get(K key) { assertRemoteCacheManagerIsStarted(); K compatKey = hasCompatibility() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, true, estimateKeySize, estimateValueSize); GetKeyMultimapOperation<V> gco = operationsFactory.newGetKeyMultimapOperation(compatKey, marshallKey); return CompletableFuture.supplyAsync(() -> gco.execute()); }

Target:
public CompletableFuture<Collection<V>> get(K key) { if (trace) { log.tracef("About to call get (K): (%s)", key); } assertRemoteCacheManagerIsStarted(); K compatKey = hasCompatibility() ? key : null; byte[] marshallKey = MarshallerUtil.obj2bytes(marshaller, key, true, estimateKeySize, estimateValueSize); GetKeyMultimapOperation<V> gco = operationsFactory.newGetKeyMultimapOperation(compatKey, marshallKey); return CompletableFuture.supplyAsync(() -> gco.execute()); }
Source:
public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { ItemStack stack = trackKits.get(random.nextInt(trackKits.size())).getTrackKitItem(2); if (stack == null) return; recipeList.add(new MerchantRecipe(stack, null, new ItemStack(Items.EMERALD, MathHelper.getRandomIntegerInRange(random, 1, 3)))); }

Target:
public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { if (trackKits.size() == 0) return; ItemStack stack = trackKits.get(random.nextInt(trackKits.size())).getTrackKitItem(2); if (stack == null) return; recipeList.add(new MerchantRecipe(stack, null, new ItemStack(Items.EMERALD, MathHelper.getRandomIntegerInRange(random, 1, 3)))); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_provider_management); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { getSupportActionBar().setElevation(0); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } providerManagerDashboardFragment = (ProviderManagerDashboardFragment) getSupportFragmentManager().findFragmentById(R.id.providerManagementContentFrame); if (providerManagerDashboardFragment == null) { providerManagerDashboardFragment = ProviderManagerDashboardFragment.newInstance(); } if (!providerManagerDashboardFragment.isActive()) { addFragmentToActivity(getSupportFragmentManager(), providerManagerDashboardFragment, R.id.providerManagementContentFrame); } if (savedInstanceState != null) { ProviderManagerDashboardPresenter mPresenter = new ProviderManagerDashboardPresenter(providerManagerDashboardFragment); } else { ProviderManagerDashboardPresenter mPresenter = new ProviderManagerDashboardPresenter(providerManagerDashboardFragment); } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_provider_management); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { getSupportActionBar().setElevation(0); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } providerManagerDashboardFragment = (ProviderManagerDashboardFragment) getSupportFragmentManager().findFragmentById(R.id.providerManagementContentFrame); if (providerManagerDashboardFragment == null) { providerManagerDashboardFragment = ProviderManagerDashboardFragment.newInstance(); } if (!providerManagerDashboardFragment.isActive()) { addFragmentToActivity(getSupportFragmentManager(), providerManagerDashboardFragment, R.id.providerManagementContentFrame); } ProviderManagerDashboardPresenter mPresenter = new ProviderManagerDashboardPresenter(providerManagerDashboardFragment); }
Source:
public List<String> getPrimaryKeyColumns() { return new ArrayList<>(_primaryKeyColumns); }

Target:
public List<String> getPrimaryKeyColumns() { return _primaryKeyColumns; }
Source:
private void onRoutingTableUpdateMsg(final AvroElasticMemoryMessage msg) { Trace.setProcessId("eval"); try (final TraceScope onRoutingTableUpdateMsgScope = Trace.startSpan(ON_TABLE_UPDATE_MSG, HTraceUtils.fromAvro(msg.getTraceInfo()))) { final RoutingTableUpdateMsg routingTableUpdateMsg = msg.getRoutingTableUpdateMsg(); final List<Integer> blockIds = routingTableUpdateMsg.getBlockIds(); final int newOwnerId = getStoreId(routingTableUpdateMsg.getNewEvalId().toString()); final int oldOwnerId = getStoreId(routingTableUpdateMsg.getOldEvalId().toString()); LOG.log(Level.INFO, "Update routing table. [newOwner: {0}, oldOwner: {1}, blocks: {2}]", new Object[]{newOwnerId, oldOwnerId, blockIds}); for (final int blockId : blockIds) { router.updateOwnership(blockId, oldOwnerId, newOwnerId); } } }

Target:
private void onRoutingTableUpdateMsg(final AvroElasticMemoryMessage msg) { Trace.setProcessId("eval"); try (final TraceScope onRoutingTableUpdateMsgScope = Trace.startSpan("on_table_update_msg", HTraceUtils.fromAvro(msg.getTraceInfo()))) { final RoutingTableUpdateMsg routingTableUpdateMsg = msg.getRoutingTableUpdateMsg(); final List<Integer> blockIds = routingTableUpdateMsg.getBlockIds(); final int newOwnerId = getStoreId(routingTableUpdateMsg.getNewEvalId().toString()); final int oldOwnerId = getStoreId(routingTableUpdateMsg.getOldEvalId().toString()); LOG.log(Level.INFO, "Update routing table. [newOwner: {0}, oldOwner: {1}, blocks: {2}]", new Object[]{newOwnerId, oldOwnerId, blockIds}); for (final int blockId : blockIds) { router.updateOwnership(blockId, oldOwnerId, newOwnerId); } } }
Source:
public SqlNode expandSelectExpr(SqlNode expr, SelectScope scope, SqlSelect select) { final Expander expander = new SelectExpander(this, scope, select); SqlNode newExpr = expr.accept(expander); if (expr != newExpr) { setOriginal(newExpr, expr); } return newExpr; }

Target:
public SqlNode expandSelectExpr(SqlNode expr, SelectScope scope, SqlSelect select) { final Expander expander = new SelectExpander(this, scope, select); final SqlNode newExpr = expr.accept(expander); if (expr != newExpr) { setOriginal(newExpr, expr); } return newExpr; }
Source:
public void setCurrentUrl( URL urlCurrent ) { oldFeedSource.setCurrentUrl( urlCurrent ); newFeedSource.setCurrentUrl( urlCurrent ); }

Target:
public void setCurrentUrl( URL urlCurrent ) { }
Source:
public void calculate() { final HuffmanTree<Integer> tree; { final int size = countMap.size(); final int[] frequencies = new int[size]; final int[] values = new int[size]; int i = 0; for (final Integer key : countMap.keySet()) { values[i] = key; frequencies[i] = countMap.get(key).value; i++; } tree = HuffmanCode.buildTree(frequencies, autobox(values)); } final List<Integer> valueList = new ArrayList<Integer>(); final List<Integer> lens = new ArrayList<Integer>(); HuffmanCode.getValuesAndBitLengths(valueList, lens, tree); final BitCode[] codes = new BitCode[valueList.size()]; for (int i = 0; i < valueList.size(); i++) { codes[i] = new BitCode(valueList.get(i), lens.get(i)); } Arrays.sort(codes); values = new int[codes.length]; bitLens = new int[codes.length]; for (int i = 0; i < codes.length; i++) { final BitCode code = codes[i]; getBitLens()[i] = code.length; getValues()[i] = code.value; } }

Target:
public void calculate() { final HuffmanTree<Integer> tree; { final int size = countMap.size(); final int[] frequencies = new int[size]; final int[] values = new int[size]; int i = 0; for (final Integer key : countMap.keySet()) { values[i] = key; frequencies[i] = countMap.get(key).value; i++; } tree = HuffmanCode.buildTree(frequencies, autobox(values)); } final List<Integer> valueList = new ArrayList<Integer>(); final List<Integer> lens = new ArrayList<Integer>(); HuffmanCode.getValuesAndBitLengths(valueList, lens, tree); final BitCode[] codes = new BitCode[valueList.size()]; for (int i = 0; i < valueList.size(); i++) { codes[i] = new BitCode(valueList.get(i), lens.get(i)); } Arrays.sort(codes); values = new int[codes.length]; bitLens = new int[codes.length]; for (int i = 0; i < codes.length; i++) { final BitCode code = codes[i]; bitLens[i] = code.length; values[i] = code.value; } }
Source:
private static CloudHealthcare createClient() throws IOException { GoogleCredential credential = GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY) .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM)); HttpRequestInitializer requestInitializer = request -> { credential.initialize(request); request.setConnectTimeout(60000); request.setReadTimeout(60000); }; return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer) .setApplicationName("your-application-name") .build(); }

Target:
private static CloudHealthcare createClient() throws IOException { GoogleCredential credential = GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY) .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM)); HttpRequestInitializer requestInitializer = request -> { credential.initialize(request); request.setConnectTimeout(1 * 60 * 1000); request.setReadTimeout(1 * 60 * 1000); }; return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer) .setApplicationName("your-application-name") .build(); }
Source:
static Period roundToPrecision(Period period, Precision start, Precision end) { if (start == null && end == null) { return period; } if (start == Precision.YEAR && end == null) { return Period.years(period.getYears()); } if (start == Precision.YEAR && end == Precision.MONTH) { return Period.years(period.getYears()).withMonths(period.getMonths()); } if (start == Precision.MONTH && end == null) { return Period.years(period.getYears()).withMonths(period.getMonths()); } if (start == Precision.DAY && end == null) { return new Period(period).withHours(0).withMinutes(0).withSeconds(0).withMillis(0); } if (start == Precision.DAY && end == Precision.HOUR) { return new Period(period).withMinutes(0).withSeconds(0).withMillis(0); } if (start == Precision.DAY && end == Precision.MINUTE) { return new Period(period).withSeconds(0).withMillis(0); } if (start == Precision.DAY && end == Precision.SECOND) { return new Period(period).withMillis(0); } if (start == Precision.HOUR && end == null) { return new Period(period).withMinutes(0).withSeconds(0).withMillis(0); } if (start == Precision.HOUR && end == Precision.MINUTE) { return new Period(period).withSeconds(0).withMillis(0); } if (start == Precision.HOUR && end == Precision.SECOND) { return new Period(period).withMillis(0); } if (start == Precision.MINUTE && end == null) { return new Period(period).withSeconds(0).withMillis(0); } if (start == Precision.MINUTE && end == Precision.SECOND) { return new Period(period).withMillis(0); } if (start == Precision.SECOND && end == null) { return new Period(period).withMillis(0); } throw new IllegalArgumentException(String.format("Invalid start and end combination", start, end)); }

Target:
static Period roundToPrecision(Period period, Precision start, Precision end) { if (start == null && end == null) { return period; } if (start == Precision.YEAR) { if (end == null) { return Period.years(period.getYears()); } if (end == Precision.MONTH) { return Period.years(period.getYears()).withMonths(period.getMonths()); } } if (start == Precision.MONTH && end == null) { return Period.years(period.getYears()).withMonths(period.getMonths()); } if (start == Precision.DAY) { if (end == null) { return period.withHours(0).withMinutes(0).withSeconds(0).withMillis(0); } if (end == Precision.HOUR) { return period.withMinutes(0).withSeconds(0).withMillis(0); } if (end == Precision.MINUTE) { return period.withSeconds(0).withMillis(0); } if (end == Precision.SECOND) { return period.withMillis(0); } } if (start == Precision.HOUR) { if (end == null) { return period.withMinutes(0).withSeconds(0).withMillis(0); } if (end == Precision.MINUTE) { return period.withSeconds(0).withMillis(0); } if (end == Precision.SECOND) { return period.withMillis(0); } } if (start == Precision.MINUTE) { if (end == null) { return period.withSeconds(0).withMillis(0); } if (end == Precision.SECOND) { return period.withMillis(0); } } if (start == Precision.SECOND && end == null) { return period.withMillis(0); } throw new IllegalArgumentException("Invalid start and end combination"); }