auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void dispose() { getSite().getPage().removeSelectionListener(this); getSite().setSelectionProvider(null); if (mTargetListener != null) { AdtPlugin.getDefault().removeTargetListener(mTargetListener); mTargetListener = null; } if (mReloadListener != null) { LayoutReloadMonitor.getMonitor().removeListener(mReloadListener); mReloadListener = null; } if (mCanvasViewer != null && mCanvasViewer.getCanvas() != null) { mCanvasViewer.getCanvas().dispose(); } super.dispose(); }

Target:
public void dispose() { getSite().getPage().removeSelectionListener(this); getSite().setSelectionProvider(null); if (mTargetListener != null) { AdtPlugin.getDefault().removeTargetListener(mTargetListener); mTargetListener = null; } if (mReloadListener != null) { LayoutReloadMonitor.getMonitor().removeListener(mReloadListener); mReloadListener = null; } if (mCanvasViewer != null) { mCanvasViewer.dispose(); mCanvasViewer = null; } super.dispose(); }
Source:
private void testXSDConfigXML(String xmlFileName) throws Exception { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaResource = XMLConfigBuilderTest.class.getClassLoader().getResource("hazelcast-config-" + Versions.CURRENT_CLUSTER_VERSION + ".xsd"); assertNotNull(schemaResource); InputStream xmlResource = XMLConfigBuilderTest.class.getClassLoader().getResourceAsStream(xmlFileName); Schema schema = factory.newSchema(schemaResource); Source source = new StreamSource(xmlResource); Validator validator = schema.newValidator(); try { validator.validate(source); } catch (SAXException ex) { fail(xmlFileName + " is not valid because: " + ex.toString()); } }

Target:
private static void testXSDConfigXML(String xmlFileName) throws Exception { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaResource = XMLConfigBuilderTest.class.getClassLoader().getResource("hazelcast-config-" + Versions.CURRENT_CLUSTER_VERSION + ".xsd"); InputStream xmlResource = XMLConfigBuilderTest.class.getClassLoader().getResourceAsStream(xmlFileName); Schema schema = factory.newSchema(schemaResource); Source source = new StreamSource(xmlResource); Validator validator = schema.newValidator(); try { validator.validate(source); } catch (SAXException ex) { fail(xmlFileName + " is not valid because: " + ex.toString()); } }
Source:
private void createVMFromTemplate() { VmTemplate template = getSelectedItem(); UnitVmModel model = new UnitVmModel(new NewVmFromTemplateModelBehavior(template)); model.setIsAdvancedModeLocalStorageKey(getEditTemplateAdvancedModelKey()); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().newVmTitle()); model.setTitle(ConstantsManager.getInstance().getConstants().newVmTitle()); model.setHelpTag(HelpTag.new_vm); model.setHashName("new_vm"); model.setIsNew(true); model.getVmType().setSelectedItem(template.getVmType()); model.setCustomPropertiesKeysList(AsyncDataProvider.getInstance().getCustomPropertiesList()); model.setIsAdvancedModeLocalStorageKey("wa_vm_dialog"); model.initialize(this.getSystemTreeSelectedItem()); VmBasedWidgetSwitchModeCommand switchModeCommand = new VmBasedWidgetSwitchModeCommand(); switchModeCommand.init(model); model.getCommands().add(switchModeCommand); model.getProvisioning().setEntity(true); UICommand onSaveVmCommand = UICommand.createDefaultOkUiCommand("OnSaveVm", this); model.getCommands().add(onSaveVmCommand); UICommand cancelCommand = UICommand.createCancelUiCommand("Cancel", this); model.getCommands().add(cancelCommand); }

Target:
private void createVMFromTemplate() { VmTemplate template = getSelectedItem(); List<UICommand> commands = new ArrayList<>(); commands.add(UICommand.createDefaultOkUiCommand("OnSaveVm", this)); commands.add(UICommand.createCancelUiCommand("Cancel", this)); setupNewVmModel(new UnitVmModel(new NewVmFromTemplateModelBehavior(template)), template.getVmType(), getSystemTreeSelectedItem(), commands); }
Source:
public String getTitle() { return getData(KEY_TITLE).toString(); }

Target:
public String getTitle() { return (getCreativeData(KEY_TITLE) != null) ? creativeData.get(KEY_TITLE).toString() : null; }
Source:
public void testLoadingKryoSerializersFromConfiguration() { StreamExecutionEnvironment envFromConfiguration = StreamExecutionEnvironment.getExecutionEnvironment(); Configuration configuration = new Configuration(); configuration.setString( "pipeline.default-kryo-serializers", "class:'org.apache.flink.streaming.api.environment.StreamExecutionEnvironmentComplexConfigurationTest$CustomPojo'" + ",serializer:'org.apache.flink.streaming.api.environment.StreamExecutionEnvironmentComplexConfigurationTest$CustomPojoSerializer'"); envFromConfiguration.configure( configuration, Thread.currentThread().getContextClassLoader()); LinkedHashMap<Object, Object> serializers = new LinkedHashMap<>(); serializers.put(CustomPojo.class, CustomPojoSerializer.class); assertThat( envFromConfiguration.getConfig().getDefaultKryoSerializerClasses(), equalTo(serializers)); }

Target:
public void testLoadingKryoSerializersFromConfiguration() { Configuration configuration = new Configuration(); configuration.setString( "pipeline.default-kryo-serializers", "class:'org.apache.flink.streaming.api.environment.StreamExecutionEnvironmentComplexConfigurationTest$CustomPojo'" + ",serializer:'org.apache.flink.streaming.api.environment.StreamExecutionEnvironmentComplexConfigurationTest$CustomPojoSerializer'"); StreamExecutionEnvironment envFromConfiguration = StreamExecutionEnvironment.getExecutionEnvironment( configuration); LinkedHashMap<Object, Object> serializers = new LinkedHashMap<>(); serializers.put(CustomPojo.class, CustomPojoSerializer.class); assertThat( envFromConfiguration.getConfig().getDefaultKryoSerializerClasses(), equalTo(serializers)); }
Source:
public void TSDLSimpleTest() throws CTFReaderException { createDummyTrace(simpleTSDL); CTFTrace trace = new CTFTrace(tempTraceDir); assertNotNull(trace); trace.dispose(); }

