auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected StorageProvider getStorageProvider() { if (duracloudConfigBean.getSwiftEndpoint() != null) { Map<String, String> map = new HashMap<String, String>(); map.put(OPTS.SWIFT_S3_ENDPOINT.name(), duracloudConfigBean.getSwiftEndpoint()); map.put(OPTS.SWIFT_S3_SIGNER_TYPE.name(), duracloudConfigBean.getSwiftSignerType()); return new SwiftStorageProvider( duracloudConfigBean.getSwiftAccessKey(), duracloudConfigBean.getSwiftSecretKey(), map ); } else { AWSCredentials creds = new DefaultAWSCredentialsProviderChain().getCredentials(); AmazonS3 s3client = AmazonS3ClientBuilder.standard().build(); return new S3StorageProvider(s3client, creds.getAWSAccessKeyId(), null); } }

Target:
protected StorageProvider getStorageProvider() { if (duracloudConfigBean.getSwiftEndpoint() != null) { Map<String, String> map = new HashMap<>(); map.put(OPTS.SWIFT_S3_ENDPOINT.name(), duracloudConfigBean.getSwiftEndpoint()); map.put(OPTS.SWIFT_S3_SIGNER_TYPE.name(), duracloudConfigBean.getSwiftSignerType()); return new SwiftStorageProvider( duracloudConfigBean.getSwiftAccessKey(), duracloudConfigBean.getSwiftSecretKey(), map ); } else { AWSCredentials creds = new DefaultAWSCredentialsProviderChain().getCredentials(); AmazonS3 s3client = AmazonS3ClientBuilder.standard().build(); return new S3StorageProvider(s3client, creds.getAWSAccessKeyId(), null); } }
Source:
public void getLogReturnsAnEmptyListWhenCalledWith0() throws Exception { Run r = new Run(new StubJob(), 0) {}; File f = r.getLogFile(); f.getParentFile().mkdirs(); PrintWriter w = new PrintWriter(f, "utf-8"); w.println("dummy"); w.close(); List<String> logLines = r.getLog(0); assertTrue(logLines.isEmpty()); }

Target:
public void getLogReturnsAnEmptyListWhenCalledWith0() throws Exception { Job j = Mockito.mock(Job.class); File tempBuildDir = tmp.newFolder(); Mockito.when(j.getBuildDir()).thenReturn(tempBuildDir); Run r = new Run(j, 0) {}; File f = r.getLogFile(); f.getParentFile().mkdirs(); PrintWriter w = new PrintWriter(f, "utf-8"); w.println("dummy"); w.close(); List<String> logLines = r.getLog(0); assertTrue(logLines.isEmpty()); }
Source:
public void testJsonOutput() { DumpProcessingAction action = new JsonSerializationAction(); action.open(); action.close(); assertEquals(action.getReport(), "Finished serialization of 0 EntityDocuments in file {PROJECT}-{DATE}.json"); }

Target:
public void testJsonOutput() { String[] args = { "-a", "json", "-o", "output/wikidata.json" }; ClientConfiguration configuration = new ClientConfiguration(args); DumpProcessingAction action = configuration.actions.get(0); action.open(); action.close(); assertTrue(action .getReport() .matches( "Finished serialization of \\d+ EntityDocuments in file output/wikidata.json")); }
Source:
public ArrayList<CapraOfficeObject> getSelection() { return this.selection; }

Target:
public List<CapraOfficeObject> getSelection() { return this.selection; }
Source:
static MusicConfig load(String moduleName, JSONObject config) { List<String> menuMusicSet = new ArrayList<>(); List<String> gameMusicSet = new ArrayList<>(); JSONArray menuMusicArray = config.getJSONArray("menuMusic"); JSONArray gameMusicArray = config.getJSONArray("gameMusic"); for (Object o : menuMusicArray) { if (o instanceof String) { menuMusicSet.add(moduleName + ":" + o); } } for (Object o : gameMusicArray) { if (o instanceof String) { gameMusicSet.add(moduleName + ":" + o); } } Map<String, List<String>> musicMap = new HashMap<>(); musicMap.put(OggMusicManager.MENU_MUSIC_SET, menuMusicSet); musicMap.put(OggMusicManager.GAME_MUSIC_SET, gameMusicSet); return new MusicConfig(moduleName, musicMap); }

Target:
static MusicConfig load(String moduleName, JSONObject config) { List<String> menuMusicSet = new ArrayList<>(); List<String> gameMusicSet = new ArrayList<>(); JSONArray menuMusicArray = config.getJSONArray("menuMusic"); JSONArray gameMusicArray = config.getJSONArray("gameMusic"); for (Object object : menuMusicArray) { if (object instanceof String) { menuMusicSet.add(moduleName + ":" + object); } } for (Object object : gameMusicArray) { if (object instanceof String) { gameMusicSet.add(moduleName + ":" + object); } } Map<String, List<String>> musicMap = new HashMap<>(); musicMap.put(OggMusicManager.MENU_MUSIC_SET, menuMusicSet); musicMap.put(OggMusicManager.GAME_MUSIC_SET, gameMusicSet); return new MusicConfig(moduleName, musicMap); }
Source:
private void shutdown() throws IOException { try { Field executor = this.parent.getDeclaredField("_executor"); executor.setAccessible(true); ExecutorService _executor = (ExecutorService) executor.get(this); _executor.shutdown(); } catch (NoSuchFieldException | IllegalAccessException e) { logger.severe("Error trying to abort JmDNS: " + e.getMessage()); throw new IOException(e); } }

Target:
private void shutdown() throws IOException { try { Field executor = this.parent.getDeclaredField("_executor"); executor.setAccessible(true); ExecutorService _executor = (ExecutorService) executor.get(this); _executor.shutdown(); } catch (NoSuchFieldException | IllegalAccessException e) { logger.log(Level.SEVERE, "Error trying to abort JmDNS", e); throw new IOException(e); } }
Source:
private boolean isAppPresent() { try { Thread.sleep(3000); } catch (InterruptedException e) { PageObjectLogging.log("noEmailPerms", e.getMessage(), false); } boolean isPresent = false; for (WebElement element : pageElementList) { if (element.getText().toString().matches("^Wikia.*\n?.*")) { isPresent = true; } } return isPresent; }

