auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void browserTest() throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { final String namespace = "namespace"; final String tableName = "table"; Process corfuServer = runSinglePersistentServer(corfuSingleNodeHost, corfuStringNodePort); runtime = createRuntime(singleNodeEndpoint); CorfuStore store = new CorfuStore(runtime); store.openTable( namespace, tableName, SampleSchema.Uuid.class, SampleSchema.Uuid.class, SampleSchema.Uuid.class, TableOptions.builder().build()); final long keyUuid = 1L; final long valueUuid = 3L; final long metadataUuid = 5L; SampleSchema.Uuid uuidKey = SampleSchema.Uuid.newBuilder() .setMsb(keyUuid) .setLsb(keyUuid) .build(); SampleSchema.Uuid uuidVal = SampleSchema.Uuid.newBuilder() .setMsb(valueUuid) .setLsb(valueUuid) .build(); SampleSchema.Uuid metadata = SampleSchema.Uuid.newBuilder() .setMsb(metadataUuid) .setLsb(metadataUuid) .build(); TxBuilder tx = store.tx(namespace); tx.create(tableName, uuidKey, uuidVal, metadata) .update(tableName, uuidKey, uuidVal, metadata) .commit(); runtime.shutdown(); runtime.connect(); CorfuStoreBrowser browser = new CorfuStoreBrowser(runtime); CorfuTable table = browser.getTable(namespace, tableName); browser.printTable(table); Assert.assertEquals(1, table.size()); for(Object obj : table.values()) { CorfuDynamicRecord record = (CorfuDynamicRecord)obj; Assert.assertEquals( UnknownFieldSet.newBuilder().build(), record.getPayload().getUnknownFields()); } }

Target:
public void browserTest() throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { final String namespace = "namespace"; final String tableName = "table"; Process corfuServer = runSinglePersistentServer(corfuSingleNodeHost, corfuStringNodePort); runtime = createRuntime(singleNodeEndpoint); CorfuStore store = new CorfuStore(runtime); store.openTable( namespace, tableName, SampleSchema.Uuid.class, SampleSchema.Uuid.class, SampleSchema.Uuid.class, TableOptions.builder().build()); final long keyUuid = 1L; final long valueUuid = 3L; final long metadataUuid = 5L; SampleSchema.Uuid uuidKey = SampleSchema.Uuid.newBuilder() .setMsb(keyUuid) .setLsb(keyUuid) .build(); SampleSchema.Uuid uuidVal = SampleSchema.Uuid.newBuilder() .setMsb(valueUuid) .setLsb(valueUuid) .build(); SampleSchema.Uuid metadata = SampleSchema.Uuid.newBuilder() .setMsb(metadataUuid) .setLsb(metadataUuid) .build(); TxBuilder tx = store.tx(namespace); tx.create(tableName, uuidKey, uuidVal, metadata) .update(tableName, uuidKey, uuidVal, metadata) .commit(); runtime.shutdown(); runtime = createRuntime(singleNodeEndpoint); CorfuStoreBrowser browser = new CorfuStoreBrowser(runtime); CorfuTable table = browser.getTable(namespace, tableName); browser.printTable(table); Assert.assertEquals(1, table.size()); for(Object obj : table.values()) { CorfuDynamicRecord record = (CorfuDynamicRecord)obj; Assert.assertEquals( UnknownFieldSet.newBuilder().build(), record.getPayload().getUnknownFields()); } }
Source:
public List<Guid> getCommandIdsBySessionSeqId(long engineSessionSeqId) { List<Guid> cmdIds = new ArrayList<>(); CommandEntity cmdEntity; for (Guid cmdId : commandsCache.keySet()) { cmdEntity = commandsCache.get(cmdId); if (cmdEntity != null && cmdEntity.getEngineSessionSeqId() != -1 && cmdEntity.getEngineSessionSeqId() == engineSessionSeqId) { cmdIds.add(cmdId); } } return cmdIds; }

Target:
public List<Guid> getCommandIdsBySessionSeqId(long engineSessionSeqId) { List<Guid> cmdIds = new ArrayList<>(); CommandEntity cmdEntity; for (Guid cmdId : commandsCache.keySet()) { cmdEntity = commandsCache.get(cmdId); if (cmdEntity != null && cmdEntity.getEngineSessionSeqId() != SSOSessionUtils.EMPTY_SESSION_SEQ_ID && cmdEntity.getEngineSessionSeqId() == engineSessionSeqId) { cmdIds.add(cmdId); } } return cmdIds; }
Source:
private String generatePatientId() { int number = new Random().nextInt(10000000); return "CONNECT-" + String.format ("%07d", number); }

Target:
private static String generatePatientId() { return "CONNECT-" + new Date().getTime(); }
Source:
public static void initTestCase() throws Exception { EjbUtils.setStrategy(new DaoTestEjbUtilsStrategy()); if(dataSource == null) { dataSource = createDataSource(); dataset = initDataSet(); dbFacade = DbFacadeLocator.getDbFacade(); dbFacade.setDbEngineDialect(DbFacadeLocator.loadDbEngineDialect()); DatabaseOperation.CLEAN_INSERT.execute(getConnection(), dataset); } }

Target:
public static void initTestCase() throws Exception { if(dataSource == null) { dataSource = createDataSource(); ejbRule.mockResource(ContainerManagedResourceType.DATA_SOURCE, dataSource); dataset = initDataSet(); dbFacade = DbFacadeLocator.getDbFacade(); dbFacade.setDbEngineDialect(DbFacadeLocator.loadDbEngineDialect()); DatabaseOperation.CLEAN_INSERT.execute(getConnection(), dataset); } }
Source:
public Function newInstance(ObjList<Function> args, int position, CairoConfiguration configuration) throws SqlException { Function value = args.getQuick(0); CharSequence likeString=args.getQuick(1).getStr(null); if (likeString == null) { throw SqlException.$(args.getQuick(1).getPosition(), "NULL likeString"); } String regex = escapeSpecialChars(likeString). replace('_', '.').replace("%", ".*?"); try { Matcher matcher = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(""); return new MatchFunction(position, value, matcher); } catch (PatternSyntaxException e) { throw SqlException.$(args.getQuick(1).getPosition() + e.getIndex() + 1, e.getMessage()); } }