Target:
public void TSDLSimpleTest() throws CTFReaderException { createDummyTrace(simpleTSDL); trace = new CTFTrace(tempTraceDir); assertNotNull(trace); }
Source:
public Tenant createTenant(final TenantData data, final CallContext context) throws TenantApiException { final Tenant tenant = new DefaultTenant(data); try { tenantDao.create(new TenantModelDao(tenant), internalCallContextFactory.createInternalCallContextWithoutAccountRecordId(context)); } catch (final Exception e) { if (e.getCause() instanceof SQLDataException) { throw new TenantApiException(e, ErrorCode.EXTERNAL_KEY_LIMIT_EXCEEDED); } else throw new TenantApiException(e, ErrorCode.TENANT_CREATION_FAILED); } return tenant; }

Target:
public Tenant createTenant(final TenantData data, final CallContext context) throws TenantApiException { final Tenant tenant = new DefaultTenant(data); if (null != tenant.getExternalKey() && tenant.getExternalKey().length() > 255) { throw new TenantApiException(ErrorCode.EXTERNAL_KEY_LIMIT_EXCEEDED); } try { tenantDao.create(new TenantModelDao(tenant), internalCallContextFactory.createInternalCallContextWithoutAccountRecordId(context)); } catch (final TenantApiException e) { throw new TenantApiException(e, ErrorCode.TENANT_CREATION_FAILED); } return tenant; }
Source:
public void getTaskData(Set<String> taskIds, TaskRepository taskRepository, TaskDataCollector collector, IOperationMonitor monitor) throws BugzillaRestException { HashSet<String> taskIdsTemp = new HashSet<String>(taskIds); BugzillaRestConfiguration config; try { config = connector.getRepositoryConfiguration(taskRepository); } catch (CoreException e1) { throw new BugzillaRestException(e1); } while (taskIdsTemp.size() > 0) { Set<String> idsToRetrieve = new HashSet<String>(); Iterator<String> itr = taskIdsTemp.iterator(); int xid = 0; String urlIDList = ""; for (int x = 0; itr.hasNext() && x < MAX_RETRIEVED_PER_QUERY; x++) { String taskId = itr.next(); while (taskId.startsWith("0")) { taskId = taskId.substring(1); } urlIDList = ((xid++ > 0 ? "," : "id=") + taskId); idsToRetrieve.add(taskId); } try { List<TaskData> taskDataArray = new BugzillaRestGetTaskData(client, connector, urlIDList, taskRepository) .run(monitor); for (TaskData taskData : taskDataArray) { config.updateProductOptions(taskData.getRoot() .getMappedAttribute(BugzillaRestTaskSchema.getDefault().PRODUCT.getKey())); config.addValidOperations(taskData); collector.accept(taskData); } } catch (BugzillaRestException e) { e.printStackTrace(); } taskIdsTemp.removeAll(idsToRetrieve); } }

Target:
public void getTaskData(Set<String> taskIds, TaskRepository taskRepository, TaskDataCollector collector, IOperationMonitor monitor) throws BugzillaRestException { BugzillaRestConfiguration config; try { config = connector.getRepositoryConfiguration(taskRepository); } catch (CoreException e1) { throw new BugzillaRestException(e1); } Iterable<String> taskIdsTemp = Iterables.transform(taskIds, function); Iterable<List<String>> partitions = Iterables.partition(taskIdsTemp, MAX_RETRIEVED_PER_QUERY); for (List<String> list : partitions) { Joiner joiner = Joiner.on(",id=").skipNulls(); String urlIDList = "id=" + joiner.join(list); List<TaskData> taskDataArray = new BugzillaRestGetTaskData(client, connector, urlIDList, taskRepository) .run(monitor); for (TaskData taskData : taskDataArray) { config.updateProductOptions( taskData.getRoot().getMappedAttribute(BugzillaRestTaskSchema.getDefault().PRODUCT.getKey())); config.addValidOperations(taskData); collector.accept(taskData); } } }
Source:
protected void saveAdditionalChildInfo(XmlMemento child, TableColumn column) { TableColumnDescriptor desc = (TableColumnDescriptor) column .getData(TableColumnDescriptor.TABLE_COLUMN_DESCRIPTOR_KEY); XmlMemento descriptor = child.createChild("TableColumnDescriptors"); descriptor.putInteger("alignment", desc.getAlignment()); descriptor.putInteger("sortDirection", desc.getSortDirection()); descriptor.putInteger("widths", desc.getWidths()); descriptor.putBoolean("autoSize", desc.isAutoSize()); descriptor.putBoolean("defaultSortColumn", desc.isDefaultSortColumn()); }