Target:
private boolean isAppPresent() { try { Thread.sleep(3000); } catch (InterruptedException e) { PageObjectLogging.log("isAppPresent", e.getMessage(), false); } boolean isPresent = false; for (WebElement element : pageElementList) { if (element.getText().toString().matches("^Wikia.*\n?.*")) { isPresent = true; } } return isPresent; }
Source:
public Map<P2PDataStorage.ByteArray, PersistableNetworkPayload> getMap(String filter) { HashMap<P2PDataStorage.ByteArray, PersistableNetworkPayload> result = new HashMap<>(); result.putAll(store.getMap()); if (filter.startsWith("since ")) { filter = filter.replace("since ", ""); if (!filter.equals(Version.VERSION)) { String finalFilter = filter; history.entrySet().stream().filter(entry -> Integer.valueOf(entry.getKey().replace(".", "")) > Integer.valueOf(finalFilter.replace(".", ""))).forEach(entry -> result.putAll(entry.getValue().getMap())); } } return result; }

Target:
public Map<P2PDataStorage.ByteArray, PersistableNetworkPayload> getMap(String filter) { HashMap<P2PDataStorage.ByteArray, PersistableNetworkPayload> result = new HashMap<>(); result.putAll(store.getMap()); if (filter.startsWith("since ")) { String finalFilter = filter.replace("since ", ""); if (!finalFilter.equals(Version.VERSION)) { history.entrySet().stream() .filter(entry -> parseSpecialKey(entry.getKey()) > parseSpecialKey(finalFilter)) .forEach(entry -> result.putAll(entry.getValue().getMap())); } } return result; }
Source:
public ParquetRecordWriter( ParquetFileWriter w, WriteSupport<T> writeSupport, MessageType schema, Map<String, String> extraMetaData, int blockSize, int pageSize, BytesCompressor compressor, int dictionaryPageSize, boolean enableDictionary, boolean validating, WriterVersion writerVersion) { this(w, writeSupport, schema, extraMetaData, blockSize, pageSize, compressor, dictionaryPageSize, enableDictionary, validating, writerVersion, null); }

Target:
public ParquetRecordWriter( ParquetFileWriter w, WriteSupport<T> writeSupport, MessageType schema, Map<String, String> extraMetaData, int blockSize, int pageSize, BytesCompressor compressor, int dictionaryPageSize, boolean enableDictionary, boolean validating, WriterVersion writerVersion) { internalWriter = new InternalParquetRecordWriter<T>(w, writeSupport, schema, extraMetaData, blockSize, pageSize, compressor, dictionaryPageSize, enableDictionary, validating, writerVersion); }
Source:
protected void prepareOnAffectedNodes(TxInvocationContext<?> ctx, PrepareCommand command, Collection<Address> recipients, boolean ignored) { try { Map<Address, Response> resps = rpcManager.invokeRemotely(recipients, command, rpcManager.getDefaultRpcOptions(true, DeliverOrder.NONE)); checkTxCommandResponses(resps, command); CacheTransaction ct = ctx.getCacheTransaction(); for (Response r : resps.values()) readVersionsFromResponse(r, ct); } finally { transactionRemotelyPrepared(ctx); } }

Target:
protected void prepareOnAffectedNodes(TxInvocationContext<?> ctx, PrepareCommand command, Collection<Address> recipients, boolean ignored) { try { RpcOptions rpcOptions = rpcManager.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS, DeliverOrder.NONE).build(); Map<Address, Response> resps = rpcManager.invokeRemotely(recipients, command, rpcOptions); checkTxCommandResponses(resps, command); CacheTransaction ct = ctx.getCacheTransaction(); for (Response r : resps.values()) readVersionsFromResponse(r, ct); } finally { transactionRemotelyPrepared(ctx); } }
Source:
public void buildAtomicElement(Document doc, Element rootElement) { if (getAdds() != null) { Element atomic = doc.createElement(Constants.ATOMIC); rootElement.appendChild(atomic); if (getCommandId() != -1) { Element commandId = doc.createElement(Constants.COMMAND_ID); commandId.appendChild(doc.createTextNode(String.valueOf(getCommandId()))); atomic.appendChild(commandId); } for (int x = 0; x < getAdds().size(); x++) { if (getAdds().get(x) != null) { getAdds().get(x).buildAddElement(doc, atomic); } } for (int x = 0; x < getReplaces().size(); x++) { if (getReplaces().get(x) != null) { getReplaces().get(x).buildReplaceElement(doc, atomic); } } } }

Target:
public void buildAtomicElement(Document doc, Element rootElement) { Element atomic = doc.createElement(Constants.ATOMIC); if (getAdds() != null) { rootElement.appendChild(atomic); if (getCommandId() != -1) { Element commandId = doc.createElement(Constants.COMMAND_ID); commandId.appendChild(doc.createTextNode(String.valueOf(getCommandId()))); atomic.appendChild(commandId); } for (Iterator<Add> addIterator = getAdds().iterator(); addIterator.hasNext(); ) { Add add = addIterator.next(); if (add != null) { add.buildAddElement(doc, atomic); } } } if (getReplaces() != null) { for (Iterator<Replace> replaceIterator = getReplaces().iterator(); replaceIterator.hasNext(); ) { Replace add = replaceIterator.next(); if (add != null) { add.buildReplaceElement(doc, atomic); } } } }
Source:
public void configureSeries(Map<@NonNull ISeries, Object[]> mapper) { XYChartConsumer chartConsumer = getChartConsumer(); NumericalConsumerAggregator aggregator = (NumericalConsumerAggregator) checkNotNull(chartConsumer.getYAggregator()); fYRanges = clampExternalRange(checkNotNull(aggregator.getChartRanges())); for (XYSeriesConsumer seriesConsumer : chartConsumer.getSeries()) { BarStringConsumer xconsumer = (BarStringConsumer) seriesConsumer.getXConsumer(); NumericalConsumer yConsumer = (NumericalConsumer) seriesConsumer.getYConsumer(); Object[] object = seriesConsumer.getObject().toArray(); fCategories = xconsumer.getList().stream().toArray(s -> new String[s]); double[] yData = new double[yConsumer.getData().size()]; for (int i = 0; i < yData.length; i++) { Number number = checkNotNull(yConsumer.getData().get(i)); yData[i] = fYRanges.getInternalValue(number).doubleValue(); } ISeries series = checkNotNull(getSeriesMap().get(seriesConsumer.getSeries())); series.setYSeries(yData); mapper.put(series, checkNotNull(object)); } }

