auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ListEventsForSubjectTableFactory(boolean showMoreLink) { imageIconPaths.put("NOT_SCHEDULED", "icon icon-clock2"); imageIconPaths.put("SCHEDULED", "icon icon-clock"); imageIconPaths.put("DATA_ENTRY_STARTED", "icon icon-pencil-squared orange"); imageIconPaths.put("COMPLETED", "icon icon-checkbox-checked green"); imageIconPaths.put("STOPPED", "icon icon-stop-circle red"); imageIconPaths.put("SKIPPED", "icon icon-redo"); imageIconPaths.put("SIGNED", "icon icon-icon-sign"); crfColumnImageIconPaths.put(0, "icon icon-file-excel red"); crfColumnImageIconPaths.put(1, "icon icon-doc"); crfColumnImageIconPaths.put(2, "icon icon-pencil-squared orange"); crfColumnImageIconPaths.put(3, "icon icon-pencil-squared orange"); crfColumnImageIconPaths.put(4, "icon icon-icon-doubleDataEntry orange"); crfColumnImageIconPaths.put(5, "icon icon-checkbox-checked green"); crfColumnImageIconPaths.put(6, "icon icon-checkbox-checked green"); crfColumnImageIconPaths.put(7, "icon icon-lock"); this.showMoreLink = showMoreLink; }

Target:
public ListEventsForSubjectTableFactory(boolean showMoreLink) { imageIconPaths.put(StudyEventWorkflowStatusEnum.NOT_SCHEDULED.toString(), "icon icon-clock2"); imageIconPaths.put(StudyEventWorkflowStatusEnum.SCHEDULED.toString(), "icon icon-clock"); imageIconPaths.put(StudyEventWorkflowStatusEnum.DATA_ENTRY_STARTED.toString(), "icon icon-pencil-squared orange"); imageIconPaths.put(StudyEventWorkflowStatusEnum.COMPLETED.toString(), "icon icon-checkbox-checked green"); imageIconPaths.put(StudyEventWorkflowStatusEnum.STOPPED.toString(), "icon icon-stop-circle red"); imageIconPaths.put(StudyEventWorkflowStatusEnum.SKIPPED.toString(), "icon icon-redo"); imageIconPaths.put(StudyEventWorkflowStatusEnum.SIGNED.toString(), "icon icon-icon-sign"); crfColumnImageIconPaths.put(0, "icon icon-file-excel red"); crfColumnImageIconPaths.put(1, "icon icon-doc"); crfColumnImageIconPaths.put(2, "icon icon-pencil-squared orange"); crfColumnImageIconPaths.put(3, "icon icon-pencil-squared orange"); crfColumnImageIconPaths.put(4, "icon icon-icon-doubleDataEntry orange"); crfColumnImageIconPaths.put(5, "icon icon-checkbox-checked green"); crfColumnImageIconPaths.put(6, "icon icon-checkbox-checked green"); crfColumnImageIconPaths.put(7, "icon icon-lock"); this.showMoreLink = showMoreLink; }
Source:
public int emitBatches() { Database database = oma.getDatabase(mixing.getDescriptor(SQLReplicationTask.class).getRealm()); AtomicInteger numberOfBatches = new AtomicInteger(maxBatches); AtomicInteger scheduledTasks = new AtomicInteger(0); emitter.computeBatches(SQLReplicationTask.class, qry -> enhanceQuery(qry, true), batchSize, batch -> { distributedTasks.submitFIFOTask(ReplicationTaskExecutor.class, batch); scheduledTasks.addAndGet(batchSize); markTasksAsScheduled(database, batch); return numberOfBatches.decrementAndGet() > 0; }); return scheduledTasks.get(); }

Target:
public int emitBatches() { Database database = oma.getDatabase(mixing.getDescriptor(SQLReplicationTask.class).getRealm()); AtomicInteger numberOfBatches = new AtomicInteger(maxBatches); AtomicInteger scheduledTasks = new AtomicInteger(0); emitter.computeBatches(SQLReplicationTask.class, query -> filterOnExecutableTasks(query, true), batchSize, batch -> { distributedTasks.submitFIFOTask(ReplicationTaskExecutor.class, batch); scheduledTasks.addAndGet(batchSize); markTasksAsScheduled(database, batch); return numberOfBatches.decrementAndGet() > 0; }); return scheduledTasks.get(); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final VolumeFromImage that = (VolumeFromImage) o; return name.equals(that.name); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (!super.equals(o)) return false; final VolumeFromImage that = (VolumeFromImage) o; return this.volumeSize == that.volumeSize; }
Source:
public void grantSystemPermissions(String userId) { try { AbstractPermissionsDomain<? extends AbstractPermissions> systemDomain = permissionsManager.getDomain(SystemDomain.DOMAIN_ID); permissionsManager.storePermission( systemDomain.newInstance(userId, null, systemDomain.getAllowedActions())); } catch (ServerException | NotFoundException | ConflictException e) { LOG.warn( format("System permissions creation failed for user %s", userId), e.getLocalizedMessage()); } }

Target:
public void grantSystemPermissions(String userId) { try { AbstractPermissionsDomain<? extends AbstractPermissions> systemDomain = permissionsManager.getDomain(SystemDomain.DOMAIN_ID); permissionsManager.storePermission( systemDomain.newInstance(userId, null, systemDomain.getAllowedActions())); } catch (ServerException | NotFoundException | ConflictException e) { LOG.warn(format("System permissions creation failed for user %s", userId), e); } }
Source:
public void addParserConfig(String description, String path) { String rulePath = createPageArea("rule", new Runnable() { @Override public void run() { addButton.click(); } }); Rule rule = new Rule(getPage(), rulePath); rule.description.set(description); rule.path.set(path); }

Target:
public void addParserConfig(String description, String path) { String rulePath = createPageArea("rule", () -> addButton.click()); Rule rule = new Rule(getPage(), rulePath); rule.description.set(description); rule.path.set(path); }
Source:
public String getValue(String value, Attribute attr) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(value); } catch (JsonProcessingException e) { log.warn("Error converting to JSON", value, e); return null; } }

Target:
public String getValue(String value, Attribute attr) { try { return mapper.writeValueAsString(value); } catch (JsonProcessingException e) { log.warn("Error converting to JSON", value, e); return null; } }
Source:
protected void saveOffsets() { if (tailer != null) { tailer.commit(); Span span = Tracing.getTracer().getCurrentSpan(); span.addAnnotation("Checkpoint positions" + Instant.now().toString()); } }