Target:
public Function newInstance(ObjList<Function> args, int position, CairoConfiguration configuration) throws SqlException { Function value = args.getQuick(0); CharSequence likeString = args.getQuick(1).getStr(null); if (likeString == null) { throw SqlException.$(args.getQuick(1).getPosition(), "NULL input not supported for like"); } String regex = escapeSpecialChars(likeString); Matcher matcher = Pattern.compile(regex, Pattern.DOTALL).matcher(""); return new MatchFunction(position, value, matcher); }
Source:
private void showWord(final Word word) { currentCard.findViewById(R.id.general_crad).setVisibility(View.VISIBLE); currentCard.findViewById(R.id.error_crad).setVisibility(View.GONE); TextView wordTextView = (TextView) currentCard.findViewById(R.id.textview_word); TextView descriptionTextView = (TextView) currentCard.findViewById(R.id.textview_desc); Button goToWikiButton = (Button) currentCard.findViewById(R.id.button_go_to_wiki); wordTextView.setText(word.label); loadImage(word.imageURL); descriptionTextView.setText(word.shortDesc); descriptionTextView.setMovementMethod(new ScrollingMovementMethod()); goToWikiButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(word.url)); startActivity(intent); } }); }

Target:
private void showWord(final Word word) { currentCard.findViewById(R.id.general_card).setVisibility(View.VISIBLE); currentCard.findViewById(R.id.error_card).setVisibility(View.GONE); TextView wordTextView = (TextView) currentCard.findViewById(R.id.textview_word); TextView descriptionTextView = (TextView) currentCard.findViewById(R.id.textview_desc); Button goToWikiButton = (Button) currentCard.findViewById(R.id.button_go_to_wiki); wordTextView.setText(word.label); loadImage(word.imageURL); descriptionTextView.setText(word.shortDesc); goToWikiButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(word.url)); startActivity(intent); } }); }
Source:
public Map<Long, ILogData> readRange(RuntimeLayout runtimeLayout, Set<Long> globalAddresses) { return globalAddresses.parallelStream() .map(a -> new AbstractMap.SimpleImmutableEntry<>(a, read(runtimeLayout, a))) .collect(Collectors.toMap(r -> r.getKey(), r -> r.getValue())); }

Target:
public Map<Long, ILogData> readRange(RuntimeLayout runtimeLayout, Set<Long> globalAddresses) { return globalAddresses.parallelStream() .collect(Collectors.toMap(addr -> addr, addr -> read(runtimeLayout, addr))); }
Source:
String checkForError() { if (artifactTypeCheckbox.isSelected() && artifactList.getSelectedValuesList().isEmpty()) { return "At least one Result type must be selected."; } return ""; }

Target:
String checkForError() { if (artifactTypeCheckbox.isSelected() && artifactList.getSelectedValuesList().isEmpty()) { return Bundle.ArtifactTypeFilterPanel_selectionNeeded_text(); } return ""; }
Source:
public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { if (templateOptions.getSecurityGroupIds().size() > 0) { options.securityGroupIds(templateOptions.getSecurityGroupIds()); } if (templateOptions.getNetworks().size() > 0) { options.networkIds(templateOptions.getNetworks()); } return options; }

Target:
public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { if (!templateOptions.getSecurityGroupIds().isEmpty()) { options.securityGroupIds(templateOptions.getSecurityGroupIds()); } if (!templateOptions.getNetworks().isEmpty()) { options.networkIds(templateOptions.getNetworks()); } return options; }
Source:
public void should_mark_nested_argument_as_part_of_full_argument(){ Formats formats = new AnsiFormats(); Argument fullArg = new Argument(20, "and not yet confirmed"); Argument nestedArg = new Argument(-21, "not yet "); PrettyFormatter prettyFormatter = new PrettyFormatter(null); String formattedText = prettyFormatter.formatStepText("Given ", "the order is placed and not yet confirmed", formats.get("passed"), formats.get("passed_arg"), asList(fullArg, nestedArg)); assertThat(formattedText, equalTo(AnsiEscapes.GREEN + "Given " + AnsiEscapes.RESET + AnsiEscapes.GREEN + "the order is placed " + AnsiEscapes.RESET + AnsiEscapes.GREEN + AnsiEscapes.INTENSITY_BOLD + "and not yet confirmed" + AnsiEscapes.RESET)); }

Target:
public void should_mark_nested_argument_as_part_of_full_argument(){ Formats formats = new AnsiFormats(); Argument enclosingArg = new Argument(20, "and not yet confirmed"); Argument nestedArg = new Argument(-17, "not yet "); PrettyFormatter prettyFormatter = new PrettyFormatter(null); String formattedText = prettyFormatter.formatStepText("Given ", "the order is placed and not yet confirmed", formats.get("passed"), formats.get("passed_arg"), asList(enclosingArg, nestedArg)); assertThat(formattedText, equalTo(AnsiEscapes.GREEN + "Given " + AnsiEscapes.RESET + AnsiEscapes.GREEN + "the order is placed " + AnsiEscapes.RESET + AnsiEscapes.GREEN + AnsiEscapes.INTENSITY_BOLD + "and not yet confirmed" + AnsiEscapes.RESET)); }
Source:
public void tearDown() throws Exception { mJobScheduler.cancel(CONNECTIVITY_JOB_ID); if (mInitialRestrictBackground) { SystemUtil.runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_ON_CMD); } if (mHasWifi) { if (mWifiManager.isWifiEnabled() != mInitialWiFiState) { NetworkInfo.State expectedState = mInitialWiFiState ? NetworkInfo.State.CONNECTED : NetworkInfo.State.DISCONNECTED; ConnectivityActionReceiver receiver = new ConnectivityActionReceiver(ConnectivityManager.TYPE_WIFI, expectedState); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); mContext.registerReceiver(receiver, filter); assertTrue(mWifiManager.setWifiEnabled(mInitialWiFiState)); receiver.waitForStateChange(); assertTrue("Failure to restore previous WiFi state", mWifiManager.isWifiEnabled() == mInitialWiFiState); mContext.unregisterReceiver(receiver); } } super.tearDown(); }