Target:
public void configureSeries(Map<@NonNull ISeries, Object[]> mapper) { XYChartConsumer chartConsumer = getChartConsumer(); NumericalConsumerAggregator aggregator = (NumericalConsumerAggregator) checkNotNull(chartConsumer.getYAggregator()); fYRanges = clampExternalRange(checkNotNull(aggregator.getChartRanges())); for (XYSeriesConsumer seriesConsumer : chartConsumer.getSeries()) { BarStringConsumer xconsumer = (BarStringConsumer) seriesConsumer.getXConsumer(); NumericalConsumer yConsumer = (NumericalConsumer) seriesConsumer.getYConsumer(); Object[] object = seriesConsumer.getObject().toArray(); fCategories = xconsumer.getList().stream().toArray(size -> new String[size]); double[] yData = new double[yConsumer.getData().size()]; for (int i = 0; i < yData.length; i++) { Number number = checkNotNull(yConsumer.getData().get(i)); yData[i] = fYRanges.getInternalValue(number).doubleValue(); } ISeries series = checkNotNull(getSeriesMap().get(seriesConsumer.getSeries())); series.setYSeries(yData); mapper.put(series, checkNotNull(object)); } }
Source:
public void beforeEach(final ExtensionContext context) { Set<Object> testInstances = new LinkedHashSet<>(); testInstances.add(context.getRequiredTestInstance()); this.collectParentTestInstances(testInstances); Strictness actualStrictness = this.retrieveAnnotationFromTestClasses(context) .map(MockitoSettings::strictness) .orElse(strictness); MockitoSession session = Mockito.mockitoSession() .initMocks(testInstances.toArray()) .strictness(actualStrictness) .logger(new MockitoSessionLoggerAdapter(Plugins.getMockitoLogger())) .startMocking(); context.getStore(MOCKITO).put(SESSION, session); }

Target:
public void beforeEach(final ExtensionContext context) { List<Object> testInstances = context.getRequiredTestInstances().getAllInstances(); Strictness actualStrictness = this.retrieveAnnotationFromTestClasses(context) .map(MockitoSettings::strictness) .orElse(strictness); MockitoSession session = Mockito.mockitoSession() .initMocks(testInstances.toArray()) .strictness(actualStrictness) .logger(new MockitoSessionLoggerAdapter(Plugins.getMockitoLogger())) .startMocking(); context.getStore(MOCKITO).put(SESSION, session); }
Source:
public void testCharacterWrapperWithParamOverloading() throws IOException { String translation = translateSourceFile( "class Test { " + "void f(char i) void f(int i) void f(long l) void f(float f) void f(double d) " + "void test1(Character toChar1) { f(toChar1); } " + "void test2(Character toChar2) { f((char) toChar2); } " + "void test3(Character toInt) { f((int) toInt); } " + "void test4(Character toLong) { f((long) toLong); } " + "void test5(Character toFlt) { f((float) toFlt); } " + "void test6(Character toDbl) { f((double) toDbl); } }", "Test", "Test.m"); assertTranslation(translation, "[self fWithChar:[((JavaLangCharacter *) nil_chk(toChar1)) charValue]]"); assertTranslation(translation, "[self fWithChar:[((JavaLangCharacter *) nil_chk(toChar2)) charValue]];"); assertTranslation(translation, "[self fWithInt:(jint) [((JavaLangCharacter *) nil_chk(toInt)) charValue]];"); assertTranslation(translation, "[self fWithLong:(jlong) [((JavaLangCharacter *) nil_chk(toLong)) charValue]];"); assertTranslation(translation, "[self fWithFloat:(jfloat) [((JavaLangCharacter *) nil_chk(toFlt)) charValue]];"); assertTranslation(translation, "[self fWithDouble:(jdouble) [((JavaLangCharacter *) nil_chk(toDbl)) charValue]];"); }

Target:
public void testCharacterWrapperWithParamOverloading() throws IOException { String translation = translateSourceFile( "class Test { " + "void f(char i) void f(int i) void f(long l) " + "void f(float f) void f(double d) " + "void test1(Character toChar1) { f(toChar1); } " + "void test2(Character toChar2) { f((char) toChar2); } " + "void test3(Character toInt) { f((int) toInt); } " + "void test4(Character toLong) { f((long) toLong); } " + "void test5(Character toFlt) { f((float) toFlt); } " + "void test6(Character toDbl) { f((double) toDbl); } }", "Test", "Test.m"); assertTranslation( translation, "[self fWithChar:[((JavaLangCharacter *) nil_chk(toChar1)) charValue]]"); assertTranslation( translation, "[self fWithChar:[((JavaLangCharacter *) nil_chk(toChar2)) charValue]];"); assertTranslation( translation, "[self fWithInt:(jint) [((JavaLangCharacter *) nil_chk(toInt)) charValue]];"); assertTranslation( translation, "[self fWithLong:(jlong) [((JavaLangCharacter *) nil_chk(toLong)) charValue]];"); assertTranslation( translation, "[self fWithFloat:(jfloat) [((JavaLangCharacter *) nil_chk(toFlt)) charValue]];"); assertTranslation( translation, "[self fWithDouble:(jdouble) [((JavaLangCharacter *) nil_chk(toDbl)) charValue]];"); }
Source:
public synchronized String toString() { List<String> stanzas = Lists.newArrayListWithCapacity(3); if (isNotBlank(appName) && appVersion != null) { stanzas.add(String.format("%s/%s", appName, appVersion)); } else if (isNotBlank(appName)) { stanzas.add(appName); } else if (appVersion != null) { stanzas.add(Integer.toString(appVersion)); } if (isNotBlank(device) && isNotBlank(osName)) { stanzas.add(String.format("(%s; %s; %s)", device, osName, osVersion)); } else if (isNotBlank(device)) { stanzas.add(String.format("(%s)", device)); } else if (isNotBlank(osName)){ stanzas.add(String.format("(%s; %s)", osName, osVersion)); } if (isNotBlank(sdkVersion)) { stanzas.add(String.format("BridgeJavaSDK/%s", sdkVersion)); } else { stanzas.add("BridgeJavaSDK"); } return Joiner.on(" ").join(stanzas); }

Target:
public synchronized String toString() { List<String> stanzas = Lists.newArrayListWithCapacity(3); if (isNotBlank(appName) && appVersion != null) { stanzas.add(String.format("%s/%s", appName, appVersion)); } else if (isNotBlank(appName)) { stanzas.add(appName); } else if (appVersion != null) { stanzas.add(Integer.toString(appVersion)); } if (isNotBlank(device) && isNotBlank(osName)) { stanzas.add(String.format("(%s; %s %s)", device, osName, osVersion)); } else if (isNotBlank(device)) { stanzas.add(String.format("(%s)", device)); } else if (isNotBlank(osName)){ stanzas.add(String.format("(%s; %s)", osName, osVersion)); } if (isNotBlank(sdkVersion)) { stanzas.add(String.format("BridgeJavaSDK/%s", sdkVersion)); } else { stanzas.add("BridgeJavaSDK"); } return Joiner.on(" ").join(stanzas); }
Source:
public void widgetSelected(@Nullable SelectionEvent e) { int selectedCell = getColumnIndex(); ISegment selectedSegment = ((ISegment) NonNullUtils.checkNotNull(e).item.getData()); if (selectedSegment == null){ return; } ITmfTimestamp start = new TmfTimestamp(selectedSegment.getStart(), ITmfTimestamp.NANOSECOND_SCALE); ITmfTimestamp end = new TmfTimestamp(selectedSegment.getEnd(), ITmfTimestamp.NANOSECOND_SCALE); TmfSelectionRangeUpdatedSignal signal; switch (selectedCell) { case 0: signal = new TmfSelectionRangeUpdatedSignal(this, start, start); break; case 1: signal = new TmfSelectionRangeUpdatedSignal(this, end, end); break; case 2: signal = new TmfSelectionRangeUpdatedSignal(this, start, end); break; default: return; } TmfSignalManager.dispatchSignal(signal); }