Target:
protected void saveOffsets() { if (tailer != null) { tailer.commit(); Span span = Tracing.getTracer().getCurrentSpan(); span.addAnnotation("Checkpoint positions at " + Instant.now()); } }
Source:
public OptimalAssignment calculate(ClusterModel clusterModel) { OptimalAssignment optimalAssignment = new OptimalAssignment(); Map<String, Set<AssignableReplica>> replicasByResource = clusterModel.getAssignableReplicaMap(); List<AssignableNode> nodes = new ArrayList<>(clusterModel.getAssignableNodes().values()); for (String resource : replicasByResource.keySet()) { for (AssignableReplica replica : replicasByResource.get(resource)) { Optional<AssignableNode> maybeBestNode = getNodeWithHighestPoints(replica, nodes, clusterModel.getContext(), optimalAssignment); if (optimalAssignment.hasAnyFailure()) { LOG.error("Unable to find any available candidate node for partition {}; Fail reasons: {}", replica.getPartitionName(), optimalAssignment.getFailures()); return optimalAssignment; } maybeBestNode.ifPresent(node -> clusterModel.assign(replica.getResourceName(), replica.getPartitionName(), replica.getReplicaState(), node.getInstanceName())); } } return optimalAssignment.convertFrom(clusterModel); }

Target:
public OptimalAssignment calculate(ClusterModel clusterModel) throws HelixRebalanceException { OptimalAssignment optimalAssignment = new OptimalAssignment(); Map<String, Set<AssignableReplica>> replicasByResource = clusterModel.getAssignableReplicaMap(); List<AssignableNode> nodes = new ArrayList<>(clusterModel.getAssignableNodes().values()); for (String resource : replicasByResource.keySet()) { for (AssignableReplica replica : replicasByResource.get(resource)) { Optional<AssignableNode> maybeBestNode = getNodeWithHighestPoints(replica, nodes, clusterModel.getContext(), optimalAssignment); if (optimalAssignment.hasAnyFailure()) { String errorMessage = String.format( "Unable to find any available candidate node for partition %s; Fail reasons: %s", replica.getPartitionName(), optimalAssignment.getFailures()); throw new HelixRebalanceException(errorMessage, HelixRebalanceException.Type.FAILED_TO_CALCULATE); } maybeBestNode.ifPresent(node -> clusterModel.assign(replica.getResourceName(), replica.getPartitionName(), replica.getReplicaState(), node.getInstanceName())); } } return optimalAssignment.convertFrom(clusterModel); }
Source:
private IkeSessionStateMachine makeAndStartIkeSession(IkeSessionParams ikeParams) throws Exception { IkeSessionStateMachine ikeSession = new IkeSessionStateMachine( mLooper.getLooper(), mSpyContext, mIpSecManager, ikeParams, mChildSessionParams, mSpyUserCbExecutor, mMockIkeSessionCallback, mMockChildSessionCallback, mMockEapAuthenticatorFactory); ikeSession.setDbg(true); assertFalse(mSecureRandom instanceof DeterministicSecureRandom); mLooper.dispatchAll(); ikeSession.mLocalAddress = LOCAL_ADDRESS; assertEquals(REMOTE_ADDRESS, ikeSession.mRemoteAddress); mSpyIkeUdp4Socket = spy(IkeUdp4Socket.getInstance(mMockDefaultNetwork, ikeSession)); mSpyIkeUdp6Socket = spy(IkeUdp6Socket.getInstance(mMockDefaultNetwork, ikeSession)); mSpyIkeUdpEncapSocket = spy( IkeUdpEncapSocket.getIkeUdpEncapSocket( mMockDefaultNetwork, mIpSecManager, ikeSession)); doNothing().when(mSpyIkeUdp4Socket).sendIkePacket(any(), any()); doNothing().when(mSpyIkeUdp6Socket).sendIkePacket(any(), any()); doNothing().when(mSpyIkeUdpEncapSocket).sendIkePacket(any(), any()); mSpyCurrentIkeSocket = mSpyIkeUdp4Socket; ikeSession.mIkeSocket = mSpyCurrentIkeSocket; return ikeSession; }

Target:
private IkeSessionStateMachine makeAndStartIkeSession(IkeSessionParams ikeParams) throws Exception { IkeSessionStateMachine ikeSession = new IkeSessionStateMachine( mLooper.getLooper(), mSpyContext, mIpSecManager, ikeParams, mChildSessionParams, mSpyUserCbExecutor, mMockIkeSessionCallback, mMockChildSessionCallback, mMockEapAuthenticatorFactory); ikeSession.setDbg(true); mLooper.dispatchAll(); ikeSession.mLocalAddress = LOCAL_ADDRESS; assertEquals(REMOTE_ADDRESS, ikeSession.mRemoteAddress); mSpyIkeUdp4Socket = spy(IkeUdp4Socket.getInstance(mMockDefaultNetwork, ikeSession)); mSpyIkeUdp6Socket = spy(IkeUdp6Socket.getInstance(mMockDefaultNetwork, ikeSession)); mSpyIkeUdpEncapSocket = spy( IkeUdpEncapSocket.getIkeUdpEncapSocket( mMockDefaultNetwork, mIpSecManager, ikeSession)); doNothing().when(mSpyIkeUdp4Socket).sendIkePacket(any(), any()); doNothing().when(mSpyIkeUdp6Socket).sendIkePacket(any(), any()); doNothing().when(mSpyIkeUdpEncapSocket).sendIkePacket(any(), any()); mSpyCurrentIkeSocket = mSpyIkeUdp4Socket; ikeSession.mIkeSocket = mSpyCurrentIkeSocket; return ikeSession; }
Source:
public ContentDto getContent(Long versionId) { try { final ContentVersion contentVersion = versioningManager.getVersion(versionId); final Content content = versioningManager.getContent(contentVersion); final ContentDto contentDto = contentService.getDtoBuilder().convert(content); return contentDto; } catch (ApsSystemException e) { e.printStackTrace(); } return null; }