Target:
public void tearDown() throws Exception { mJobScheduler.cancel(CONNECTIVITY_JOB_ID); if (mInitialRestrictBackground) { SystemUtil.runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_ON_CMD); } if (mHasWifi && (mWifiManager.isWifiEnabled() != mInitialWiFiState)) { NetworkInfo.State expectedState = mInitialWiFiState ? NetworkInfo.State.CONNECTED : NetworkInfo.State.DISCONNECTED; ConnectivityActionReceiver receiver = new ConnectivityActionReceiver(ConnectivityManager.TYPE_WIFI, expectedState); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); mContext.registerReceiver(receiver, filter); assertTrue(mWifiManager.setWifiEnabled(mInitialWiFiState)); receiver.waitForStateChange(); assertTrue("Failure to restore previous WiFi state", mWifiManager.isWifiEnabled() == mInitialWiFiState); mContext.unregisterReceiver(receiver); } super.tearDown(); }
Source:
private static @NonNull Table<ITimeGraphEntry, @NonNull Pair<Long, Long>, List<ITimeEvent>> regroupOverlappingGaps(Map<? extends ITimeGraphEntry, List<ITimeEvent>> gapsMap) { Table<ITimeGraphEntry, @NonNull Pair<Long, Long>, List<ITimeEvent>> gapsTable = HashBasedTable.create(); PriorityQueue<ITimeEvent> queue = new PriorityQueue<>(TIME_EVENT_COMPARATOR); gapsMap.values().forEach(event -> queue.addAll(event)); Pair<Long, Long> previous = null; while(!queue.isEmpty()) { ITimeEvent event = Objects.requireNonNull(queue.poll()); ITimeGraphEntry entry = event.getEntry(); Pair<Long, Long> result = previous != null && event.getTime() < previous.getRight() && event.getTime() + event.getDuration() > previous.getLeft() ? previous : null; Map<ITimeGraphEntry, List<ITimeEvent>> column = new HashMap<>(); if (result != null) { Pair<Long, Long> merged = mergeInterval(result, event); column = gapsTable.column(result); if (!result.equals(merged)) { gapsTable.columnKeySet().remove(result); result = merged; for (Entry<ITimeGraphEntry, List<ITimeEvent>> row : column.entrySet()) { gapsTable.put(row.getKey(), result, row.getValue()); } } } else { result = Objects.requireNonNull(Pair.of(event.getTime(), event.getTime() + event.getDuration())); } previous = result; List<ITimeEvent> events = gapsTable.get(entry, result); if (events == null) { events = new ArrayList<>(); gapsTable.put(entry, result, events); } events.add(event); } return gapsTable; }

Target:
private static @NonNull Table<ITimeGraphEntry, @NonNull Pair<Long, Long>, List<ITimeEvent>> regroupOverlappingGaps(Map<? extends ITimeGraphEntry, List<ITimeEvent>> gapsMap) { Table<ITimeGraphEntry, @NonNull Pair<Long, Long>, List<ITimeEvent>> gapsTable = HashBasedTable.create(); PriorityQueue<ITimeEvent> queue = new PriorityQueue<>(TIME_EVENT_COMPARATOR); gapsMap.values().forEach(events -> queue.addAll(events)); Pair<Long, Long> previous = null; while(!queue.isEmpty()) { ITimeEvent event = Objects.requireNonNull(queue.poll()); ITimeGraphEntry entry = event.getEntry(); Pair<Long, Long> result = previous != null && event.getTime() < previous.getRight() && event.getTime() + event.getDuration() > previous.getLeft() ? previous : null; if (result != null) { Pair<Long, Long> merged = mergeInterval(result, event); Map<ITimeGraphEntry, List<ITimeEvent>> currentColumn = gapsTable.column(result); Map<ITimeGraphEntry, List<ITimeEvent>> column = new HashMap<>(currentColumn); final int count[] = new int[]{0}; column.values().forEach(events -> { count[0] += events.size();}); if (!result.equals(merged)) { gapsTable.columnKeySet().remove(result); final int count2[] = new int[]{0}; column.values().forEach(events -> { count2[0] += events.size();}); result = merged; for (Entry<ITimeGraphEntry, List<ITimeEvent>> row : column.entrySet()) { gapsTable.put(row.getKey(), result, row.getValue()); } } } else { result = Objects.requireNonNull(Pair.of(event.getTime(), event.getTime() + event.getDuration())); } previous = result; List<ITimeEvent> events = gapsTable.get(entry, result); if (events == null) { events = new ArrayList<>(); gapsTable.put(entry, result, events); } events.add(event); } return gapsTable; }
Source:
public boolean equals(Object obj) { if (!(obj instanceof OgcMessage)) return false; OgcMessage other = (OgcMessage) obj; return new EqualsBuilder() .appendSuper(super.equals(other)) .append(getService(), other.getService()) .append(getOperation(), other.getOperation()) .append(getEndPoint(), other.getEndPoint()) .isEquals(); }

Target:
public boolean equals(Object obj) { if (!(obj instanceof OgcMessage)) return false; OgcMessage other = (OgcMessage) obj; return new EqualsBuilder() .append(getService(), other.getService()) .append(getOperation(), other.getOperation()) .append(getEndPoint(), other.getEndPoint()) .append(getRequestRule(), other.getRequestRule()) .append(getResponseRule(), other.getResponseRule()) .isEquals(); }
Source:
void enrich(ConfigDef newDef) { Object aliases = ConfigDef.parseType(aliasConfig, props.get(aliasConfig), Type.LIST); if (!(aliases instanceof List)) { return; } LinkedHashSet<?> uniqueAliases = new LinkedHashSet<>((List<?>) aliases); for (Object o : uniqueAliases) { if (!(o instanceof String)) { throw new ConfigException("Item in " + aliasConfig + " property is not of " + "type String"); } String alias = (String) o; final String prefix = aliasConfig + "." + alias + "."; final String group = aliasGroup + ": " + alias; int orderInGroup = 0; final String typeConfig = prefix + "type"; final ConfigDef.Validator typeValidator = new ConfigDef.Validator() { @Override public void ensureValid(String name, Object value) { validateProps(prefix); getConfigDefFromConfigProvidingClass(typeConfig, (Class<?>) value); } }; newDef.define(typeConfig, Type.CLASS, ConfigDef.NO_DEFAULT_VALUE, typeValidator, Importance.HIGH, "Class for the '" + alias + "' " + aliasKind.toLowerCase(Locale.ENGLISH) + ".", group, orderInGroup++, Width.LONG, baseClass.getSimpleName() + " type for " + alias, Collections.emptyList(), new ClassRecommender()); final ConfigDef configDef = populateConfigDef(typeConfig); if (configDef == null) continue; newDef.embed(prefix, group, orderInGroup, configDef); } }