Target:
protected void saveAdditionalChildInfo(XmlMemento child, TableColumn column) { TableColumnDescriptor desc = (TableColumnDescriptor) column .getData(TableColumnDescriptor.TABLE_COLUMN_DESCRIPTOR_KEY); XmlMemento descriptor = child.createChild(xmlChildName); descriptor.putInteger(xmlFieldAlignment, desc.getAlignment()); descriptor.putInteger(xmlFieldSortDirection, desc.getSortDirection()); descriptor.putInteger(xmlFieldWidth, desc.getWidth()); descriptor.putBoolean(xmlFieldAutoSize, desc.isAutoSize()); descriptor.putBoolean(xmlFieldDefaultSortColumn, desc.isDefaultSortColumn()); }
Source:
protected int doWork() { IOUtil.assertFilesAreReadable(INPUT); final MetricsFile<?, ?> metricsA = new MetricsFile(); final MetricsFile<?, ?> metricsB = new MetricsFile(); int retVal = 1; try { metricsA.read(new FileReader(INPUT.get(0))); metricsB.read(new FileReader(INPUT.get(1))); retVal = compareMetricsFiles(INPUT.get(0), INPUT.get(1)); final String status = retVal == 0 ? "EQUAL" : "NOT EQUAL"; log.info("Files " + INPUT.get(0) + " and " + INPUT.get(1) + " are " + status); } catch (final Exception e) { throw new PicardException(e.getMessage()); } return retVal; }

Target:
protected int doWork() { IOUtil.assertFilesAreReadable(INPUT); try { final int retVal = compareMetricsFiles(INPUT.get(0), INPUT.get(1)); final String status = retVal == 0 ? "equal" : "NOT equal"; log.info(metricClassName + " Metric files " + INPUT.get(0) + " and " + INPUT.get(1) + " are " + status); if (!differences.isEmpty()) { for (String difference : differences) { log.error(difference); } } if (OUTPUT != null) { final String header = "Comparison of " + metricClassName + " metrics between files " + INPUT.get(0).getAbsolutePath() + " and " + INPUT.get(1).getAbsolutePath() + "\n\nMetrics are " + status; writeTextToFile(OUTPUT, header, differences); } return retVal; } catch (final Exception e) { throw new PicardException(e.getMessage()); } }
Source:
public String getMetadataStoreRealm(String namespace, String shardingKey) { if (!_routingDataMap.containsKey(namespace)) { throw new IllegalArgumentException( "Failed to get all mapping under path: Namespace " + namespace + " is not found!"); } return _routingDataMap.get(namespace).getMetadataStoreRealm(shardingKey); }

Target:
public String getMetadataStoreRealm(String namespace, String shardingKey) { if (!_routingDataMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to get metadata store realm: Namespace " + namespace + " is not found!"); } return _routingDataMap.get(namespace).getMetadataStoreRealm(shardingKey); }
Source:
public List<Map<String, Object>> toMaps() { return contentlets.stream().map(this::copy).map(this::transform).collect(Collectors.toList()); }

Target:
public List<Map<String, Object>> toMaps() { return contentlets.stream().map(this::copy).map(this::transform).collect(CollectionsUtils.toImmutableList()); }
Source:
public void testFullPath() throws Exception { final String xpath = "/CLASS_DEF/OBJBLOCK/METHOD_DEF[1]/SLIST/VARIABLE_DEF[2]"; final DetailAST rootAst = getRootAst("InputXpathMapperAst.java"); final RootNode rootNode = new RootNode(rootAst); final DetailAST[] actual = convertToDetailAstArray(getXpathItems(xpath, rootNode)); final DetailAST realVariableDefNode = getSiblingByType(rootAst, TokenTypes.CLASS_DEF) .findFirstToken(TokenTypes.OBJBLOCK) .findFirstToken(TokenTypes.METHOD_DEF) .findFirstToken(TokenTypes.SLIST) .findFirstToken(TokenTypes.VARIABLE_DEF) .getNextSibling() .getNextSibling(); final DetailAST[] expected = {realVariableDefNode}; assertArrayEquals(expected, actual); }

Target:
public void testFullPath() throws Exception { final String xpath = "/CLASS_DEF/OBJBLOCK/METHOD_DEF[1]/SLIST/VARIABLE_DEF[2]"; final RootNode rootNode = getRootNode("InputXpathMapperAst.java"); final DetailAST[] actual = convertToArray(getXpathItems(xpath, rootNode)); final DetailAST expectedVariableDefNode = getSiblingByType(rootNode.getUnderlyingNode(), TokenTypes.CLASS_DEF) .findFirstToken(TokenTypes.OBJBLOCK) .findFirstToken(TokenTypes.METHOD_DEF) .findFirstToken(TokenTypes.SLIST) .findFirstToken(TokenTypes.VARIABLE_DEF) .getNextSibling() .getNextSibling(); final DetailAST[] expected = {expectedVariableDefNode}; assertArrayEquals("Result nodes differ from expected", expected, actual); }
Source:
protected void doStart() throws Exception { if (raftHandle == null && jgroupsConfig != null && !jgroupsConfig.isEmpty()) { raftHandle = new RaftHandle( new JChannel(jgroupsConfig), new NopStateMachine()).raftId(raftId); } else if(raftHandle == null) { raftHandle = new RaftHandle(new JChannel(JGroupsRaftEndpoint.DEFAULT_JGROUPSRAFT_CONFIG), new NopStateMachine()).raftId(raftId); } fireLeadershipChangedEvent(Optional.empty()); raftHandle.addRoleListener(new ClusterRoleChangeListener(this)); raftHandle.channel().connect(jgroupsClusterName); }

Target:
protected void doStart() throws Exception { if (raftHandle == null && jgroupsConfig != null && !jgroupsConfig.isEmpty()) { raftHandle = new RaftHandle(new JChannel(jgroupsConfig), new NopStateMachine()).raftId(raftId); } else if (raftHandle == null) { raftHandle = new RaftHandle(new JChannel(JGroupsRaftConstants.DEFAULT_JGROUPSRAFT_CONFIG), new NopStateMachine()).raftId(raftId); } fireLeadershipChangedEvent(Optional.empty()); raftHandle.addRoleListener(new ClusterRoleChangeListener(this)); raftHandle.channel().connect(jgroupsClusterName); }
Source:
private void display(final GroupMembersList groupMembers) { final PrintWriter stdout = toPrintWriter(out); try { printWarnings(stdout, groupMembers); final Set<Account> accounts = groupMembers.getAllAccounts(); final Set<GroupMembersList> includedGroups = groupMembers.getAllIncludedGroups(); if (!accounts.isEmpty()) { stdout.println("Accounts:"); for (final Account account : accounts) { stdout.println(accountFormatter.formatWithFullnameEmailAndId(account)); } if (!includedGroups.isEmpty()) { stdout.println(); } } if (!includedGroups.isEmpty()) { stdout.println("Included Groups:"); for (final GroupMembersList includedGroupMembers : includedGroups) { if (includedGroupMembers.isGroupVisible()) { final AccountGroup group = includedGroupMembers.getGroup(); stdout.println(group.getName() + " (" + group.getId() + ")"); } } } } finally { stdout.flush(); } }

Target:
private void display(final GroupMembersList groupMembers) { final PrintWriter stdout = toPrintWriter(out); try { printWarnings(stdout, groupMembers); final Set<Account> accounts = groupMembers.getAllAccounts(); final Set<GroupMembersList> includedGroups = groupMembers.getAllIncludedGroups(); if (!accounts.isEmpty()) { stdout.print("Accounts:\n"); for (final Account account : accounts) { stdout.print(accountFormatter.formatWithFullnameEmailAndId(account) + "\n"); } if (!includedGroups.isEmpty()) { stdout.print("\n"); } } if (!includedGroups.isEmpty()) { stdout.print("Included Groups:\n"); for (final GroupMembersList includedGroupMembers : includedGroups) { if (includedGroupMembers.isGroupVisible()) { final AccountGroup group = includedGroupMembers.getGroup(); stdout.print(group.getName() + " (" + group.getId() + ")\n"); } } } } finally { stdout.flush(); } }
Source:
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (AbstractParam.class.isAssignableFrom(rawType)) { final String parameterName = JerseyParameterNameProvider.getParameterNameFromAnnotations(annotations).orElse("Parameter"); final Constructor<T> constructor; try { constructor = rawType.getConstructor(String.class, String.class); } catch (NoSuchMethodException ignored) { return null; } return new ParamConverter<T>() { @Override @SuppressWarnings("unchecked") public T fromString(String s) { if (rawType != NonEmptyStringParam.class && Strings.isNullOrEmpty(s)) { return null; } try { return constructor.newInstance(s, parameterName); } catch (InstantiationException | IllegalAccessException e) { throw new InternalServerErrorException(String.format("Unable to convert parameter %s: %s", parameterName, e.getMessage())); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } return null; } } @Override public String toString(T t) { return t == null ? null : t.toString(); } }; } return null; }