Target:
public ContentDto getContent(Long versionId) { try { final ContentVersion contentVersion = versioningManager.getVersion(versionId); final Content content = versioningManager.getContent(contentVersion); final ContentDto contentDto = contentService.getDtoBuilder().convert(content); return contentDto; } catch (ApsSystemException e) { logger.error("Error reading the content from version ", versionId, e); } return null; }
Source:
public void testCloudWithAPI() throws Exception { final String OUTPUT = TEST_OUTPUT_GCS_FOLDER + "CountReadsITCase-testCloudWithAPI-output.txt"; String[] ARGS = { "--apiKey=" + API_KEY, "--project=" + TEST_PROJECT, "--output=" + OUTPUT, "--numWorkers=2", "--runner=BlockingDataflowPipelineRunner", "--stagingLocation=" + TEST_STAGING_GCS_FOLDER, "--references=1:550000:560000", "--readGroupSetId=" + TEST_READGROUPSET }; final long EXPECTED = 685; GenomicsOptions popts = PipelineOptionsFactory.create().as(GenomicsOptions.class); popts.setApiKey(API_KEY); GcsUtil gcsUtil = new GcsUtil.GcsUtilFactory().create(popts); touchOutput(gcsUtil, OUTPUT); CountReads.main(ARGS); BufferedReader reader = new BufferedReader(Channels.newReader(gcsUtil.open(GcsPath.fromUri(OUTPUT)), "UTF-8")); long got = Long.parseLong(reader.readLine()); Assert.assertEquals(EXPECTED, got); }

Target:
public void testCloudWithAPI() throws Exception { final String OUTPUT = TEST_OUTPUT_GCS_FOLDER + "CountReadsITCase-testCloudWithAPI-output.txt"; String[] ARGS = { "--apiKey=" + API_KEY, "--project=" + TEST_PROJECT, "--output=" + OUTPUT, "--numWorkers=2", "--runner=BlockingDataflowPipelineRunner", "--stagingLocation=" + TEST_STAGING_GCS_FOLDER, "--references=" + TEST_CONTIG, "--readGroupSetId=" + TEST_READGROUPSET }; GenomicsOptions popts = PipelineOptionsFactory.create().as(GenomicsOptions.class); popts.setApiKey(API_KEY); GcsUtil gcsUtil = new GcsUtil.GcsUtilFactory().create(popts); touchOutput(gcsUtil, OUTPUT); CountReads.main(ARGS); BufferedReader reader = new BufferedReader(Channels.newReader(gcsUtil.open(GcsPath.fromUri(OUTPUT)), "UTF-8")); long got = Long.parseLong(reader.readLine()); Assert.assertEquals(TEST_EXPECTED, got); }
Source:
public static JobConf configureCompression(Configuration config, HiveCompressionCodec compression) { JobConf result; if (config instanceof FileSystemFactory) { checkArgument(config instanceof JobConf, "config is not an instance of JobConf: %s", config.getClass()); checkArgument(config.get(IS_NOT_A_COPY) == null, "config is not a copy"); config.set(IS_NOT_A_COPY, Boolean.TRUE.toString()); result = (JobConf) config; } else { result = new JobConf(false); copy(config, result); } setCompressionProperties(result, compression); return result; }

Target:
public static JobConf configureCompression(Configuration config, HiveCompressionCodec compression) { JobConf result; if (config instanceof FileSystemFactory) { checkArgument(config instanceof JobConf, "config is not an instance of JobConf: %s", config.getClass()); result = (JobConf) config; } else { result = new JobConf(false); copy(config, result); } setCompressionProperties(result, compression); return result; }
Source:
public byte[] convertFromJson(String jsonValue) { return convertFromString(ValueType.readJson(jsonValue, String.class)); }

Target:
public byte[] convertFromJson(String jsonValue) { return convertFromString(jsonValue); }
Source:
private float[] calculateRubricAverage(List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question) { FeedbackRubricQuestionDetails fqd = (FeedbackRubricQuestionDetails) question.getQuestionDetails(); float[][] percentageFrequency = calculateRubricStats(responses, question); float[] average = new float[fqd.numOfRubricSubQuestions]; for(int i=0; i<fqd.numOfRubricSubQuestions ; i++){ int[] rubricChoiceWeight = getChoiceAssginedWeight(fqd.rubricChoices); if(rubricChoiceWeight != null){ for(int j=0; j<fqd.numOfRubricChoices ; j++){ average[i] += rubricChoiceWeight[j] * percentageFrequency[i][j]; } }else{ for(int j=0; j<fqd.numOfRubricChoices ; j++){ average[i] += (fqd.numOfRubricChoices - j) * percentageFrequency[i][j]; } } } return average; }

Target:
private float[] calculateRubricAverage(List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question) { FeedbackRubricQuestionDetails fqd = (FeedbackRubricQuestionDetails) question.getQuestionDetails(); float[][] percentageFrequency = calculateRubricStats(responses, question); float[] average = new float[fqd.numOfRubricSubQuestions]; for(int i = 0; i < fqd.numOfRubricSubQuestions; i++){ for(int j = 0; j < fqd.numOfRubricChoices; j++){ average[i] += (fqd.numOfRubricChoices - j) * percentageFrequency[i][j]; } } return average; }
Source:
public void compare() { if (clockHasNotMovedForwards()) { return; } if (hasTooMuchTimeElapsedSincePreviousRequest()) { events.tooMuchTimeSincePreviousRequest(minElapsedTime); return; } if (requestsTookTooLongToComplete()) { events.requestsTookTooLong(minElapsedTime, maxElapsedTime); return; } long skew = getSkew(); events.clockSkew(server, skew); }

Target:
public void compare() { if (clockHasMovedBackwards()) { return; } long skew = getSkew(); events.clockSkew(server, skew, minElapsedTime, lastRequestDuration); }
Source:
public void canClickALine() throws Exception { SWTBotTableItem line = table.getTableItem("Index:2"); bot.button("Clear").click(); line.click(); assertTextContains("MouseDown [3]: MouseEvent{Table ", listeners); assertTextContains("Selection [13]: SelectionEvent{Table ", listeners); assertEquals(1, table.selectionCount()); }