Target:
void enrich(ConfigDef newDef) { Object aliases = ConfigDef.parseType(aliasConfig, props.get(aliasConfig), Type.LIST); if (!(aliases instanceof List)) { return; } LinkedHashSet<?> uniqueAliases = new LinkedHashSet<>((List<?>) aliases); for (Object o : uniqueAliases) { if (!(o instanceof String)) { throw new ConfigException("Item in " + aliasConfig + " property is not of " + "type String"); } String alias = (String) o; final String prefix = aliasConfig + "." + alias + "."; final String group = aliasGroup + ": " + alias; int orderInGroup = 0; final String typeConfig = prefix + "type"; final ConfigDef.Validator typeValidator = ConfigDef.LambdaValidator.with( (String name, Object value) -> { validateProps(prefix); getConfigDefFromConfigProvidingClass(typeConfig, (Class<?>) value); }, () -> "valid configs for " + alias + " " + aliasKind.toLowerCase(Locale.ENGLISH)); newDef.define(typeConfig, Type.CLASS, ConfigDef.NO_DEFAULT_VALUE, typeValidator, Importance.HIGH, "Class for the '" + alias + "' " + aliasKind.toLowerCase(Locale.ENGLISH) + ".", group, orderInGroup++, Width.LONG, baseClass.getSimpleName() + " type for " + alias, Collections.emptyList(), new ClassRecommender()); final ConfigDef configDef = populateConfigDef(typeConfig); if (configDef == null) continue; newDef.embed(prefix, group, orderInGroup, configDef); } }
Source:
public int linkifyUri(String text, int startPos, StringBuffer outputBuffer) { Matcher matcher = BITCOIN_URI_PATTERN.matcher(text); if (!matcher.find(startPos) || matcher.start() != startPos) { return startPos; } String linkifiedUri = String.format("<a href=\"%1$s\">%1$s</a>", matcher.group()); outputBuffer.append(linkifiedUri); return matcher.end(); }

Target:
public int linkifyUri(String text, int startPos, StringBuffer outputBuffer) { Matcher matcher = BITCOIN_URI_PATTERN.matcher(text); if (!matcher.find(startPos) || matcher.start() != startPos) { return startPos; } String bitcoinUri = matcher.group(); outputBuffer.append("<a href=\"") .append(bitcoinUri) .append("\">") .append(bitcoinUri) .append("</a>"); return matcher.end(); }
Source:
} catch (ClassNotFoundException | NoSuchMethodException e) { rule = new SwitchTargetSdkVersionRule() { @Override protected Statement createStatement(Statement statement, int targetSdkVersion) { return new Statement() { @Override public void evaluate() { fail("Targeting SDK version not supported as " + VMRUNTIME + " is not supported"); } }; } }; }

Target:
} catch (ClassNotFoundException | NoSuchMethodException e) { rule = new VMRuntimeNotSupported(); }
Source:
private boolean hidePart(MPart part, boolean save, boolean confirm, boolean force, boolean local) { if (!partService.getParts().contains(part)) { if (local) { return false; } part.setToBeRendered(false); return true; } Object clientObject = part.getObject(); if (clientObject == null || !(clientObject instanceof CompatibilityPart)) { if (save) { if (partService.savePart(part, confirm)) { partService.hidePart(part, force); return true; } return false; } partService.hidePart(part, force); return true; } IWorkbenchPart workbenchPart = getWrappedPart((CompatibilityPart) clientObject); if (save && workbenchPart != null) { ISaveablePart saveablePart = SaveableHelper.getSaveable(workbenchPart); if (saveablePart != null) { if (saveablePart.isSaveOnCloseNeeded()) { if (!saveSaveable(saveablePart, workbenchPart, confirm, true)) { return false; } } } } for (IViewReference viewRef : viewReferences) { if (workbenchPart == viewRef.getPart(false)) { partService.hidePart(part, force); return true; } } for (IEditorReference viewRef : editorReferences) { if (workbenchPart == viewRef.getPart(false)) { partService.hidePart(part, force); return true; } } return false; }

Target:
private boolean hidePart(MPart part, boolean save, boolean confirm, boolean force, boolean local) { if (!partService.getParts().contains(part)) { if (local) { return false; } part.setToBeRendered(false); return true; } Object clientObject = part.getObject(); if (!(clientObject instanceof CompatibilityPart)) { if (save) { if (partService.savePart(part, confirm)) { partService.hidePart(part, force); return true; } return false; } partService.hidePart(part, force); return true; } IWorkbenchPart workbenchPart = getWrappedPart((CompatibilityPart) clientObject); if (save && workbenchPart != null) { ISaveablePart saveablePart = SaveableHelper.getSaveable(workbenchPart); if (saveablePart != null) { if (saveablePart.isSaveOnCloseNeeded()) { if (!saveSaveable(saveablePart, workbenchPart, confirm, true)) { return false; } } } } for (IViewReference viewRef : viewReferences) { if (workbenchPart == viewRef.getPart(false)) { partService.hidePart(part, force); return true; } } for (IEditorReference viewRef : editorReferences) { if (workbenchPart == viewRef.getPart(false)) { partService.hidePart(part, force); return true; } } return false; }
Source:
public static void populateStockIdInListDataProject(final List<ListDataProject> data , InventoryDataManager inventoryDataManager) { final List<Integer> gids = new ArrayList<>(); if (data != null && !data.isEmpty()) { for (final ListDataProject listDataProject : data) { gids.add(listDataProject.getGermplasmId()); } } Map<Integer, String> stockIds = inventoryDataManager.retrieveStockIds(gids); if (data != null && !data.isEmpty()) { for (final ListDataProject ListData : data) { String stockIdValue = ""; if (stockIds != null) { for (final Integer gid : stockIds.keySet()) { if (ListData.getGermplasmId().equals(gid)) { stockIdValue = stockIds.get(gid); break; } } } ListData.setStockIDs(stockIdValue); } } }

Target:
public static void populateStockIdInListDataProject(final List<ListDataProject> data , InventoryDataManager inventoryDataManager) { final List<Integer> gids = new ArrayList<>(); if (data != null && !data.isEmpty()) { for (final ListDataProject listDataProject : data) { gids.add(listDataProject.getGermplasmId()); } } Map<Integer, String> stockIds = inventoryDataManager.retrieveStockIds(gids); if (data != null && !data.isEmpty()) { for (final ListDataProject listData : data) { String stockIdValue = ""; if (stockIds != null) { for (final Integer gid : stockIds.keySet()) { if (listData.getGermplasmId().equals(gid)) { stockIdValue = stockIds.get(gid); break; } } } listData.setStockIDs(stockIdValue); } } }
Source:
private static String getSupportedProperty(final List<String> supportedProperties, final Map<String, String> propertiesMap) { for (final String supportedProperty : supportedProperties) { if (propertiesMap.containsKey(supportedProperty)) { final String prop = propertiesMap.get(supportedProperty); ParameterHandler.LOG.debug("Supported convention property: found: {}", supportedProperty, prop); return prop; } } return null; }