Target:
public void widgetSelected(@Nullable SelectionEvent e) { int selectedCell = getColumnIndex(); ISegment selectedSegment = ((ISegment) NonNullUtils.checkNotNull(e).item.getData()); if (selectedSegment == null) { return; } ITmfTimestamp start = new TmfNanoTimestamp(selectedSegment.getStart()); ITmfTimestamp end = new TmfNanoTimestamp(selectedSegment.getEnd()); TmfSelectionRangeUpdatedSignal signal; switch (selectedCell) { case 0: signal = new TmfSelectionRangeUpdatedSignal(this, start); break; case 1: signal = new TmfSelectionRangeUpdatedSignal(this, end, end); break; case 2: signal = new TmfSelectionRangeUpdatedSignal(this, start, end); break; default: return; } TmfSignalManager.dispatchSignal(signal); }
Source:
private Collection<PendingTransaction> getTransactionWithAnyLockedKey(int transactionTopologyId, Collection<Object> keys, GlobalTransaction globalTransaction) { Function<CacheTransaction, PendingTransaction> filter = transaction -> { if (transaction.getTopologyId() < transactionTopologyId && !transaction.getGlobalTransaction().equals(globalTransaction)) { Object key = transaction.findAnyLockedOrBackupLocked(keys.stream()); return key == null ? null : new PendingTransaction(transaction, key); } return null; }; return filterAndCollectTransactions(filter); }

Target:
private Collection<PendingTransaction> getTransactionWithAnyLockedKey(int transactionTopologyId, Collection<Object> keys, GlobalTransaction globalTransaction) { final Collection<PendingTransaction> pendingTransactions = new ArrayList<>(); forEachTransaction(transaction -> { if (transaction.getTopologyId() < transactionTopologyId && !transaction.getGlobalTransaction().equals(globalTransaction)) { Object key = transaction.findAnyLockedOrBackupLocked(keys); if (key != null) { pendingTransactions.add(new PendingTransaction(transaction, key)); } } }); return pendingTransactions.isEmpty() ? Collections.emptyList() : pendingTransactions; }
Source:
private List<String> getLoginsFromPerun(String loginAttrName) throws InternalErrorException { PerunSession sess = this.getSession(); List<String> allLogins = new ArrayList<>(); try { AttributeDefinition attrDefLoginInMu = perunBl.getAttributesManagerBl().getAttributeDefinition(sess, loginAttrName); perunBl.getAttributesManagerBl().getAllValues(sess, attrDefLoginInMu).stream().forEach( value -> allLogins.add((String) value)); } catch (AttributeNotExistsException | WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } return allLogins; }

Target:
private List<String> getLoginsFromPerun(String loginAttrName) throws InternalErrorException { PerunSession sess = this.getSession(); List<String> allLogins = new ArrayList<>(); try { AttributeDefinition attrDefLoginInMu = perunBl.getAttributesManagerBl().getAttributeDefinition(sess, loginAttrName); perunBl.getAttributesManagerBl().getAllValues(sess, attrDefLoginInMu).forEach( value -> allLogins.add((String) value)); } catch (AttributeNotExistsException | WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } return allLogins; }
Source:
protected void removeActionSet(IActionSetDescriptor toRemove) { String id = toRemove.getId(); IContextService service = page.getWorkbenchWindow().getService(IContextService.class); try { service.deferUpdates(true); for (IActionSetDescriptor desc : alwaysOnActionSets) { if (desc.getId().equals(id)) { removeAlwaysOn(desc); break; } } for (IActionSetDescriptor desc : alwaysOffActionSets) { if (desc.getId().equals(id)) { removeAlwaysOff(desc); break; } } addAlwaysOff(toRemove); String tag = ModeledPageLayout.ACTION_SET_TAG + id; layout.getTags().remove(tag); } finally { service.deferUpdates(false); } }

Target:
protected void removeActionSet(IActionSetDescriptor toRemove) { String id = toRemove.getId(); IContextService service = page.getWorkbenchWindow().getService(IContextService.class); try { service.deferUpdates(true); for (IActionSetDescriptor desc : alwaysOnActionSets) { if (desc.getId().equals(id)) { removeAlwaysOn(desc); break; } } for (IActionSetDescriptor desc : alwaysOffActionSets) { if (desc.getId().equals(id)) { removeAlwaysOff(desc); break; } } addAlwaysOff(toRemove); String tag = ModeledPageLayout.ACTION_SET_TAG + id; if (layout.getTags().contains(tag)) { layout.getTags().remove(tag); } } finally { service.deferUpdates(false); } }
Source:
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets) { reset(); if(cursor > text.length()) cursor = text.length(); for (char c : text.toCharArray()) { if(cursor == index && (prev != SPACE_CHAR || haveEscape)) { cursorWord = textList.size(); wordCursor = builder.length(); } if (c == SPACE_CHAR) { handleSpace(c); } else if (c == BACK_SLASH) { if (haveEscape || ternaryQuote || haveDoubleQuote || haveSingleQuote) { builder.append(c); haveEscape = false; } else haveEscape = true; } else if (c == SINGLE_QUOTE) { handleSingleQuote(c); } else if (c == DOUBLE_QUOTE) { handleDoubleQuote(c); } else if (parseCurlyAndSquareBrackets && (c == CURLY_START || c == PARENTHESIS_START)) { handleCurlyStart(c); } else if (parseCurlyAndSquareBrackets && (c == CURLY_END || c == PARENTHESIS_END) && haveCurlyBracket) { handleCurlyEnd(c); } else if (haveEscape) { builder.append(c); haveEscape = false; } else builder.append(c); prev = c; index++; } return endOfLineProcessing(text, cursor, 0, text.length()); }