Target:
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (AbstractParam.class.isAssignableFrom(rawType)) { final String parameterName = JerseyParameterNameProvider.getParameterNameFromAnnotations(annotations).orElse("Parameter"); final Constructor<T> constructor; try { constructor = rawType.getConstructor(String.class, String.class); } catch (NoSuchMethodException ignored) { return null; } return new ParamConverter<T>() { @Override @SuppressWarnings("unchecked") public T fromString(String value) { if (rawType != NonEmptyStringParam.class && Strings.isNullOrEmpty(value)) { return null; } try { return _fromString(value); } catch (InvocationTargetException ex) { final Throwable cause = ex.getCause(); if (cause instanceof WebApplicationException) { throw (WebApplicationException) cause; } else { throw new ExtractorException(cause); } } catch (final Exception ex) { throw new ProcessingException(ex); } } protected T _fromString(String value) throws Exception { return constructor.newInstance(value, parameterName); } @Override public String toString(T value) throws IllegalArgumentException { if (value == null) { throw new IllegalArgumentException(LocalizationMessages.METHOD_PARAMETER_CANNOT_BE_NULL("value")); } return value.toString(); } }; } return null; }
Source:
boolean setIdFor(final SObjectNode node, final String referenceId, final String id) { final org.apache.camel.component.salesforce.api.dto.Attributes attributes = node.getObject().getAttributes(); final String attributesReferenceId = attributes.getReferenceId(); if (Objects.equals(attributesReferenceId, referenceId)) { final Object object = node.getObject(); if (object != null) { return updateBaseObjectId(id, (AbstractSObjectBase) object); } else { return updateGeneralObjectId(id, object); } } return StreamSupport.stream(node.getChildNodes().spliterator(), false) .anyMatch(n -> setIdFor(n, referenceId, id)); }

Target:
boolean setIdFor(final SObjectNode node, final String referenceId, final String id) { final Attributes attributes = node.getObject().getAttributes(); final String attributesReferenceId = attributes.getReferenceId(); if (Objects.equals(attributesReferenceId, referenceId)) { final Object object = node.getObject(); if (object != null) { return updateBaseObjectId(id, (AbstractSObjectBase) object); } else { return updateGeneralObjectId(id, object); } } return StreamSupport.stream(node.getChildNodes().spliterator(), false) .anyMatch(n -> setIdFor(n, referenceId, id)); }
Source:
public void afterPropertiesSet() throws Exception { Assert.hasText(realmName, "realmName must be specified"); }

Target:
public void afterPropertiesSet() throws Exception { }
Source:
public void addConfiguration(MultipleJGitEnvironmentProperties environmentProperties) throws GeneralSecurityException { if (environmentProperties.getUri().startsWith("http")) { httpClientBuildersByUriAuthority.put(environmentProperties.getUri(), HttpClientSupport.builder(environmentProperties)); } for (JGitEnvironmentProperties repo : environmentProperties.getRepos().values()) { if (repo.getUri().startsWith("http")) { httpClientBuildersByUriAuthority.put(repo.getUri(), HttpClientSupport.builder(repo)); } } }