Target:
public void canClickALine() throws Exception { String ITEM_TEXT = "Index:2"; SWTBotTableItem line = table.getTableItem(ITEM_TEXT); bot.button("Clear").click(); line.click(); assertTextContains("MouseDown [3]: MouseEvent{Table ", listeners); assertTextContains("Selection [13]: SelectionEvent{Table ", listeners); assertEquals(1, table.selectionCount()); assertEquals(ITEM_TEXT, table.selection().get(0).get(0)); }
Source:
public RemoteOperation buildOperation() { if (mGrantType != OAuth2GrantType.AUTHORIZATION_CODE && mGrantType != OAuth2GrantType.REFRESH_TOKEN) { throw new UnsupportedOperationException( "Unsupported grant type. Only " + OAuth2GrantType.AUTHORIZATION_CODE.getValue() + " and " + OAuth2GrantType.REFRESH_TOKEN + " are supported" ); } OAuth2ClientConfiguration clientConfiguration = mOAuth2Provider.getClientConfiguration(); switch(mRequest) { case CREATE_ACCESS_TOKEN: return new OAuth2GetAccessTokenOperation( mGrantType.getValue(), mCode, clientConfiguration.getClientId(), clientConfiguration.getClientSecret(), clientConfiguration.getRedirectUri(), mOAuth2Provider.getAccessTokenEndpointPath() ); case REFRESH_ACCESS_TOKEN: return new OAuth2GetRefreshedAccessTokenOperation( mGrantType.getValue(), clientConfiguration.getClientId(), clientConfiguration.getClientSecret(), mRefreshToken, mOAuth2Provider.getAccessTokenEndpointPath() ); default: throw new UnsupportedOperationException( "Unsupported request" ); } }

Target:
public RemoteOperation buildOperation() { if (mGrantType != OAuth2GrantType.AUTHORIZATION_CODE && mGrantType != OAuth2GrantType.REFRESH_TOKEN) { throw new UnsupportedOperationException( "Unsupported grant type. Only " + OAuth2GrantType.AUTHORIZATION_CODE.getValue() + " and " + OAuth2GrantType.REFRESH_TOKEN + " are supported" ); } OAuth2ClientConfiguration clientConfiguration = mOAuth2Provider.getClientConfiguration(); switch(mRequest) { case CREATE_ACCESS_TOKEN: return new OAuth2GetAccessTokenOperation( mGrantType.getValue(), mCode, clientConfiguration.getClientId(), clientConfiguration.getClientSecret(), clientConfiguration.getRedirectUri(), mOAuth2Provider.getAccessTokenEndpointPath() ); case REFRESH_ACCESS_TOKEN: return new OAuth2RefreshAccessTokenOperation( clientConfiguration.getClientId(), clientConfiguration.getClientSecret(), mRefreshToken, mOAuth2Provider.getAccessTokenEndpointPath() ); default: throw new UnsupportedOperationException( "Unsupported request" ); } }
Source:
private RadioGroupItem createRadioItemToModifyPluginField(PluginDescriptor plugin, PluginDescriptor.Field pluginField) { String formItemPrefixName = plugin.getPluginName() + pluginField.getName(); LinkedHashMap<String, String> radioOptions = new LinkedHashMap<>(); radioOptions.put(EDIT_RADIO_OPTION_NAME, "In-line editing"); radioOptions.put(UPLOAD_RADIO_OPTION_NAME, "Upload new file"); RadioGroupItem editOrUploadFormItem = new RadioGroupItem(formItemPrefixName + EDIT_OR_UPLOAD_FORM_ITEM_SUFFIX, pluginField.getName()); editOrUploadFormItem.setValueMap(radioOptions); editOrUploadFormItem.setVertical(false); editOrUploadFormItem.setDefaultValue(EDIT_RADIO_OPTION_NAME); editOrUploadFormItem.addChangedHandler(changedEvent -> { String radioValue = changedEvent.getValue().toString(); List<FormItem> formItemsForPlugin = this.nodeSourceWindow.getFormItemsOfPlugin(plugin.getPluginName()); if (radioValue.equals(EDIT_RADIO_OPTION_NAME)) { enableEditInLine(formItemPrefixName, formItemsForPlugin); } else if (radioValue.equals(UPLOAD_RADIO_OPTION_NAME)) { enableUploadNewFile(formItemPrefixName, formItemsForPlugin); } }); return editOrUploadFormItem; }

Target:
private RadioGroupItem createRadioItemToModifyPluginField(PluginDescriptor plugin, PluginDescriptor.Field pluginField) { String formItemPrefixName = plugin.getPluginName() + pluginField.getName(); LinkedHashMap<String, String> radioOptions = new LinkedHashMap<>(); radioOptions.put(EDIT_RADIO_OPTION_NAME, "In-line editing"); radioOptions.put(UPLOAD_RADIO_OPTION_NAME, "Upload new file"); RadioGroupItem editOrUploadFormItem = new RadioGroupItem(formItemPrefixName + EDIT_OR_UPLOAD_FORM_ITEM_SUFFIX, pluginField.getName()); editOrUploadFormItem.setValueMap(radioOptions); editOrUploadFormItem.setVertical(false); editOrUploadFormItem.setDefaultValue(EDIT_RADIO_OPTION_NAME); editOrUploadFormItem.addChangedHandler(changedEvent -> { String radioValue = changedEvent.getValue().toString(); List<FormItem> formItemsForPlugin = this.nodeSourceWindow.getFormItemsOfPlugin(plugin.getPluginName()); if (radioValue.equals(EDIT_RADIO_OPTION_NAME)) { enableOrDisableEditInLine(formItemPrefixName, formItemsForPlugin); } else if (radioValue.equals(UPLOAD_RADIO_OPTION_NAME)) { enableOrDisableUploadNewFile(formItemPrefixName, formItemsForPlugin); } }); return editOrUploadFormItem; }
Source:
public static long[] encodeDateTime( int keyId, long epochSecond, long nanoOfSecond, String zoneId ) { int idBits = StandardFormatSettings.PROPERTY_TOKEN_MAXIMUM_ID_BITS; short zoneNumber = TimeZoneMapping.TIME_ZONE_STRING_TO_SHORT.get( zoneId ); long keyAndType = keyId | (((long) (PropertyType.TEMPORAL.intValue()) << idBits)); long temporalTypeBits = TemporalType.TEMPORAL_DATE_TIME.temporalType << (idBits + 4); long[] data = new long[3]; data[0] = keyAndType | temporalTypeBits | (nanoOfSecond << 33); data[1] = epochSecond; data[2] = zoneNumber; return data; }