Target:
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets) { reset(); if(cursor > text.length()) cursor = text.length(); for (char c : text.toCharArray()) { if(cursor == index && (prev != SPACE_CHAR || haveEscape)) { cursorWord = textList.size(); wordCursor = builder.length(); } if (c == SPACE_CHAR) { handleSpace(c); } else if (c == BACK_SLASH) { if (haveEscape || ternaryQuote || haveDoubleQuote || haveSingleQuote) { builder.append(c); haveEscape = false; } else haveEscape = true; } else if (c == SINGLE_QUOTE) { handleSingleQuote(c); } else if (c == DOUBLE_QUOTE) { handleDoubleQuote(c); } else if (parseCurlyAndSquareBrackets && (c == CURLY_START || c == PARENTHESIS_START)) { handleCurlyStart(c); } else if (parseCurlyAndSquareBrackets && (c == CURLY_END || c == PARENTHESIS_END) && haveCurlyBracket) { handleCurlyEnd(c); } else if (haveEscape) { builder.append(BACK_SLASH); builder.append(c); haveEscape = false; } else builder.append(c); prev = c; index++; } return endOfLineProcessing(text, cursor, 0, text.length()); }
Source:
protected void executeCommand() { getNetwork().setId(Guid.newGuid()); NetworkUtils.setNetworkVdsmName(getNetwork()); TransactionSupport.executeInNewTransaction(() -> { networkDao.save(getNetwork()); if (getNetwork().isVmNetwork() && getParameters().isVnicProfileRequired()) { vnicProfileDao.save(networkHelper.createVnicProfile(getNetwork())); } networkHelper.addPermissionsOnNetwork(getUserId(), getNetwork().getId()); return null; }); List<NetworkCluster> networkAttachments = getParameters().getNetworkClusterList(); boolean clusterAttachmentsSucceeded = true; if (networkAttachments != null) { clusterAttachmentsSucceeded = attachToClusters(networkAttachments).getSucceeded(); } getReturnValue().setActionReturnValue(clusterAttachmentsSucceeded ? getNetwork().getId() : null); setSucceeded(clusterAttachmentsSucceeded); }

Target:
protected void executeCommand() { getNetwork().setId(Guid.newGuid()); NetworkUtils.setNetworkVdsmName(getNetwork()); TransactionSupport.executeInNewTransaction(() -> { networkDao.save(getNetwork()); if (getNetwork().isVmNetwork() && getParameters().isVnicProfileRequired()) { vnicProfileDao.save(networkHelper.createVnicProfile(getNetwork())); } networkHelper.addPermissionsOnNetwork(getUserId(), getNetwork().getId()); return null; }); List<NetworkCluster> networkAttachments = getParameters().getNetworkClusterList(); if (networkAttachments != null) { ActionReturnValue attachToClustersResult = attachToClusters(networkAttachments); if (!attachToClustersResult.getSucceeded()) { propagateFailure(attachToClustersResult); return; } } getReturnValue().setActionReturnValue(getNetwork().getId()); setSucceeded(true); }
Source:
public void testGetOrganizations() throws IOException { final MkUser user = new MkUser( new MkStorage.InFile(), "orgTestIterate" ); final Organizations orgs = user.organizations(); Assert.assertNotNull(orgs); }

Target:
public void testGetOrganizations() throws IOException { final MkUser user = new MkUser( new MkStorage.InFile(), "orgTestIterate" ); final Organizations orgs = user.organizations(); MatcherAssert.assertThat( orgs, Matchers.notNullValue() ); }
Source:
private IEvaluationResult creatErrorResult(Exception ex) { final BasicDiagnostic diag = new BasicDiagnostic(Diagnostic.ERROR, SiriusPlugin.ID, 0, "Error while evaluating expression", new Object[] { ex }); return new IEvaluationResult() { @Override public Object getValue() { return null; } @Override public Diagnostic getDiagnostic() { return diag; } }; }

Target:
private IEvaluationResult creatErrorResult(Exception ex) { final BasicDiagnostic diag = new BasicDiagnostic(Diagnostic.ERROR, SiriusPlugin.ID, 0, Messages.SessionInterpreter_evaluationError, new Object[] { ex }); return new IEvaluationResult() { @Override public Object getValue() { return null; } @Override public Diagnostic getDiagnostic() { return diag; } }; }
Source:
public static SacnNode getBroadcastNode(int universeId) { return new SacnNode(new String( "239.255." + String.format("%d", universeId / 256) + "." + String.format("%d", universeId % 256))); }

Target:
public static SacnNode getBroadcastNode(int universeId) { return new SacnNode(String.format("239.255.%d.%d", universeId / 256, universeId % 256)); }
Source:
public boolean validateUserVisibleChangeToken(String userVisibleChangeToken) { if (userVisibleChangeToken == null) { return true; } if (session.isChangeTokenEnabled()) { Long sysChangeToken = (Long) getPropertyValue(Model.MAIN_SYS_CHANGE_TOKEN_PROP); Long changeToken = (Long) getPropertyValue(Model.MAIN_CHANGE_TOKEN_PROP); return validateUserVisibleChangeToken(sysChangeToken, changeToken, userVisibleChangeToken); } else { Calendar modified; try { modified = (Calendar) getPropertyValue(DC_MODIFIED); } catch (PropertyNotFoundException e) { modified = null; } if (modified == null) { return true; } String currentToken = String.valueOf(modified.getTimeInMillis()); return userVisibleChangeToken.equals(currentToken); } }

Target:
public boolean validateUserVisibleChangeToken(String userVisibleChangeToken) { if (userVisibleChangeToken == null) { return true; } if (session.isChangeTokenEnabled()) { Long sysChangeToken = (Long) getPropertyValue(Model.MAIN_SYS_CHANGE_TOKEN_PROP); Long changeToken = (Long) getPropertyValue(Model.MAIN_CHANGE_TOKEN_PROP); return validateUserVisibleChangeToken(sysChangeToken, changeToken, userVisibleChangeToken); } else { Calendar modified; try { modified = (Calendar) getPropertyValue(DC_MODIFIED); } catch (PropertyNotFoundException e) { modified = null; } return validateLegacyChangeToken(modified, userVisibleChangeToken); } }
Source:
public void checkTransitionPropertySpec(final Transition transition) { for (ReactionProperty property : transition.getProperties()) { if (property instanceof EntryPointSpec) { if (transition.getTarget() instanceof org.yakindu.sct.model.sgraph.State) { org.yakindu.sct.model.sgraph.State state = (org.yakindu.sct.model.sgraph.State) transition .getTarget(); if (!state.isComposite()) { warning(TRANSITION_ENTRY_SPEC_NOT_COMPOSITE, transition, null, -1); } } } else if (!(property instanceof ExitPointSpec)) { continue; } final ExitPointSpec exitPointSpec = (ExitPointSpec) property; if (!(transition.getSource() instanceof org.yakindu.sct.model.sgraph.State)) { return; } org.yakindu.sct.model.sgraph.State state = (org.yakindu.sct.model.sgraph.State) transition.getSource(); if (!state.isComposite()) { warning(TRANSITION_EXIT_SPEC_NOT_COMPOSITE, transition, null, -1); } else { for (Transition t : state.getOutgoingTransitions()) { if (transition != t && STextValidationModelUtils.isNamedExitTransition(t, exitPointSpec.getExitpoint())) { warning(TRANSITION_EXIT_SPEC_ON_MULTIPLE_SIBLINGS, transition, null, -1); } } boolean hasExit = false; Iterator<Region> regionIter = state.getRegions().iterator(); while (regionIter.hasNext() && !hasExit) { Iterator<Exit> exitIter = STextValidationModelUtils.getExits(regionIter.next().eContents()) .iterator(); while (exitIter.hasNext() && !hasExit) { Exit exit = exitIter.next(); hasExit = exitPointSpec.getExitpoint().equals(exit.getName()); } } if (!hasExit) { error(TRANSITION_NOT_EXISTING_NAMED_EXIT_POINT, transition, null, -1); } } } }