Target:
public void addConfiguration(MultipleJGitEnvironmentProperties environmentProperties) throws GeneralSecurityException { addHttpClient(environmentProperties); for (JGitEnvironmentProperties repo : environmentProperties.getRepos().values()) { addHttpClient(repo); } }
Source:
public static PinotDataType getSpecificMapDataTypeFromMap(Map<Object, Object> map) { Iterator<Object> iterator = map.values().iterator(); Object obj = iterator.next(); if (obj instanceof Integer) { return PinotDataType.INTEGER_MAP; } else if (obj instanceof Long) { return PinotDataType.LONG_MAP; } else if (obj instanceof Float) { return PinotDataType.FLOAT_MAP; } else if (obj instanceof Double) { return PinotDataType.DOUBLE_MAP; } else if (obj instanceof String) { return PinotDataType.STRING_MAP; } else { throw new IllegalStateException(String.format("'%s' isn't supported in the hash map.", obj.getClass())); } }

Target:
public static PinotDataType getSpecificMapDataTypeFromMap(Map<Object, Object> map) { Iterator<Object> iterator = map.values().iterator(); Object obj = iterator.next(); if (obj instanceof Integer) { return PinotDataType.INTEGER_VALUE_MAP; } else if (obj instanceof Long) { return PinotDataType.LONG_VALUE_MAP; } else if (obj instanceof Float) { return PinotDataType.FLOAT_VALUE_MAP; } else if (obj instanceof Double) { return PinotDataType.DOUBLE_VALUE_MAP; } else if (obj instanceof String) { return PinotDataType.STRING_VALUE_MAP; } else { throw new IllegalStateException(String.format("'%s' isn't supported in the hash map.", obj.getClass())); } }
Source:
public void restartWorkspace() throws Exception { if (testWorkspaceServiceClient.getStatus(workspace.getId()).equals(WorkspaceStatus.RUNNING)) { editor.closeAllTabs(); testWorkspaceServiceClient.stop(workspace.getName(), workspace.getOwner().getName()); ide.open(workspace); ide.waitOpenedWorkspaceIsReadyToUse(); restoreLanguageServer(); projectExplorer.quickRevealToItemWithJavaScript(PROJECT_NAME + "/Program.cs"); } }

Target:
public void restartWorkspace() throws Exception { editor.closeAllTabs(); testWorkspaceServiceClient.stop(workspace.getName(), workspace.getOwner().getName()); ide.open(workspace); ide.waitOpenedWorkspaceIsReadyToUse(); restoreDependenciesForLanguageServerByCommand(); projectExplorer.quickRevealToItemWithJavaScript(PROJECT_NAME + "/Program.cs"); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle(R.string.box_sharesdk_sample_name); BoxConfig.IS_LOG_ENABLED = true; BoxConfig.CLIENT_ID = "your_client_id"; BoxConfig.CLIENT_SECRET = "your_client_secret"; BoxConfig.CLIENT_SECRET = "your_client_secret"; if (savedInstanceState != null) { mSampleFolder = (BoxFolder) savedInstanceState.getSerializable(EXTRA_SAMPLE_FOLDER); } initialize(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle(R.string.box_sharesdk_sample_name); BoxConfig.IS_LOG_ENABLED = true; BoxConfig.CLIENT_ID = "your_client_id"; BoxConfig.CLIENT_SECRET = "your_client_secret"; if (savedInstanceState != null) { mSampleFolder = (BoxFolder) savedInstanceState.getSerializable(EXTRA_SAMPLE_FOLDER); } initialize(); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (this == obj) { return true; } if (!(obj instanceof JobSubjectEntityId)) { return false; } JobSubjectEntityId other = (JobSubjectEntityId) obj; return Objects.equals(entityId, other.entityId) && Objects.equals(jobId, other.jobId); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof JobSubjectEntityId)) { return false; } JobSubjectEntityId other = (JobSubjectEntityId) obj; return Objects.equals(entityId, other.entityId) && Objects.equals(jobId, other.jobId); }
Source:
public String toString() { if (mOptions.size() == 0) { return mName; } else { StringBuilder options = new StringBuilder(); for (TestOption option : mOptions) { options.append(option.toString() + ", "); } options.delete(options.length() - 2, options.length()); return String.format("%s: Options: %s", mName, options); } }

Target:
public String toString() { if (mOptions.size() == 0) { return mName; } else { return String.format( "%s: Options: %s", mName, Joiner.on(",") .join( mOptions.stream() .map(TestOption::toString) .collect(Collectors.toList()))); } }
Source:
HelixClusterManagerMetrics(MetricRegistry registry, final HelixClusterManager.HelixClusterManagerCallback clusterMapCallback) { this.clusterMapCallback = clusterMapCallback; this.registry = registry; liveInstanceChangeTriggerCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "liveInstanceChangeTriggerCount")); externalViewChangeTriggerCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "externalViewChangeTriggerCount")); instanceConfigChangeTriggerCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "instanceConfigChangeTriggerCount")); getPartitionIdFromStreamMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getPartitionIdFromStreamMismatchCount")); getWritablePartitionIdsMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getWritablePartitionIdsMismatchCount")); getAllPartitionsMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getAllPartitionsMismatchCount")); hasDatacenterMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "hasDatacenterMismatchCount")); getDataNodeIdMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getDataNodeIdMismatchCount")); getReplicaIdsMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getReplicaIdsMismatchCount")); getDataNodeIdsMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getDataNodeIdsMismatchCount")); }