Target:
private static Optional<String> getSupportedProperty(final List<String> supportedProperties, final Map<String, String> propertiesMap) { return supportedProperties.stream().filter(propertiesMap::containsKey).findFirst().map(propertiesMap::get); }
Source:
private String[][] getZoneStringsImpl(boolean needsCopy) { if (zoneStrings == null) { zoneStrings = TimeZoneNames.getZoneStrings(locale); } if (!needsCopy) { return zoneStrings; } int len = zoneStrings.length; String[][] aCopy = new String[len][]; for (int i = 0; i < len; i++) { aCopy[i] = Arrays.copyOf(zoneStrings[i], zoneStrings[i].length); } return aCopy; }

Target:
private final String[][] getZoneStringsImpl(boolean needsCopy) { String[][] zoneStrings = internalZoneStrings(); END Android-changed: extract initialization of zoneStrings to separate method. if (!needsCopy) { return zoneStrings; } int len = zoneStrings.length; String[][] aCopy = new String[len][]; for (int i = 0; i < len; i++) { aCopy[i] = Arrays.copyOf(zoneStrings[i], zoneStrings[i].length); } return aCopy; }
Source:
public Collection<Mutation> toMutations(K key, long seq) { Map<RowColumn, Bytes> oldData = generateData(key, oldVal); Map<RowColumn, Bytes> newData = generateData(key, newVal); Map<Bytes, Mutation> mutationMap = new HashMap<>(); for (Map.Entry<RowColumn, Bytes> entry : oldData.entrySet()) { RowColumn rc = entry.getKey(); if (!newData.containsKey(rc)) { Mutation m = mutationMap.computeIfAbsent(rc.getRow(), r -> new Mutation(r.toArray())); m.putDelete(rc.getColumn().getFamily().toArray(), rc.getColumn().getQualifier().toArray()); } } for (Map.Entry<RowColumn, Bytes> entry : newData.entrySet()) { RowColumn rc = entry.getKey(); Column col = rc.getColumn(); Bytes val = entry.getValue(); if (!oldData.containsKey(rc) || !oldData.get(rc).equals(val)) { Mutation m = mutationMap.computeIfAbsent(rc.getRow(), r -> new Mutation(r.toArray())); m.put(col.getFamily().toArray(), col.getQualifier().toArray(), seq, val.toArray()); } } return mutationMap.values(); }

Target:
public Collection<Mutation> toMutations(K key, long seq) { Map<RowColumn, Bytes> oldData = generateData(key, oldVal); Map<RowColumn, Bytes> newData = generateData(key, newVal); Map<Bytes, Mutation> mutationMap = new HashMap<>(); for (Map.Entry<RowColumn, Bytes> entry : oldData.entrySet()) { RowColumn rc = entry.getKey(); if (!newData.containsKey(rc)) { Mutation m = mutationMap.computeIfAbsent(rc.getRow(), r -> new Mutation(r.toArray())); m.putDelete(rc.getColumn().getFamily().toArray(), rc.getColumn().getQualifier().toArray(), seq); } } for (Map.Entry<RowColumn, Bytes> entry : newData.entrySet()) { RowColumn rc = entry.getKey(); Column col = rc.getColumn(); Bytes newVal = entry.getValue(); Bytes oldVal = oldData.get(rc); if (oldVal == null || !oldVal.equals(newVal)) { Mutation m = mutationMap.computeIfAbsent(rc.getRow(), r -> new Mutation(r.toArray())); m.put(col.getFamily().toArray(), col.getQualifier().toArray(), seq, newVal.toArray()); } } return mutationMap.values(); }
Source:
public abstract void start() throws RunnerException ; public abstract void stop() throws RunnerException ; public void getLogs(Appendable output) throws IOException, RunnerException { final String url = bindAddress + ':' + port + "/log/_app"; final String logContent = sendGet(new URL(url.startsWith("http://") ? url : "http://" + url)); output.append(String.format("%n====> GWT-code-server.log <====")); output.append(logContent); output.append(System.lineSeparator()); }

Target:
public abstract void start() throws RunnerException ; public abstract void stop() throws RunnerException ; public void appendLogs(Appendable output) throws IOException, RunnerException { final String url = bindAddress + ':' + port + "/log/_app"; final String logContent = sendGet(new URL(url.startsWith("http://") ? url : "http://" + url)); output.append(String.format("%n====> GWT-code-server.log <====")); output.append(logContent); output.append(System.lineSeparator()); }
Source:
public Expression add(String field,JsonNode value) { ((ObjectNode)node).set(field,value); return this; }

Target:
public Expression add(String field,JsonNode value) { try { ((ObjectNode)node).set(field,value); return this; } catch (ClassCastException e) { throw new RuntimeException("Object node expected while adding "+field); } }
Source:
ProducerSustainedConnection() { this.producer = null; this.partitions = null; this.topicName = SustainedConnectionWorker.this.spec.topicName(); this.partitionsIterator = null; this.keys = new PayloadIterator(SustainedConnectionWorker.this.spec.keyGenerator()); this.values = new PayloadIterator(SustainedConnectionWorker.this.spec.valueGenerator()); this.refreshRate = SustainedConnectionWorker.this.spec.refreshRateMs(); this.props = new Properties(); this.props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, SustainedConnectionWorker.this.spec.bootstrapServers()); this.props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 1); WorkerUtils.addConfigsToProperties( this.props, SustainedConnectionWorker.this.spec.commonClientConf(), SustainedConnectionWorker.this.spec.producerConf()); }