Target:
public static long[] encodeDateTime( int keyId, long epochSecond, long nanoOfSecond, String zoneId ) { int idBits = StandardFormatSettings.PROPERTY_TOKEN_MAXIMUM_ID_BITS; short zoneNumber = TimeZoneMapping.map( zoneId ); long keyAndType = keyId | (((long) (PropertyType.TEMPORAL.intValue()) << idBits)); long temporalTypeBits = TemporalType.TEMPORAL_DATE_TIME.temporalType << (idBits + 4); long[] data = new long[BLOCKS_DATETIME]; data[0] = keyAndType | temporalTypeBits | (nanoOfSecond << 33); data[1] = epochSecond; data[2] = zoneNumber; return data; }
Source:
public void addLostEvents(TmfTimeRange tr, int lostEvents) { if (tr.getStartTime().getValue() < 0 || tr.getEndTime().getValue() < 0) { return; } final Pair<Integer, TmfTimeRange> infos = new Pair<Integer, TmfTimeRange>(lostEvents, tr); final Pair<Integer, Integer> pair = new Pair<Integer, Integer>(0, 0); lostEventsRangeBars.add(pair); lostEventInfos.add(infos); setMaxAggregateValue(lostEvents); }

Target:
public void addLostEvents(TmfTimeRange tr, int lostEvents) { if (tr.getStartTime().getValue() < 0 || tr.getEndTime().getValue() < 0) { return; } boolean found = false; for (int i = 0; i < lostEventInfos.size() && found == true; i++) { Pair<Integer, TmfTimeRange> info = lostEventInfos.get(i); if (isFullyOverlapped(info.getSecond(), tr)) { long start = Math.min(tr.getStartTime().getValue(), info.getSecond().getStartTime().getValue()); long end = Math.max(tr.getEndTime().getValue(), info.getSecond().getEndTime().getValue()); TmfTimeRange timeRange = new TmfTimeRange( new TmfTimestamp(start, ITmfTimestamp.NANOSECOND_SCALE), new TmfTimestamp(end, ITmfTimestamp.NANOSECOND_SCALE)); int nbLostEvents = lostEvents + info.getFirst(); info = new Pair<Integer, TmfTimeRange>(nbLostEvents, timeRange); found = true; } } if (!found) { final Pair<Integer, TmfTimeRange> infos = new Pair<Integer, TmfTimeRange>(lostEvents, tr); lostEventInfos.add(infos); } }
Source:
public void testSensorDefinition() { org.fest.assertions.Assertions.assertThat(sensor.toString()).isEqualTo("JaCoCoOverallSensor"); }

Target:
public void testSensorDefinition() { assertThat(sensor.toString()).isEqualTo("JaCoCoOverallSensor"); }
Source:
public List<WebElement> getHeadings() { return getWrappedElement().findElements(By.cssSelector("th")); }