Target:
HelixClusterManagerMetrics(MetricRegistry registry, final HelixClusterManager.HelixClusterManagerCallback clusterMapCallback) { this.clusterMapCallback = clusterMapCallback; this.registry = registry; liveInstanceChangeTriggerCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "liveInstanceChangeTriggerCount")); externalViewChangeTriggerCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "externalViewChangeTriggerCount")); instanceConfigChangeTriggerCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "instanceConfigChangeTriggerCount")); getPartitionIdFromStreamMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getPartitionIdFromStreamMismatchCount")); getWritablePartitionIdsMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getWritablePartitionIdsMismatchCount")); getAllPartitionIdsMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getAllPartitionIdsMismatchCount")); hasDatacenterMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "hasDatacenterMismatchCount")); getDataNodeIdMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getDataNodeIdMismatchCount")); getReplicaIdsMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getReplicaIdsMismatchCount")); getDataNodeIdsMismatchCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "getDataNodeIdsMismatchCount")); }
Source:
public AnsibleReturnValue runCommand(AnsibleCommandConfig command, Logger originLogger, Consumer<String> eventUrlConsumer) { int timeout = EngineLocalConfig.getInstance().getInteger("ANSIBLE_PLAYBOOK_EXEC_DEFAULT_TIMEOUT"); return runCommand( command, timeout, (String taskName, String eventUrl) -> { AuditLogable logable = createAuditLogable(command, taskName); Injector.get(AuditLogDirector.class).log(logable, AuditLogType.ANSIBLE_RUNNER_EVENT_NOTIFICATION); try { eventUrlConsumer.accept(eventUrl); } catch (Exception ex) { originLogger.error("Error: {}", ex.getMessage()); originLogger.debug("Exception: ", ex); } }); }

Target:
public AnsibleReturnValue runCommand(AnsibleCommandConfig command, Logger originLogger, Consumer<String> eventUrlConsumer) { int timeout = EngineLocalConfig.getInstance().getInteger("ANSIBLE_PLAYBOOK_EXEC_DEFAULT_TIMEOUT"); return runCommand( command, timeout, (String taskName, String eventUrl) -> { AuditLogable logable = createAuditLogable(command, taskName); auditLogDirector.log(logable, AuditLogType.ANSIBLE_RUNNER_EVENT_NOTIFICATION); try { eventUrlConsumer.accept(eventUrl); } catch (Exception ex) { originLogger.error("Error: {}", ex.getMessage()); originLogger.debug("Exception: ", ex); } }); }
Source:
beginReleasePhoneNumbers(List<PhoneNumber> phoneNumbers, Duration pollInterval) { Objects.requireNonNull(phoneNumbers, "'phoneNumbers' cannot be null."); Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); return new PollerFlux<PhoneNumberRelease, PhoneNumberRelease>(pollInterval, releaseNumbersActivationOperation(phoneNumbers), releaseNumbersPollOperation(), (activationResponse, pollingContext) -> monoError(logger, new RuntimeException("Cancellation is not supported")), releaseNumbersFetchResultOperation()); }

Target:
beginReleasePhoneNumbers(List<PhoneNumber> phoneNumbers, Duration pollInterval) { Objects.requireNonNull(phoneNumbers, "'phoneNumbers' cannot be null."); if (pollInterval == null) { pollInterval = defaultPollInterval; } return new PollerFlux<PhoneNumberRelease, PhoneNumberRelease>(pollInterval, releaseNumbersActivationOperation(phoneNumbers), releaseNumbersPollOperation(), (activationResponse, pollingContext) -> monoError(logger, new RuntimeException("Cancellation is not supported")), releaseNumbersFetchResultOperation()); }
Source:
public String docs() { return "void {world, region, flagName, flagValue, [group]} Add/change/remove flag for selected region. FlagName should be any" + " supported flag from this list <LINK_1>. For flagValue use types which" + " are supported by WorldGuard. Add group argument if you want to add WorldGuard group flag (read more about group" + " flag type here: <LINK_0>). Set flagValue as null (and don't set" + " group) if you want to delete flag from region."; }

Target:
public String docs() { return "void {world, region, flagName, flagValue, [group]} Add/change/remove flag for selected region. FlagName should be any" + " supported flag from [<LINK_1> this list]. For the flagValue, use types which" + " are supported by WorldGuard. Add group argument if you want to add WorldGuard group flag (read more about group" + " flag types [<LINK_0> here]). Set flagValue as null (and don't set" + " group) to delete the flag from the region."; }
Source:
public static ArrayList<String> getAllVariants(Entity en, Campaign campaign) { final String METHOD_NAME = "getAllVariants(Entity, Campaign)"; CampaignOptions options = campaign.getCampaignOptions(); ArrayList<String> variants = new ArrayList<>(); for(MechSummary summary : MechSummaryCache.getInstance().getAllMechs()) { if (!en.getChassis().equalsIgnoreCase(summary.getChassis()) || en.getModel().equalsIgnoreCase(summary.getModel()) || !summary.getUnitType().equals(UnitType.determineUnitType(en))) { continue; } if (!summary.isCanon() && options.allowCanonRefitOnly()) { continue; } if (en instanceof BattleArmor) { if (((BattleArmor)en).getTroopers() != (int) summary.getTWweight()) { continue; } } else { if (summary.getTons() != en.getWeight()) { continue; } } ITechnology techProg = UnitTechProgression.getProgression(summary, campaign.getTechFaction(), true); if (null == techProg) { MekHQ.getLogger().log(Utilities.class, METHOD_NAME, LogLevel.WARNING, "Could not determine tech progression for " + summary.getName() + ", including among available refits."); } else if (!campaign.isLegal(techProg)) { continue; } variants.add(summary.getModel()); } return variants; }