Target:
public void checkTransitionPropertySpec(final Transition transition) { for (ReactionProperty property : transition.getProperties()) { if (property instanceof EntryPointSpec) { if (transition.getTarget() instanceof org.yakindu.sct.model.sgraph.State) { org.yakindu.sct.model.sgraph.State state = (org.yakindu.sct.model.sgraph.State) transition .getTarget(); if (!state.isComposite()) { warning(TRANSITION_ENTRY_SPEC_NOT_COMPOSITE, transition, null, -1); } } } else if (property instanceof ExitPointSpec) { final ExitPointSpec exitPointSpec = (ExitPointSpec) property; if (transition.getSource() instanceof org.yakindu.sct.model.sgraph.State) { org.yakindu.sct.model.sgraph.State state = (org.yakindu.sct.model.sgraph.State) transition .getSource(); if (!state.isComposite()) { warning(TRANSITION_EXIT_SPEC_NOT_COMPOSITE, transition, null, -1); } else { for (Transition t : state.getOutgoingTransitions()) { if (transition != t && STextValidationModelUtils.isNamedExitTransition(t, exitPointSpec.getExitpoint())) { warning(TRANSITION_EXIT_SPEC_ON_MULTIPLE_SIBLINGS, transition, null, -1); } } boolean hasExit = false; Iterator<Region> regionIter = state.getRegions().iterator(); while (regionIter.hasNext() && !hasExit) { Iterator<Exit> exitIter = STextValidationModelUtils.getExits(regionIter.next().eContents()) .iterator(); while (exitIter.hasNext() && !hasExit) { Exit exit = exitIter.next(); hasExit = exitPointSpec.getExitpoint().equals(exit.getName()); } } if (!hasExit) { error(TRANSITION_NOT_EXISTING_NAMED_EXIT_POINT, transition, null, -1); } } } } } }
Source:
public Client() { nwc.addServerPeer(); nwc.startListeningOnDefaultClientPort(); }

Target:
public Client() { this(NetworkController.DEFAULT_CLIENT_PORT); }
Source:
private static SwapTrade parseVariableRates(SwapTrade trade, List<CsvRow> variableRows) { ImmutableList.Builder<ValueStep> stepBuilder = ImmutableList.builder(); for (CsvRow row : variableRows) { LocalDate date = LoaderUtils.parseDate(row.getValue(START_DATE_FIELD)); row.findValue(FIXED_RATE_FIELD) .map(str -> LoaderUtils.parseDoublePercent(str)) .ifPresent(fixedRate -> stepBuilder.add(ValueStep.of(date, ValueAdjustment.ofReplace(fixedRate)))); } ImmutableList<ValueStep> vnotionals = stepBuilder.build(); if (vnotionals.isEmpty()) { return trade; } ImmutableList.Builder<SwapLeg> legBuilder = ImmutableList.builder(); for (SwapLeg swapLeg : trade.getProduct().getLegs()) { RateCalculationSwapLeg leg = (RateCalculationSwapLeg) swapLeg; if (leg.getCalculation() instanceof FixedRateCalculation) { FixedRateCalculation baseCalc = (FixedRateCalculation) leg.getCalculation(); FixedRateCalculation calc = baseCalc.toBuilder() .rate(ValueSchedule.of(baseCalc.getRate().getInitialValue(), vnotionals)) .build(); legBuilder.add(leg.toBuilder().calculation(calc).build()); } else { legBuilder.add(leg); } } return replaceLegs(trade, legBuilder.build()); }

Target:
private static SwapTrade parseVariableRates(SwapTrade trade, List<CsvRow> variableRows) { ImmutableList.Builder<ValueStep> stepBuilder = ImmutableList.builder(); for (CsvRow row : variableRows) { LocalDate date = LoaderUtils.parseDate(row.getValue(START_DATE_FIELD)); row.findValue(FIXED_RATE_FIELD) .map(str -> LoaderUtils.parseDoublePercent(str)) .ifPresent(fixedRate -> stepBuilder.add(ValueStep.of(date, ValueAdjustment.ofReplace(fixedRate)))); } ImmutableList<ValueStep> varRates = stepBuilder.build(); if (varRates.isEmpty()) { return trade; } ImmutableList.Builder<SwapLeg> legBuilder = ImmutableList.builder(); for (SwapLeg swapLeg : trade.getProduct().getLegs()) { RateCalculationSwapLeg leg = (RateCalculationSwapLeg) swapLeg; if (leg.getCalculation() instanceof FixedRateCalculation) { FixedRateCalculation baseCalc = (FixedRateCalculation) leg.getCalculation(); FixedRateCalculation calc = baseCalc.toBuilder() .rate(ValueSchedule.of(baseCalc.getRate().getInitialValue(), varRates)) .build(); legBuilder.add(leg.toBuilder().calculation(calc).build()); } else { legBuilder.add(leg); } } return replaceLegs(trade, legBuilder.build()); }
Source:
private static String arrayToString(final Object o) { if (o == null) { return "null"; } if (o.getClass().isArray()) { if (o instanceof Object[]) { return Arrays.toString((Object[]) o); } if (byte[].class.equals(o.getClass())) { return Arrays.toString((byte[])o); } if (short[].class.equals(o.getClass())) { return Arrays.toString((short[])o); } if (char[].class.equals(o.getClass())) { return Arrays.toString((char[])o); } if (int[].class.equals(o.getClass())) { return Arrays.toString((int[])o); } if (long[].class.equals(o.getClass())) { return Arrays.toString((long[])o); } if (float[].class.equals(o.getClass())) { return Arrays.toString((float[])o); } if (double[].class.equals(o.getClass())) { return Arrays.toString((double[])o); } if (boolean[].class.equals(o.getClass())) { return Arrays.toString((boolean[])o); } } return "unknown"; }