Target:
public List<WebElement> getHeadings() { return getWrappedElement().findElements(By.xpath(". }
Source:
public DataTransactionResult offerToStore(ValueContainer<?> container, E value) { for (ValueProcessor<E, V> processor : this.processors) { if (processor.supports(container)) { final DataTransactionResult result = processor.offerToStore(container, value); if (!result.getType().equals(DataTransactionResult.Type.FAILURE)) { return result; } } } for (ValueProcessor<E, V> processor : this.processors) { if (processor.supports(container)) { final Optional<V> currentValueOptional = processor.getApiValueFromContainer(container); if (currentValueOptional.isPresent()) { V currentValue = currentValueOptional.get(); Value<E> rejectedValue; if (currentValue instanceof Value<?>) { rejectedValue = (Value<E>) currentValue; } else { rejectedValue = ((ImmutableValue<E>) currentValue).asMutable(); } rejectedValue.set(value); return DataTransactionResult.failResult(rejectedValue.asImmutable()); } } } return DataTransactionResult.failNoData(); }

Target:
public DataTransactionResult offerToStore(ValueContainer<?> container, E value) { for (ValueProcessor<E, V> processor : this.processors) { if (processor.supports(container)) { final DataTransactionResult result = processor.offerToStore(container, value); if (!result.getType().equals(DataTransactionResult.Type.FAILURE)) { return result; } } } for (ValueProcessor<E, V> processor : this.processors) { if (processor.supports(container)) { final Optional<V> currentValueOptional = processor.getApiValueFromContainer(container); if (currentValueOptional.isPresent()) { V currentValue = currentValueOptional.get(); ImmutableValue<?> rejectedValue; if (currentValue instanceof Value<?>) { Value<E> mutableCurrentValue = (Value<E>) currentValue; mutableCurrentValue.set(value); rejectedValue = mutableCurrentValue.asImmutable(); } else { ImmutableValue<E> immutableCurrentValue = (ImmutableValue<E>) currentValue; rejectedValue = immutableCurrentValue.with(value); } return DataTransactionResult.failResult(rejectedValue); } } } return DataTransactionResult.failNoData(); }
Source:
private static String fixedCodeBlocks(final String txt) { return txt .replace("<code>`\r\n", MarkdownTxtmark.PRE_CODE) .replace("<code>`\n", MarkdownTxtmark.PRE_CODE) .replace("<code>`", MarkdownTxtmark.PRE_CODE) .replace("\r\n</code>`", MarkdownTxtmark.END_CODE_PRE) .replace("\n</code>`", MarkdownTxtmark.END_CODE_PRE) .replace("</code>`", MarkdownTxtmark.END_CODE_PRE); }

Target:
private static String fixedCodeBlocks(final String txt) { return MarkdownTxtmark.CODE_BLOCK_END.matcher( MarkdownTxtmark.CODE_BLOCK_START .matcher(txt) .replaceAll("<pre><code>") ).replaceAll("</code></pre>"); }
Source:
public void validateInputTask(T task) { task.setJobStartTime(OffsetDateTime.now()); }

Target:
public void validateInputTask(T task) { task.setJobStartTime(OffsetDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); }
Source:
private Set<AccountGroup.Id> getIncludedGroups(Set<AccountGroup.Id> seedGroups) { Set<AccountGroup.Id> includedGroups = new HashSet<AccountGroup.Id> (seedGroups); Queue<AccountGroup.Id> groupQueue = new LinkedList<AccountGroup.Id> (seedGroups); while (groupQueue.size() > 0) { AccountGroup.Id id = groupQueue.remove(); for (final AccountGroup.Id groupId : includedGroupCache.getByIncludedGroup(id)) { if (!includedGroups.contains(groupId)) { includedGroups.add(groupId); groupQueue.add(groupId); } } } return includedGroups; }

Target:
private Set<AccountGroup.Id> getIncludedGroups(Set<AccountGroup.Id> seedGroups) { Set<AccountGroup.Id> includedGroups = new HashSet<AccountGroup.Id> (seedGroups); Queue<AccountGroup.Id> groupQueue = new LinkedList<AccountGroup.Id> (seedGroups); while (groupQueue.size() > 0) { AccountGroup.Id id = groupQueue.remove(); for (final AccountGroup.Id groupId : includedGroupCache.getByIncludedGroup(id)) { if (includedGroups.add(groupId)) { groupQueue.add(groupId); } } } return Collections.unmodifiableSet(includedGroups); }
Source:
public void close() { executorService.shutdown(); }

Target:
public void close() { executorService.shutdownNow(); }
Source:
Response readResponse(HttpURLConnection connection) throws IOException { int status = connection.getResponseCode(); String reason = connection.getResponseMessage(); List<Header> headers = new ArrayList<Header>(); for (Map.Entry<String, List<String>> field : connection.getHeaderFields().entrySet()) { String name = field.getKey(); for (String value : field.getValue()) { headers.add(new Header(name, value)); } } String mimeType = connection.getContentType(); int length = connection.getContentLength(); InputStream stream; if (status == 200) { stream = connection.getInputStream(); } else { stream = connection.getErrorStream(); } stream = new BufferedInputStream(stream); TypedInput responseBody = new TypedInputStream(mimeType, length, stream); return new Response(status, reason, headers, responseBody); }

Target:
Response readResponse(HttpURLConnection connection) throws IOException { int status = connection.getResponseCode(); String reason = connection.getResponseMessage(); List<Header> headers = new ArrayList<Header>(); for (Map.Entry<String, List<String>> field : connection.getHeaderFields().entrySet()) { String name = field.getKey(); for (String value : field.getValue()) { headers.add(new Header(name, value)); } } String mimeType = connection.getContentType(); int length = connection.getContentLength(); InputStream stream; if (status == 200) { stream = connection.getInputStream(); } else { stream = connection.getErrorStream(); } TypedInput responseBody = new TypedInputStream(mimeType, length, stream); return new Response(status, reason, headers, responseBody); }
Source:
public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) { Optional<BulkDecodingFormat<RowData>> bulkDecodingFormat = discoverBulkDecodingFormat(); if (!partitionKeys.isEmpty() && getOrFetchPartitions().isEmpty()) { return InputFormatProvider.of(new CollectionInputFormat<>(new ArrayList<>(), null)); } else if (bulkDecodingFormat.isPresent()) { return SourceProvider.of(createBulkFormatSource(bulkDecodingFormat.get(), scanContext)); } return new DataStreamScanProvider() { @Override public DataStream<RowData> produceDataStream(StreamExecutionEnvironment execEnv) { TypeInformation<RowData> typeInfo = InternalTypeInfo.of( getProducedDataType().getLogicalType()); return execEnv.addSource( new InputFormatSourceFunction<>(getInputFormat(), typeInfo), String.format("Filesystem(%s)", tableIdentifier), typeInfo); } @Override public boolean isBounded() { return true; } }; }

Target:
public ScanRuntimeProvider getScanRuntimeProvider(ScanContext scanContext) { if (!partitionKeys.isEmpty() && getOrFetchPartitions().isEmpty()) { return InputFormatProvider.of(new CollectionInputFormat<>(new ArrayList<>(), null)); } else if (bulkReaderFormat != null) { return sourceProvider(bulkReaderFormat, scanContext); } else if (formatFactory != null) { return SourceFunctionProvider.of( new InputFormatSourceFunction<>( getInputFormat(), InternalTypeInfo.of(getProducedDataType().getLogicalType())), true); } else if (deserializationFormat != null) { throw new UnsupportedOperationException("The deserializationFormat is under developing."); } else { throw new TableException("Can not find format factory."); } }
Source:
public void appendConstraints(AllocationAttempt attempt, AllocationLog log, List<Constraint> constraints) { for (Instance instance : attempt.getInstances()) { List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(instance, objectManager); for (Volume v : volumes) { if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(v.getAccessMode())) { Long hostID = DataAccessor.fieldLong(v, VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID); if (hostID != null ) { Set<Long> hostIds = allocatorDao.findHostsWithVolumeInUse(v.getId()); boolean hardConstraint = false; if (hostIds.size() == 0) { hardConstraint = false; } else if (hostIds.size() == 1) { hardConstraint = true; for(Long id: hostIds) { hostID = id; } } else { throw new FailedToAllocate("SingleHostRW volume is used by mutiple hosts"); } constraints.add(new VolumeAccessModeSingleHostConstraint(hostID, v.getId(), hardConstraint)); } } else if (VolumeConstants.ACCESS_MODE_SINGLE_INSTANCE_RW.equals(v.getAccessMode())) { List<Long> currentlyUsedBy = allocatorDao.getInstancesWithVolumeMounted(v.getId(), instance.getId()); if (currentlyUsedBy.size() > 0) { constraints.add(new VolumeAccessModeSingleInstanceConstraint(v.getId(), v.getAccessMode(), currentlyUsedBy)); } } } } }

Target:
public void appendConstraints(AllocationAttempt attempt, AllocationLog log, List<Constraint> constraints) { for (Instance instance : attempt.getInstances()) { List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(instance, objectManager); for (Volume v : volumes) { if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(v.getAccessMode())) { Long hostID = null; Object hostIdObject = DataAccessor.fromDataFieldOf(v).withKey(VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID).get(); if ( hostIdObject != null) { hostID = Long.parseLong(hostIdObject.toString()); } Set<Long> hostIds = allocatorDao.findHostsWithVolumeInUse(v.getId()); boolean hardConstraint = false; if (hostIds.size() == 0) { hardConstraint = false; } else if (hostIds.size() == 1) { hardConstraint = true; for(Long id: hostIds) { hostID = id; } } else { throw new FailedToAllocate("SingleHostRW volume is used by mutiple hosts"); } if (hostID != null) { constraints.add(new VolumeAccessModeSingleHostConstraint(hostID, v.getId(), hardConstraint)); } } else if (VolumeConstants.ACCESS_MODE_SINGLE_INSTANCE_RW.equals(v.getAccessMode())) { List<Long> currentlyUsedBy = allocatorDao.getInstancesWithVolumeMounted(v.getId(), instance.getId()); if (currentlyUsedBy.size() > 0) { constraints.add(new VolumeAccessModeSingleInstanceConstraint(v.getId(), v.getAccessMode(), currentlyUsedBy)); } } } } }
Source:
public final Response intercept(Chain chain) throws IOException { Request request = chain.request(); Exception lastException = null; List<String> failoverUris = uris; if (randomize) { failoverUris = new ArrayList<>(uris); Collections.shuffle(failoverUris); } for (String uri : failoverUris) { request = redirectRequest(request, uri); try { return chain.proceed(request); } catch (SocketTimeoutException | UnknownHostException | HttpRetryException | MalformedURLException | SocketException | UnknownServiceException e) { lastException = e; logger.warn("Failed to send request to " + request.url(), e); } catch (IOException e) { throw e; } } throw new IllegalStateException( "Could not connect to any node. Please check that the URIs are valid and servers are up.", lastException); }