Target:
ProducerSustainedConnection() { this.producer = null; this.partitions = null; this.topicName = SustainedConnectionWorker.this.spec.topicName(); this.partitionsIterator = null; this.keys = new PayloadIterator(SustainedConnectionWorker.this.spec.keyGenerator()); this.values = new PayloadIterator(SustainedConnectionWorker.this.spec.valueGenerator()); this.refreshRate = SustainedConnectionWorker.this.spec.refreshRateMs(); this.props = new Properties(); this.props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, SustainedConnectionWorker.this.spec.bootstrapServers()); WorkerUtils.addConfigsToProperties( this.props, SustainedConnectionWorker.this.spec.commonClientConf(), SustainedConnectionWorker.this.spec.producerConf()); }
Source:
public TypeSerializerSnapshot<Tuple2<byte[], StreamRecord<IN>>> snapshotConfiguration() { return null; }

Target:
public TypeSerializerSnapshot<Tuple2<byte[], StreamRecord<IN>>> snapshotConfiguration() { throw new UnsupportedOperationException( "The KeyAndValueSerializer should not be used for persisting into State!"); }
Source:
private void writeSnapshot(long sid, XmlComponentConfigurations conf) throws KuraException { File fSnapshot = getSnapshotFile(sid); if (fSnapshot == null) { throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR); } String xmlResult; try { xmlResult = XmlUtil.marshal(conf); if (xmlResult.trim().isEmpty()) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER, conf); } } catch (Exception e1) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e1); } char[] encryptedXML = this.m_cryptoService.encryptAes(xmlResult.toCharArray()); FileOutputStream fos = null; OutputStreamWriter osw = null; try { s_logger.info("Writing snapshot - Saving {}...", fSnapshot.getAbsolutePath()); fos = new FileOutputStream(fSnapshot); osw = new OutputStreamWriter(fos, "UTF-8"); osw.append(new String(encryptedXML)); osw.flush(); fos.flush(); fos.getFD().sync(); s_logger.info("Writing snapshot - Saving {}... Done.", fSnapshot.getAbsolutePath()); } catch (FileNotFoundException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } catch (UnsupportedEncodingException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } catch (IOException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } finally { if (osw != null) { try { osw.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }

Target:
private void writeSnapshot(long sid, XmlComponentConfigurations conf) throws KuraException { File fSnapshot = getSnapshotFile(sid); if (fSnapshot == null) { throw new KuraException(KuraErrorCode.CONFIGURATION_SNAPSHOT_NOT_FOUND); } String xmlResult; try { xmlResult = XmlUtil.marshal(conf); if (xmlResult.trim().isEmpty()) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER, conf); } } catch (Exception e1) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e1); } char[] encryptedXML = this.cryptoService.encryptAes(xmlResult.toCharArray()); FileOutputStream fos = null; OutputStreamWriter osw = null; try { logger.info("Writing snapshot - Saving {}...", fSnapshot.getAbsolutePath()); fos = new FileOutputStream(fSnapshot); osw = new OutputStreamWriter(fos, "UTF-8"); osw.append(new String(encryptedXML)); osw.flush(); fos.flush(); fos.getFD().sync(); logger.info("Writing snapshot - Saving {}... Done.", fSnapshot.getAbsolutePath()); } catch (FileNotFoundException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } catch (UnsupportedEncodingException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } catch (IOException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } finally { if (osw != null) { try { osw.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }
Source:
public JavaRDD<StructuredRecord> transform(SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input) throws Exception { if (input.isEmpty()) { return context.getSparkContext().emptyRDD(); } outputSchema = outputSchema != null ? outputSchema : config.getOutputSchema(input.first().getSchema()); final Map<String, String> mapping = config.getFeatureListMapping(); final int vectorSize = loadedModel.wordVectors().length / loadedModel.wordIndex().size(); return input.map(new Function<StructuredRecord, StructuredRecord>() { @Override public StructuredRecord call(StructuredRecord input) throws Exception { StructuredRecord.Builder builder = StructuredRecord.builder(outputSchema); for (Schema.Field field : input.getSchema().getFields()) { String fieldName = field.getName(); builder.set(fieldName, input.get(fieldName)); } for (Map.Entry<String, String> mapEntry : mapping.entrySet()) { String inputField = mapEntry.getKey(); String outputField = mapEntry.getValue(); List<String> text = SparkUtils.getInputFieldValue(input, inputField, config.pattern); int numWords = 0; double[] vectorValues = new double[vectorSize]; for (String word : text) { double[] wordVector = loadedModel.transform(word).toArray(); for (int i = 0; i < vectorSize; i++) { vectorValues[i] += wordVector[i]; } numWords++; } for (int i = 0; i < vectorSize; i++) { vectorValues[i] /= (double) numWords; } builder.set(outputField, new ArrayList<>(Arrays.asList(ArrayUtils.toObject(vectorValues)))); } return builder.build(); } }); }

Target:
public JavaRDD<StructuredRecord> transform(SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input) throws Exception { if (input.isEmpty()) { return context.getSparkContext().emptyRDD(); } outputSchema = outputSchema != null ? outputSchema : config.getOutputSchema(input.first().getSchema()); final Map<String, String> mapping = config.getFeatureListMapping(config.outputColumnMapping); final int vectorSize = loadedModel.wordVectors().length / loadedModel.wordIndex().size(); return input.map(new Function<StructuredRecord, StructuredRecord>() { @Override public StructuredRecord call(StructuredRecord input) throws Exception { splitter = splitter == null ? Splitter.on(pattern) : splitter; StructuredRecord.Builder builder = StructuredRecord.builder(outputSchema); for (Schema.Field field : input.getSchema().getFields()) { String fieldName = field.getName(); builder.set(fieldName, input.get(fieldName)); } for (Map.Entry<String, String> mapEntry : mapping.entrySet()) { String inputField = mapEntry.getKey(); String outputField = mapEntry.getValue(); List<String> text = SparkUtils.getInputFieldValue(input, inputField, splitter); int numWords = 0; double[] vectorValues = new double[vectorSize]; for (String word : text) { double[] wordVector = loadedModel.transform(word).toArray(); for (int i = 0; i < vectorSize; i++) { vectorValues[i] += wordVector[i]; } numWords++; } for (int i = 0; i < vectorSize; i++) { vectorValues[i] /= (double) numWords; } builder.set(outputField, vectorValues); } return builder.build(); } }); }
Source:
protected void updateRAfterInstantiation(int binIdx, int itemIdx) throws ContradictionException { if(!R[binIdx].contains(itemIdx)) { R[binIdx].add(itemIdx); sumR[binIdx].add(itemSize[itemIdx]); binLoad[binIdx].updateLowerBound(sumR[binIdx].get(), this); binsToProcess.set(binIdx); for(int k = 0; k<nbAvailableBins; k++) { if(k != binIdx && P[k].contains(itemIdx)) { P[k].remove(itemIdx); sumP[k].add(-itemSize[itemIdx]); binLoad[k].updateUpperBound(sumP[k].get(), this); binsToProcess.set(k); } } } }

Target:
protected void updateRAfterInstantiation(int binIdx, int itemIdx) throws ContradictionException { if(R[binIdx].add(itemIdx)) { binLoad[binIdx].updateLowerBound(sumR[binIdx].add(itemSize[itemIdx]), this); binsToProcess.set(binIdx); for(int k = 0; k<nbAvailableBins; k++) { if(k != binIdx && P[k].remove(itemIdx)) { binLoad[k].updateUpperBound(sumP[k].add(-itemSize[itemIdx]), this); binsToProcess.set(k); } } } }
Source:
public void undeleteTrash() throws ProviderImplementationException { for (Map.Entry<String, Storage> entry : getConfiguration().getStorages().entrySet()) { Storage storage = entry.getValue(); final Map<String, ? extends Repository> repositories = storage.getRepositories(); for (Repository repository : repositories.values()) { if (repository.isTrashEnabled()) { RootRepositoryPath repositoryPath = repositoryPathResolver.resolve(repository); ThrowingConsumer.unchecked(RepositoryFiles::undelete).accept(repositoryPath); } } } RepositoryEvent event = new RepositoryEvent(null, null, RepositoryEventTypeEnum.EVENT_REPOSITORY_UNDELETE_TRASH_FOR_ALL_REPOSITORIES .getType()); repositoryEventListenerRegistry.dispatchEvent(event); }

Target:
public void undeleteTrash() throws IOException { for (Map.Entry<String, Storage> entry : getConfiguration().getStorages().entrySet()) { Storage storage = entry.getValue(); final Map<String, ? extends Repository> repositories = storage.getRepositories(); for (Repository repository : repositories.values()) { final String storageId = storage.getId(); final String repositoryId = repository.getId(); try { if (repository.isTrashEnabled()) { RootRepositoryPath repositoryPath = repositoryPathResolver.resolve(repository); RepositoryFiles.undelete(repositoryPath); } } catch (IOException e) { throw new ArtifactStorageException( "Unable to undelete trash for storage " + storageId + " in repository " + repositoryId, e); } } } RepositoryEvent event = new RepositoryEvent(null, null, RepositoryEventTypeEnum.EVENT_REPOSITORY_UNDELETE_TRASH_FOR_ALL_REPOSITORIES .getType()); repositoryEventListenerRegistry.dispatchEvent(event); }
Source:
static public void runAsTask(Long surveyId) { log.info("Forking to task for long assembly"); com.google.appengine.api.taskqueue.TaskOptions options = com.google.appengine.api.taskqueue.TaskOptions.Builder .withUrl("/app_worker/surveyassembly") .param(SurveyAssemblyRequest.ACTION_PARAM, SurveyAssemblyRequest.ASSEMBLE_SURVEY) .param(SurveyAssemblyRequest.IS_FWD_PARAM, "true") .param(SurveyAssemblyRequest.SURVEY_ID_PARAM, surveyId.toString()); com.google.appengine.api.taskqueue.Queue queue = QueueFactory.getQueue("surveyAssembly"); queue.add(options); }

Target:
static public void runAsTask(Long surveyId) { log.info("Forking to task for long assembly"); TaskOptions options = TaskOptions.Builder .withUrl("/app_worker/surveyassembly") .param(SurveyAssemblyRequest.ACTION_PARAM, SurveyAssemblyRequest.ASSEMBLE_SURVEY) .param(SurveyAssemblyRequest.SURVEY_ID_PARAM, surveyId.toString()); Queue queue = QueueFactory.getQueue("surveyAssembly"); queue.add(options); Survey s = new SurveyDAO().getById(surveyId); SurveyGroup sg = s != null ? new SurveyGroupDAO().getByKey(s.getSurveyGroupId()) : null; if (sg != null && sg.getNewLocaleSurveyId() != null && sg.getNewLocaleSurveyId().longValue() == surveyId.longValue()) { DataProcessorRestServlet.scheduleDatapointNameAssembly(sg.getKey().getId(), null); } }
Source:
public Set<? extends AbstractBean<?, ?>> apply(Bean<?> specializingBean) { Set<? extends AbstractBean<?, ?>> result = null; if (specializingBean instanceof AbstractClassBean<?>) { result = apply((AbstractClassBean<?>) specializingBean); } if (specializingBean instanceof ProducerMethod<?, ?>) { result = apply((ProducerMethod<?, ?>) specializingBean); } if (result != null) { if (isEnabledInAnyBeanDeployment(specializingBean)) { for (AbstractBean<?, ?> specializedBean : result) { if (specializedBeansMap.get(specializedBean) == null) { specializedBeansMap.put(specializedBean, new AtomicLong(1)); } else { specializedBeansMap.put(specializedBean, new AtomicLong(specializedBeansMap.get(specializedBean).get() + 1)); } } } return result; } throw new IllegalArgumentException("Unsupported bean type " + specializingBean); }

Target:
public Set<? extends AbstractBean<?, ?>> apply(Bean<?> specializingBean) { Set<? extends AbstractBean<?, ?>> result = null; if (specializingBean instanceof AbstractClassBean<?>) { result = apply((AbstractClassBean<?>) specializingBean); } if (specializingBean instanceof ProducerMethod<?, ?>) { result = apply((ProducerMethod<?, ?>) specializingBean); } if (result != null) { if (isEnabledInAnyBeanDeployment(specializingBean)) { for (AbstractBean<?, ?> specializedBean : result) { AtomicLong value = specializedBeansMap.get(specializedBean); if (value == null) { value = new AtomicLong(0); AtomicLong previous = specializedBeansMap.putIfAbsent(specializedBean, value); if (previous != null) { value = previous; } } value.incrementAndGet(); } } return result; } throw new IllegalArgumentException("Unsupported bean type " + specializingBean); }
Source:
public void activate(Context context) { try { if (clazz != null) { setters = new ArrayList<>(); List<String> fieldNames = schema.getFieldNames(); if (fieldNames != null) { for (String fieldName : fieldNames) { addSetter(fieldName); } } } } catch (Exception e) { logger.error("Cannot activate Parser Reason {}", e.getMessage()); } }

Target:
public void activate(Context context) { try { if (clazz != null) { setters = new ArrayList<>(); List<String> fieldNames = schema.getFieldNames(); if (fieldNames != null) { for (String fieldName : fieldNames) { addSetter(fieldName); } } } } catch (Exception e) { logger.error("Cannot activate Parser Reason {}", e.getMessage()); throw e; } }
Source:
default CompletionStage<Void> commit(Transaction transaction) { throw new UnsupportedOperationException("Store characteristic included " + Characteristic.TRANSACTIONAL + ", but it does not implement rollback"); }

Target:
default CompletionStage<Void> commit(Transaction transaction) { throw new UnsupportedOperationException("Store characteristic included " + Characteristic.TRANSACTIONAL + ", but it does not implement commit"); }
Source:
public void addOnSubscriptionsChangedListener(OnSubscriptionsChangedListener listener) { if (listener == null) return; String pkgName = mContext != null ? mContext.getOpPackageName() : "<unknown>"; if (DBG) { logd("register OnSubscriptionsChangedListener pkgName=" + pkgName + " listener=" + listener); } TelephonyRegistryManager telephonyRegistryManager = (TelephonyRegistryManager) mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE); if (telephonyRegistryManager != null) { telephonyRegistryManager.addOnSubscriptionsChangedListener(listener, listener.mExecutor); } }

Target:
public void addOnSubscriptionsChangedListener(OnSubscriptionsChangedListener listener) { if (listener == null) return; addOnSubscriptionsChangedListener(listener, listener.mExecutor); }
Source:
private boolean refreshTt() throws IOException { log.debug("Obtaining TT"); final HttpGet getTT = new HttpGet(TOKEN_URL); getTT.addHeader(SST_HEADER, sst); try { final HttpResponse response = httpClient.execute(authHost, getTT, (HttpContext) null); final int status = response.getStatusLine().getStatusCode(); switch (status) { case HttpStatus.SC_OK: tt = TokenUtils.extractTT(response); return true; case HttpStatus.SC_UNAUTHORIZED: return false; default: throw new GoodDataAuthException("Unable to obtain TT, HTTP status: " + status); } } finally { getTT.releaseConnection(); } }

Target:
private boolean refreshTt() throws IOException { log.debug("Obtaining TT"); final HttpGet request = new HttpGet(TOKEN_URL); try { request.setHeader(HttpHeaders.ACCEPT, YAML_CONTENT_TYPE); request.setHeader(SST_HEADER, sst); final HttpResponse response = httpClient.execute(authHost, request, (HttpContext) null); final int status = response.getStatusLine().getStatusCode(); switch (status) { case HttpStatus.SC_OK: tt = TokenUtils.extractToken(response); return true; case HttpStatus.SC_UNAUTHORIZED: return false; default: throw new GoodDataAuthException("Unable to obtain TT, HTTP status: " + status); } } finally { request.releaseConnection(); } }
Source:
public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort, Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds, SecurityGroup group) { String zone = group.getLocation().getId(); String id = group.getId(); Optional<? extends SecurityGroupApi> sgApi = client.getSecurityGroupExtensionForZone(zone); if (!sgApi.isPresent()) { return null; } org.jclouds.openstack.nova.v2_0.domain.SecurityGroup securityGroup = sgApi.get().get(id); if (Iterables.size(ipRanges) > 0) { for (String cidr : ipRanges) { for (SecurityGroupRule rule : filter(securityGroup.getRules(), and(ruleCidr(cidr), ruleProtocol(protocol), ruleStartPort(startPort), ruleEndPort(endPort)))) { sgApi.get().deleteRule(rule.getId()); } } } if (Iterables.size(groupIds) > 0) { for (String groupId : groupIds) { for (SecurityGroupRule rule : filter(securityGroup.getRules(), and(ruleGroup(groupId), ruleProtocol(protocol), ruleStartPort(startPort), ruleEndPort(endPort)))) { sgApi.get().deleteRule(rule.getId()); } } } return getSecurityGroupById(ZoneAndId.fromZoneAndId(zone, id).slashEncode()); }