Target:
public static ArrayList<String> getAllVariants(Entity en, Campaign campaign) { final String METHOD_NAME = "getAllVariants(Entity, Campaign)"; CampaignOptions options = campaign.getCampaignOptions(); ArrayList<String> variants = new ArrayList<>(); for(MechSummary summary : MechSummaryCache.getInstance().getAllMechs()) { if (!en.getChassis().equalsIgnoreCase(summary.getChassis()) || en.getModel().equalsIgnoreCase(summary.getModel()) || !summary.getUnitType().equals(UnitType.getTypeName(en.getUnitType()))) { continue; } if (en instanceof BattleArmor) { if (((BattleArmor) en).getTroopers() != (int) summary.getTWweight()) { continue; } } else { if (summary.getTons() != en.getWeight()) { continue; } } if (!summary.isCanon() && options.allowCanonRefitOnly()) { continue; } ITechnology techProg = UnitTechProgression.getProgression(summary, campaign.getTechFaction(), true); if (null == techProg) { MekHQ.getLogger().log(Utilities.class, METHOD_NAME, LogLevel.WARNING, "Could not determine tech progression for " + summary.getName() + ", including among available refits."); } else if (!campaign.isLegal(techProg)) { continue; } variants.add(summary.getModel()); } return variants; }
Source:
public void testJobSuspensionWhenDispatcherIsTerminated() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); dispatcherGateway.submitJob(jobGraph, TIMEOUT).get(); CommonTestUtils.waitUntilJobManagerIsInitialized(() -> dispatcherGateway.requestJobStatus(jobGraph.getJobID(), TIMEOUT).get()); final CompletableFuture<JobResult> jobResultFuture = dispatcherGateway.requestJobResult(jobGraph.getJobID(), TIMEOUT); assertThat(jobResultFuture.isDone(), is(false)); dispatcher.closeAsync(); try { jobResultFuture.get(); fail("Expected the job result to throw an exception."); } catch (ExecutionException ee) { assertThat(ExceptionUtils.findThrowable(ee, JobNotFinishedException.class).isPresent(), is(true)); } }

Target:
public void testJobSuspensionWhenDispatcherIsTerminated() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); dispatcherGateway.submitJob(jobGraph, TIMEOUT).get(); final CompletableFuture<JobResult> jobResultFuture = dispatcherGateway.requestJobResult(jobGraph.getJobID(), TIMEOUT); assertThat(jobResultFuture.isDone(), is(false)); dispatcher.closeAsync(); try { jobResultFuture.get(); fail("Expected the job result to throw an exception."); } catch (ExecutionException ee) { assertThat(ExceptionUtils.findThrowable(ee, JobNotFinishedException.class).isPresent(), is(true)); } }
Source:
public void onMetricsServiceReady(@Observes @ServiceReady ServiceReadyEvent event) { publishPeriod = getPublishPeriod(); Observable<List<Metric<?>>> events = event.getInsertedData() .filter(m -> m.getType() != MetricType.STRING) .filter(m -> publish.isPublished(m.getMetricId())) .buffer(publishPeriod, TimeUnit.MILLISECONDS, 100) .filter(list -> !list.isEmpty()) .onBackpressureBuffer() .observeOn(Schedulers.io()); subscription = events.subscribe(list -> list.forEach(this::onInsertedData)); }

Target:
public void onMetricsServiceReady(@Observes @ServiceReady ServiceReadyEvent event) { if (!Boolean.parseBoolean(disableMetricsForwarding)) { publishPeriod = getPublishPeriod(); Observable<List<Metric<?>>> events; if (Boolean.parseBoolean(disablePublishFiltering)) { events = event.getInsertedData() .buffer(publishPeriod, TimeUnit.MILLISECONDS, 100) .filter(list -> !list.isEmpty()); } else { events = event.getInsertedData() .filter(m -> m.getType() != MetricType.STRING) .filter(m -> publish.isPublished(m.getMetricId())) .buffer(publishPeriod, TimeUnit.MILLISECONDS, 100) .filter(list -> !list.isEmpty()); } events = events.onBackpressureBuffer() .observeOn(Schedulers.io()); subscription = events.subscribe(list -> list.forEach(this::onInsertedData)); } }
Source:
public static void registerMigrationListener(MigrationListener listener) { if (!sIsMigrationInProgress) { listener.onCompletion(); } else { sMigrationListener = listener; } }

Target:
public static void registerMigrationListener(MigrationListener listener) { sMigrationListener = listener; }
Source:
@Override public Float convert(JsonParser parser, Supplier<String> contentString) { String body = contentString.get(); String version = null; try { version = OBJECT_MAPPER.readTree(body).at("/version/number").textValue(); } catch (RuntimeException | IOException possiblyParseException) { } if (version == null) { throw new IllegalArgumentException(".version.number not found in response: " + body); } return Float.valueOf(version.substring(0, 3)); }

Target:
@Override public Float convert(JsonParser parser, Supplier<String> contentString) { String version = null; try { if (enterPath(parser, "version", "number") != null) version = parser.getText(); } catch (RuntimeException | IOException possiblyParseException) { } if (version == null) { throw new IllegalArgumentException( ".version.number not found in response: " + contentString.get()); } return Float.valueOf(version.substring(0, 3)); }
Source:
public void given_multibranchWithSourcesAndTwoBranches_when_indexing_then_deadBranchIsDeleted() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "feature"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); prj.setCriteria(null); prj.getSourcesList().add(new BranchSource(new MockSCMSource(null, c, "foo", true, false, false))); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); FreeStyleProject master = prj.getItem("master"); FreeStyleProject feature = prj.getItem("feature"); r.waitUntilNoActivity(); assertThat("The master branch was built", master.getLastBuild(), notNullValue()); assertThat("The master branch was built", master.getLastBuild().getNumber(), is(1)); assertThat("The feature branch was built", feature.getLastBuild(), notNullValue()); assertThat("The feature branch was built", feature.getLastBuild().getNumber(), is(1)); c.deleteBranch("foo", "feature"); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); assertThat("Indexing applies dead branch cleanup", prj.getItems(), containsInAnyOrder(master)); assertThat("Indexing applies dead branch cleanup", prj.getItems(), not(containsInAnyOrder(feature))); } }