Target:
public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Exception lastException = null; String lastUri = null; for (String uri : uris) { if (lastUri != null) { logger.warn("Redirecting request from to {}", lastUri, uri); } request = redirectRequest(request, uri); try { return chain.proceed(request); } catch (SocketTimeoutException | UnknownHostException | HttpRetryException | MalformedURLException | SocketException | UnknownServiceException e) { lastException = e; lastUri = uri; logger.warn("Failed to send request to " + request.url(), e); } } throw new IllegalStateException("Could not connect to any of the following servers: " + uris + ". " + "Please check that the URIs are correct and servers are accessible.", lastException); }
Source:
private Long getRequestTimeout(SamzaResourceRequest request) { Optional<Long> controlActionRequestExpirytimeout = containerManager.getActionExpiryTimeout(request.getProcessorId()); Long changedRequestExpiryTimeout = controlActionRequestExpirytimeout.isPresent() ? controlActionRequestExpirytimeout.get() : new Long(requestExpiryTimeout); return changedRequestExpiryTimeout; }

Target:
private Duration getRequestTimeout(SamzaResourceRequest request) { Optional<Duration> controlActionRequestExpiryTimeout = containerManager.getActionExpiryTimeout(request); return controlActionRequestExpiryTimeout.orElse(Duration.ofMillis(configuredRequestExpiryTimeout)); }
Source:
public void contextDestroyed( ServletContextEvent servletContextEvent ) { Repository jcrRepository = PentahoSystem.get( Repository.class, "jcrRepository", null ); if ( jcrRepository == null ) { System.err.println( "Cannot obtain JCR repository. Exiting" ); return; } if ( !( jcrRepository instanceof JackrabbitRepository ) ) { System.err.println( String.format( "Expected RepositoryImpl, but got: [%s]. Exiting", jcrRepository.getClass().getName() ) ); return; } ( (JackrabbitRepository) jcrRepository ).shutdown(); }

Target:
public void contextDestroyed( ServletContextEvent servletContextEvent ) { Repository jcrRepository = PentahoSystem.get( Repository.class, "jcrRepository", null ); if ( jcrRepository == null ) { Logger.error( PentahoSystemReadyListener.class.getName(), "Cannot obtain JCR repository. Exiting" ); return; } if ( !( jcrRepository instanceof JackrabbitRepository ) ) { Logger.error( PentahoSystemReadyListener.class.getName(), String.format( "Expected RepositoryImpl, but got: [%s]. Exiting", jcrRepository.getClass().getName() ) ); return; } ( (JackrabbitRepository) jcrRepository ).shutdown(); }
Source:
public PageContainerForm deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException { final JsonNode jsonNode = jsonParser.readValueAsTree(); final List<ContainerEntry> entries = new ArrayList<>(); for (JsonNode jsonElement : jsonNode) { final String containerId = jsonElement.get(CONTAINER_ID_ATTRIBUTE_NAME).asText(); final String containerUUID = jsonElement.get(CONTAINER_UUID_ATTRIBUTE_NAME).asText(); final ContainerEntry containerEntry = new ContainerEntry(containerId, containerUUID); final JsonNode containerNode = jsonElement.get(CONTAINER_CONTENTLETSID_ATTRIBUTE_NAME); containerNode.forEach(contentId -> containerEntry.addContentId(contentId.textValue())); entries.add(containerEntry); } return new PageContainerForm(entries, jsonNode.toString()); }

Target:
public PageContainerForm deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException { final JsonNode jsonNode = jsonParser.readValueAsTree(); final List<ContainerEntry> entries = new ArrayList<>(); for (final JsonNode jsonElement : jsonNode) { final String containerId = jsonElement.get(CONTAINER_ID_ATTRIBUTE_NAME).asText(); final String containerUUID = jsonElement.get(CONTAINER_UUID_ATTRIBUTE_NAME).asText(); final ContainerEntry containerEntry = new ContainerEntry(containerId, containerUUID); final JsonNode containerNode = jsonElement.get(CONTAINER_CONTENTLETSID_ATTRIBUTE_NAME); containerNode.forEach((JsonNode contentId) -> containerEntry.addContentId(contentId.textValue())); entries.add(containerEntry); } return new PageContainerForm(entries, jsonNode.toString()); }
Source:
void addRequiredFieldsToCacheTableDefinition(TableDefinition cacheTableDefinition, boolean cacheExpiryEnabled) { cacheTableDefinition.attribute(CACHE_TABLE_TIMESTAMP_ADDED, Attribute.Type.LONG); }

Target:
void addRequiredFieldsToCacheTableDefinition(TableDefinition cacheTableDefinition, boolean cacheExpiryEnabled) { cacheTableDefinition.attribute(CACHE_TABLE_TIMESTAMP_ADDED, Attribute.Type.LONG); cachePolicyAttributePosition = cacheTableDefinition.getAttributeList().size() - 1; numColumns = cachePolicyAttributePosition + 1; }
Source:
public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) { super.initFromTensorFlow(nodeDef, initWith, attributesForNode, graph); if (nodeDef.containsAttr("frame_name")) { val attr = nodeDef.getAttrOrThrow("frame_name"); this.frame_name = attr.getS().toStringUtf8(); } }

Target:
public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) { super.initFromTensorFlow(nodeDef, initWith, attributesForNode, graph); }
Source:
public void metadataReceived(final String filename, final Metadata metadata) { if (metadata.keys().contains("ds3-last-modified")) { try { final long lastModifiedMs = Long.parseLong(metadata.get("ds3-last-modified").get(0)); final Path path = outputPath.resolve(filename); final FileTime lastModified = FileTime.from(lastModifiedMs, TimeUnit.MILLISECONDS); Files.setLastModifiedTime(path, lastModified); } catch (final Throwable t) { LOG.error("Failed to restore the last modified date for object: " + filename, t); } } else { LOG.info("Object ("+ filename + ") does not contain a last modified field"); } }