Target:
private static String arrayToString(final Object o) { if (o instanceof Object[]) { return Arrays.toString((Object[]) o); } final Class<?> clazz = o.getClass(); if (byte[].class.equals(clazz)) { return Arrays.toString((byte[]) o); } if (short[].class.equals(clazz)) { return Arrays.toString((short[]) o); } if (char[].class.equals(clazz)) { return Arrays.toString((char[]) o); } if (int[].class.equals(clazz)) { return Arrays.toString((int[]) o); } if (long[].class.equals(clazz)) { return Arrays.toString((long[]) o); } if (float[].class.equals(clazz)) { return Arrays.toString((float[]) o); } if (double[].class.equals(clazz)) { return Arrays.toString((double[]) o); } if (boolean[].class.equals(clazz)) { return Arrays.toString((boolean[]) o); } throw new IllegalArgumentException("Unknown array type: " + o.getClass()); }
Source:
public void removeProfile(ProfileService profile) { Message m = mHandler.obtainMessage(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); m.obj = profile; m.arg1 = MESSAGE_PROFILE_UNREGISTERED; mHandler.sendMessage(m); }

Target:
public void removeProfile(ProfileService profile) { Message m = mHandler.obtainMessage(MESSAGE_PROFILE_SERVICE_UNREGISTERED, profile); mHandler.sendMessage(m); }
Source:
void verifyGetterOpenBraceStyle(GetterClauseContext ctx) { Location getLocation = ListenerUtil.getContextStartLocation(ctx); verifyCodeBlockOpenBraceStyle(Messages.GETTER, getLocation, ctx.codeBlock()); }

Target:
void verifyGetterOpenBraceStyle(GetterClauseContext ctx) { TerminalNodeImpl get = (TerminalNodeImpl) ParseTreeUtil.getLeftSibling(ctx.codeBlock()); Location getLocation = ListenerUtil.getTokenLocation(get.getSymbol()); verifyCodeBlockOpenBraceStyle(Messages.GETTER, getLocation, ctx.codeBlock()); }
Source:
protected int getBlockSize(final String encryptionMode) { return BLOCK_SIZE_CACHE.computeIfAbsent(encryptionMode, BLOCK_SIZE_CALCULATOR); }

Target:
protected static int getBlockSize(final String encryptionMode) { return BLOCK_SIZE_CACHE.computeIfAbsent(encryptionMode, BLOCK_SIZE_CALCULATOR); }
Source:
public void onRestart() { if (postsSort == DiscussionPostsSort.LAST_ACTIVITY_AT && mSelectedItem != -1) { discussionPostsAdapter.moveToTop(mSelectedItem); mSelectedItem = -1; } nextPage = 1; controller.refresh(); }

Target:
public void onRestart() { if (postsSort == DiscussionPostsSort.LAST_ACTIVITY_AT && mSelectedItem != -1) { discussionPostsAdapter.moveToTop(mSelectedItem); mSelectedItem = -1; } nextPage = 1; controller.resetSilently(); }
Source:
public Document getNextPage(Document doc) throws IOException { String nextPage = ""; Element elem = null; if (getHost().contains("www.totempole666.com") == true || getHost().contains("buttsmithy.com") == true || getHost().contains("themonsterunderthebed.net") || getHost().contains("prismblush.com") || getHost().contains("www.konradokonski.com") || getHost().contains("thisis.delvecomic.com")) { elem = doc.select("a.comic-nav-next").first(); if (elem == null) { throw new IOException("No more pages"); } nextPage = elem.attr("href"); } if (nextPage == "") { throw new IOException("No more pages"); } else { sleep(500); return Http.url(nextPage).get(); } }

Target:
public Document getNextPage(Document doc) throws IOException { String nextPage = ""; Element elem = null; if (getHost().contains("www.totempole666.com") || getHost().contains("buttsmithy.com") || getHost().contains("themonsterunderthebed.net") || getHost().contains("prismblush.com") || getHost().contains("www.konradokonski.com") || getHost().contains("thisis.delvecomic.com")) { elem = doc.select("a.comic-nav-next").first(); if (elem == null) { throw new IOException("No more pages"); } nextPage = elem.attr("href"); } if (nextPage == "") { throw new IOException("No more pages"); } else { return Http.url(nextPage).get(); } }
Source:
public boolean onOptionsItemSelected(MenuItem item) { if (usingNavDrawer() && item.getItemId() == android.R.id.home) { if (navDrawerController.isDrawerOpen()) { navDrawerController.closeDrawer(); } else { navDrawerController.openDrawer(); } return true; } return super.onOptionsItemSelected(item); }

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (usingNavDrawer() && item.getItemId() == android.R.id.home) { navDrawerController.toggleDrawer(); return true; } return super.onOptionsItemSelected(item); }
Source:
public boolean delete() { if (fileLock != null) { try { fileLock.release(); } catch (Exception ignored) { } } try { return Files.deleteIfExists(file.toPath()); } catch (Exception ignored) { return false; } }

Target:
public void delete() { release(); deleteIfExists(file); }
Source:
protected void onRevisit() { if (NetworkUtil.isConnected(getActivity())) { if (getActivity() instanceof SnackbarStatusListener) { ((SnackbarStatusListener) getActivity()).hideSnackBar(); } } }

Target:
protected void onRevisit() { CourseTabsUtils.onRevisit(getActivity()); }
Source:
public ClientTxContext(int txId, GridNearTxLocal tx) { this.txId = txId; this.tx = tx; }

Target:
public ClientTxContext(int txId, GridNearTxLocal tx) { assert txId != 0; assert tx != null; this.txId = txId; this.tx = tx; }
Source:
public static List<ProcessKillingVeto> all() { Jenkins jenkins = Jenkins.getInstance(); if ( null == jenkins ) return Collections.emptyList(); return jenkins.getExtensionList(ProcessKillingVeto.class); }

Target:
public static List<ProcessKillingVeto> all() { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) return Collections.emptyList(); return jenkins.getExtensionList(ProcessKillingVeto.class); }
Source:
private void validateBoundaryOutgoingTransitions(final BoundaryEventDefinition boundaryEvent) { for (final TransitionDefinition transition : boundaryEvent.getOutgoingTransitions()) { if (transition.getCondition() != null) { designErrors.add("A boundary event must have not unconditional transitions: " + transition.getSource() + "->" + transition.getTarget()); } } }