Target:
public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort, Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds, SecurityGroup group) { String zone = group.getLocation().getId(); String id = group.getId(); Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupExtensionForZone(zone); if (!sgApi.isPresent()) { return null; } org.jclouds.openstack.nova.v2_0.domain.SecurityGroup securityGroup = sgApi.get().get(id); if (Iterables.size(ipRanges) > 0) { for (String cidr : ipRanges) { for (SecurityGroupRule rule : filter(securityGroup.getRules(), and(ruleCidr(cidr), ruleProtocol(protocol), ruleStartPort(startPort), ruleEndPort(endPort)))) { sgApi.get().deleteRule(rule.getId()); } } } if (Iterables.size(groupIds) > 0) { for (String groupId : groupIds) { for (SecurityGroupRule rule : filter(securityGroup.getRules(), and(ruleGroup(groupId), ruleProtocol(protocol), ruleStartPort(startPort), ruleEndPort(endPort)))) { sgApi.get().deleteRule(rule.getId()); } } } return getSecurityGroupById(ZoneAndId.fromZoneAndId(zone, id).slashEncode()); }
Source:
public void deleteAll(long inodeId) throws StorageException { final String query = String.format("DELETE FROM %s WHERE %s=%d", TablesDef.BlockChecksumTableDef.TABLE_NAME, TablesDef.BlockChecksumTableDef.INODE_ID, inodeId); PreparedStatement s = null; try { Connection conn = mysqlConnector.obtainSession(); s = conn.prepareStatement(query); s.executeUpdate(); } catch (SQLException ex) { throw HopsSQLExceptionHelper.wrap(ex); } finally { if (s != null) { try { s.close(); } catch (SQLException ex) { } } mysqlConnector.closeSession(); } }

Target:
public void deleteAll(long inodeId) throws StorageException { final String query = String.format("DELETE FROM %s WHERE %s=%d", TablesDef.BlockChecksumTableDef.TABLE_NAME, TablesDef.BlockChecksumTableDef.INODE_ID, inodeId); PreparedStatement s = null; try { Connection conn = mysqlConnector.obtainSession(); s = conn.prepareStatement(query); s.executeUpdate(); } catch (SQLException ex) { throw HopsSQLExceptionHelper.wrap(ex); } finally { if (s != null) { try { s.close(); } catch (SQLException ex) { LOG.warn("Exception when closing the PrepareStatement", ex); } } mysqlConnector.closeSession(); } }