Target:
public void given_multibranchWithSourcesAndTwoBranches_when_indexing_then_deadBranchIsDeleted() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "feature"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); prj.setCriteria(null); prj.getSourcesList().add(new BranchSource(new MockSCMSource(null, c, "foo", true, false, false))); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); FreeStyleProject master = prj.getItem("master"); FreeStyleProject feature = prj.getItem("feature"); r.waitUntilNoActivity(); assertThat("The master branch was built", master.getLastBuild(), notNullValue()); assertThat("The master branch was built", master.getLastBuild().getNumber(), is(1)); assertThat("The feature branch was built", feature.getLastBuild(), notNullValue()); assertThat("The feature branch was built", feature.getLastBuild().getNumber(), is(1)); c.deleteBranch("foo", "feature"); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); assertThat("Indexing applies dead branch cleanup", prj.getItems(), allOf( containsInAnyOrder(master), not(containsInAnyOrder(feature)))); } }
Source:
public CommCareTransactionParserFactory(MockUserDataSandbox sandbox) { this.sandbox = sandbox; fixtureParser = new TransactionParserFactory() { FixtureXmlParser created = null; public TransactionParser getParser(KXmlParser parser) { if (created == null) { created = new FixtureXmlParser(parser) { private IStorageUtilityIndexed<FormInstance> fixtureStorage; @Override public IStorageUtilityIndexed<FormInstance> storage() { if (fixtureStorage == null) { fixtureStorage = CommCareTransactionParserFactory.this.sandbox.getUserFixtureStorage(); } return fixtureStorage; } }; } return created; } }; this.initUserParser(); this.initCaseParser(); this.initStockParser(); }

Target:
public CommCareTransactionParserFactory(MockUserDataSandbox sandbox) { this.sandbox = sandbox; this.initFixtureParser(); this.initUserParser(); this.initCaseParser(); this.initStockParser(); }
Source:
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) { String contentType = this.jettyRequest.getHeaders().getField(HttpHeader.CONTENT_TYPE).getValue(); ReactiveRequest.Content content = ReactiveRequest.Content.fromPublisher(Flux .from(body) .flatMap(publisher -> publisher) .map(buffer -> new ContentChunk(buffer.asByteBuffer())), contentType); this.reactiveRequest = ReactiveRequest.newBuilder(this.jettyRequest).content(content).build(); return doCommit(this::completes); }

Target:
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) { String contentType = this.jettyRequest.getHeaders().getField(HttpHeader.CONTENT_TYPE).getValue(); Flux<ContentChunk> chunks = Flux.from(body).flatMap(Function.identity()).map(this::toContentChunk); ReactiveRequest.Content content = ReactiveRequest.Content.fromPublisher(chunks, contentType); this.reactiveRequest = ReactiveRequest.newBuilder(this.jettyRequest).content(content).build(); return doCommit(this::completes); }
Source:
private static void runNoteOnStart(ZeppelinConfiguration conf) throws IOException, InterruptedException { String noteIdToRun = conf.getNotebookRunId(); if (!Strings.isEmpty(noteIdToRun)) { NotebookService notebookService = (NotebookService) ServiceLocatorUtilities.getService( sharedServiceLocator, NotebookService.class.getName()); ServiceContext serviceContext; String base64EncodedJsonSerializedServiceContext = conf.getNotebookRunServiceContext(); if (Strings.isEmpty(base64EncodedJsonSerializedServiceContext)) { LOG.info("No service context provided. use ANONYMOUS"); serviceContext = new ServiceContext(AuthenticationInfo.ANONYMOUS, new HashSet<String>() {}); } else { serviceContext = new Gson().fromJson( new String(Base64.getDecoder().decode(base64EncodedJsonSerializedServiceContext)), ServiceContext.class); } boolean success = notebookService.runNote(noteIdToRun, serviceContext, new ServiceCallback<Paragraph>() { @Override public void onStart(String message, ServiceContext context) throws IOException { } @Override public void onSuccess(Paragraph result, ServiceContext context) throws IOException { } @Override public void onFailure(Exception ex, ServiceContext context) throws IOException { } }); if (conf.getNotebookRunAutoShutdown()) { Thread t = shutdown(conf); t.start(); t.join(); System.exit(success ? 0 : 1); } } }

Target:
private static void runNoteOnStart(ZeppelinConfiguration conf) throws IOException, InterruptedException { String noteIdToRun = conf.getNotebookRunId(); if (!Strings.isEmpty(noteIdToRun)) { LOG.info("Running note on start", noteIdToRun); NotebookService notebookService = (NotebookService) ServiceLocatorUtilities.getService( sharedServiceLocator, NotebookService.class.getName()); ServiceContext serviceContext; String base64EncodedJsonSerializedServiceContext = conf.getNotebookRunServiceContext(); if (Strings.isEmpty(base64EncodedJsonSerializedServiceContext)) { LOG.info("No service context provided. use ANONYMOUS"); serviceContext = new ServiceContext(AuthenticationInfo.ANONYMOUS, new HashSet<String>() {}); } else { serviceContext = new Gson().fromJson( new String(Base64.getDecoder().decode(base64EncodedJsonSerializedServiceContext)), ServiceContext.class); } boolean success = notebookService.runAllParagraphs(noteIdToRun, null, serviceContext, new ServiceCallback<Paragraph>() { @Override public void onStart(String message, ServiceContext context) throws IOException { } @Override public void onSuccess(Paragraph result, ServiceContext context) throws IOException { } @Override public void onFailure(Exception ex, ServiceContext context) throws IOException { } }); if (conf.getNotebookRunAutoShutdown()) { Thread t = shutdown(conf); t.start(); t.join(); System.exit(success ? 0 : 1); } } }