Target:
public void metadataReceived(final String filename, final Metadata metadata) { final Path path = outputPath.resolve(filename); Utils.restoreLastModified(filename, metadata, path); }
Source:
public static boolean shouldOpenSampleBoard() { return !TestController.isTestMode() || TestController.shouldTestStartupBoard(); }

Target:
public static boolean shouldOpenSampleBoard() { return !isTestMode() || shouldTestStartupBoard(); }
Source:
public void setEvaluation(EvaluatedQualityGate g) { requireNonNull(g); checkState(evaluation == null, "QualityGateHolder evaluation can be initialized only once"); this.evaluation = Optional.of(g); }

Target:
public void setEvaluation(EvaluatedQualityGate g) { requireNonNull(g); checkState(evaluation == null, "QualityGateHolder evaluation can be initialized only once"); this.evaluation = g; }
Source:
private void updateDiff() throws EDBException { List<String> keyList = loadKeyList(); for (String key : keyList) { if (key.equals("id") || key.equals("@prevTimestamp") || key.equals("@timestamp")) { continue; } Object first = startState.get(key); Object last = endState.get(key); if (last != null && first != null && first.equals(last)) { continue; } diff.put(key, new Entry(first, last)); differences++; } }

Target:
private void updateDiff() throws EDBException { List<String> keyList = loadKeyList(); for (String key : keyList) { if (key.equals("id") || key.equals("prevTimestamp") || key.equals("timestamp")) { continue; } Object first = startState.get(key); Object last = endState.get(key); if (last != null && first != null && first.equals(last)) { continue; } diff.put(key, new Entry(first, last)); differences++; } }
Source:
public HtsgetResponse getResponse() { final URI reqURI = this.toURI(); try { final HttpURLConnection conn = (HttpURLConnection) reqURI.toURL().openConnection(); conn.setRequestMethod("GET"); conn.connect(); final InputStream is = conn.getInputStream(); final int statusCode = conn.getResponseCode(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); } final String json = out.toString(); if (400 <= statusCode && statusCode < 500) { final HtsgetErrorResponse err = HtsgetErrorResponse.parse(json); throw new IllegalArgumentException( "Invalid request, received error code: " + statusCode + ", error type: " + err.getError() + ", message: " + err.getMessage()); } else if (statusCode == 200) { return HtsgetResponse.parse(json); } else { throw new IllegalArgumentException("Unrecognized status code: " + statusCode); } } catch (final IOException e) { throw new RuntimeIOException("IOException while attempting htsget download, request: " + reqURI, e); } }

Target:
public HtsgetResponse getResponse() { final URI reqURI = this.toURI(); try { final HttpURLConnection conn = (HttpURLConnection) reqURI.toURL().openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", HtsgetRequest.ACCEPT_TYPE); conn.connect(); final InputStream is = conn.getInputStream(); final int statusCode = conn.getResponseCode(); final String respContentType = conn.getContentType(); if (respContentType != null && !respContentType.isEmpty() && !respContentType.contains(HtsgetRequest.PROTOCOL_VERSION)) { log.warn("Supported htsget protocol version: " + HtsgetRequest.PROTOCOL_VERSION + "may not be compatible with received content type: " + respContentType); } final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); } final String json = out.toString(); if (400 <= statusCode && statusCode < 500) { final HtsgetErrorResponse err = HtsgetErrorResponse.parse(json); throw new IllegalArgumentException( "Invalid request, received error code: " + statusCode + ", error type: " + err.getError() + ", message: " + err.getMessage()); } else if (statusCode == 200) { return HtsgetResponse.parse(json); } else { throw new IllegalStateException("Unrecognized status code: " + statusCode); } } catch (final IOException e) { throw new RuntimeIOException("IOException while attempting htsget download, request: " + reqURI, e); } }
Source:
protected boolean canDoAction() { boolean returnValue = isVmExist(); VM vm = getVm(); if (returnValue && (vm != null && vm.getstatus() != VMStatus.Down)) { returnValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } else { returnValue = returnValue && (vm == null || isDiskCanBeAddedToVm(getParameters().getDiskInfo())); if (returnValue && DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) { returnValue = checkIfImageDiskCanBeAdded(vm); } if (returnValue && getParameters().getDiskInfo().isShareable() && getParameters().getDiskInfo().isBoot()) { returnValue = false; addCanDoActionMessage(VdcBllMessages.SHAREABLE_DISK_IS_NOT_SUPPORTED_FOR_DISK); } ImagesHandler.setDiskAlias(getParameters().getDiskInfo(), getVm()); setAllowSnapshotForDisk(); } return returnValue; }

Target:
protected boolean canDoAction() { boolean returnValue = isVmExist(); VM vm = getVm(); if (returnValue && (vm != null && vm.getstatus() != VMStatus.Down)) { returnValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } else { returnValue = returnValue && (vm == null || isDiskCanBeAddedToVm(getParameters().getDiskInfo())); if (returnValue && DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) { returnValue = checkIfImageDiskCanBeAdded(vm); } if (returnValue && getParameters().getDiskInfo().isShareable() && getParameters().getDiskInfo().isBoot()) { returnValue = false; addCanDoActionMessage(VdcBllMessages.SHAREABLE_DISK_IS_NOT_SUPPORTED_FOR_DISK); } ImagesHandler.setDiskAlias(getParameters().getDiskInfo(), getVm()); if (returnValue) { setAllowSnapshotForDisk(); } } return returnValue; }
Source:
public void testInject(final Parameter[] parameters, final Object[] args) { System.out.println("In: " + Arrays.asList(parameters)); System.out.println("args: " + Arrays.asList(args)); try { final Object[] injectedArgs = ReflectionRecipes.inject( parameters, InjectableParameter.Assistant.ALL_INJECTS, args, null, null, null ); System.out.println("injectedArgs: " + Arrays.asList(injectedArgs)); Assert.assertEquals(injectedArgs.length, parameters.length); } catch (final Throwable throwable) { throwable.printStackTrace(); } }

Target:
public void testInject(final Parameter[] parameters, final Object[] args) { System.out.println("In: " + Arrays.asList(parameters)); System.out.println("args: " + Arrays.asList(args)); final Object[] injectedArgs = ReflectionRecipes.inject( parameters, InjectableParameter.Assistant.ALL_INJECTS, args, null, null, null ); System.out.println("injectedArgs: " + Arrays.asList(injectedArgs)); Assert.assertEquals(injectedArgs.length, parameters.length); }