Target:
private void validateBoundaryOutgoingTransitions(final BoundaryEventDefinition boundaryEvent) { for (final TransitionDefinition transition : boundaryEvent.getOutgoingTransitions()) { if (transition.getCondition() != null) { designErrors.add("A boundary event must have no conditional transitions: " + transition.getSource() + "->" + transition.getTarget()); } } }
Source:
public boolean performFinish() { final boolean result[] = { false }; try { getContainer().run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { IProject project = scenarioPage.getProject(); String name = scenarioPage.getScenarioName(); IPath containerPath = scenarioPage.getPathInProject(); testCase = RcpttCore .create(project) .getFolder(containerPath) .createTestCase(name, true, new NullProgressMonitor()); ITestCase workingCopy = (ITestCase) testCase .getWorkingCopy(new NullProgressMonitor()); try { workingCopy.setType(getType()); WriteAccessChecker writeAccessChecker = new WriteAccessChecker(); if (!writeAccessChecker.makeResourceWritable(workingCopy)) { result[0] = false; } else { workingCopy.commitWorkingCopy(true, new NullProgressMonitor()); } } finally { workingCopy.discardWorkingCopy(); } if (openEditor) { IDE.openEditor(getPage(), (IFile) testCase.getResource()); } result[0] = true; } catch (Exception e) { Q7UIPlugin.log(e); result[0] = false; } } }); } catch (Throwable e) { Q7UIPlugin.log(e); } return result[0]; }

Target:
public boolean performFinish() { final boolean result[] = { false }; try { getContainer().run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { IProject project = scenarioPage.getProject(); String name = scenarioPage.getScenarioName(); IPath containerPath = scenarioPage.getPathInProject(); testCase = RcpttCore .create(project) .getFolder(containerPath) .createTestCase(name, true, new NullProgressMonitor()); ITestCase workingCopy = (ITestCase) testCase .getWorkingCopy(new NullProgressMonitor()); try { workingCopy.setType(getType()); WriteAccessChecker writeAccessChecker = new WriteAccessChecker(getShell()); if (!writeAccessChecker.makeResourceWritable(workingCopy)) { result[0] = false; } else { workingCopy.commitWorkingCopy(true, new NullProgressMonitor()); } } finally { workingCopy.discardWorkingCopy(); } if (openEditor) { IDE.openEditor(getPage(), (IFile) testCase.getResource()); } result[0] = true; } catch (Exception e) { Q7UIPlugin.log(e); result[0] = false; } } }); } catch (Throwable e) { Q7UIPlugin.log(e); } return result[0]; }
Source:
public void storeAssociation(EntityKey key, Association document) { byte[] associationId = associationId( key ); connection.del( associationId ); for ( Object row : document.getRows() ) { connection.rpush( associationId, serializationStrategy.serialize( row ) ); } }

Target:
private void storeAssociation(EntityKey key, Association document) { byte[] associationId = associationId( key ); connection.del( associationId ); for ( Object row : document.getRows() ) { connection.rpush( associationId, serializationStrategy.serialize( row ) ); } }
Source:
private void removeVmStatelessImages() { if (getSnapshotDao().exists(getVmId(), SnapshotType.STATELESS) && !VmPoolType.Manual.equals(getVmPoolType())) { log.info("Deleting snapshot for stateless vm '{}'", getVmId()); runInternalAction(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(getVmId()), ExecutionHandler.createDefaultContextForTasks(getContext(), getLock())); } }

Target:
private void removeVmStatelessImages() { if (getSnapshotDao().exists(getVmId(), SnapshotType.STATELESS) && getVmPoolType() != VmPoolType.Manual) { log.info("Deleting snapshot for stateless vm '{}'", getVmId()); runInternalAction(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(getVmId()), ExecutionHandler.createDefaultContextForTasks(getContext(), getLock())); } }
Source:
public void testCanceledExecutionReturnsSlot() throws Exception { final JobVertex jobVertex = createNoOpJobVertex(); final JobVertexID jobVertexId = jobVertex.getID(); final SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway(); TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.builder() .withTaskManagerGateway(taskManagerGateway) .build(); final SchedulerBase scheduler = SchedulerTestingUtils.newSchedulerBuilder(new JobGraph(jobVertex)) .setExecutionSlotAllocatorFactory(SchedulerTestingUtils.slotSharingExecutionSlotAllocatorFactoryBuilder() .withSlotProvider(physicalSlotProvider) .build()) .build(); scheduler.initialize(testMainThreadUtil.getMainThreadExecutor()); ExecutionJobVertex executionJobVertex = scheduler.getExecutionJobVertex(jobVertexId); ExecutionVertex executionVertex = executionJobVertex.getTaskVertices()[0]; final Execution execution = executionVertex.getCurrentExecutionAttempt(); taskManagerGateway.setCancelConsumer( executionAttemptID -> { if (execution.getAttemptId().equals(executionAttemptID)) { execution.completeCancelling(); } } ); testMainThreadUtil.execute(scheduler::startScheduling); testMainThreadUtil.execute(execution::cancel); assertThat(physicalSlotProvider.getRequests().keySet(), is(physicalSlotProvider.getCancellations().keySet())); }

Target:
public void testCanceledExecutionReturnsSlot() throws Exception { final JobVertex jobVertex = createNoOpJobVertex(); final JobVertexID jobVertexId = jobVertex.getID(); final SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway(); TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.create( (resourceProfile) -> CompletableFuture.completedFuture( TestingPhysicalSlot.builder() .withTaskManagerGateway(taskManagerGateway) .build())); final SchedulerBase scheduler = SchedulerTestingUtils.newSchedulerBuilder(new JobGraph(jobVertex)) .setExecutionSlotAllocatorFactory( SchedulerTestingUtils.newSlotSharingExecutionSlotAllocatorFactory( physicalSlotProvider)) .build(); scheduler.initialize(testMainThreadUtil.getMainThreadExecutor()); ExecutionJobVertex executionJobVertex = scheduler.getExecutionJobVertex(jobVertexId); ExecutionVertex executionVertex = executionJobVertex.getTaskVertices()[0]; final Execution execution = executionVertex.getCurrentExecutionAttempt(); taskManagerGateway.setCancelConsumer( executionAttemptID -> { if (execution.getAttemptId().equals(executionAttemptID)) { execution.completeCancelling(); } }); testMainThreadUtil.execute(scheduler::startScheduling); testMainThreadUtil.execute(execution::cancel); assertThat( physicalSlotProvider.getRequests().keySet(), is(physicalSlotProvider.getCancellations().keySet())); }