auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Map<String, Person> getCurrentProgramMembers() { String cropname = this.contextUtil.getProjectInContext().getCropType().getCropName(); final Map<String, Person> currentProgramMembers = new HashMap<>(); final Long projectId = this.workbenchDataManager.getProjectByUuidAndCrop(this.getCurrentProgramID(), cropname).getProjectId(); final Map<Integer, Person> programMembers = new HashMap<>(); for (final Map.Entry<Integer, Person> member : programMembers.entrySet()) { currentProgramMembers.put(String.valueOf(member.getKey()), member.getValue()); } return currentProgramMembers; }

Target:
public Map<String, Person> getCurrentProgramMembers() { String cropname = this.contextUtil.getProjectInContext().getCropType().getCropName(); final Map<String, Person> currentProgramMembers = new HashMap<>(); final Long projectId = this.workbenchDataManager.getProjectByUuidAndCrop(this.getCurrentProgramID(), cropname).getProjectId(); final Map<Integer, Person> programMembers = this.workbenchDataManager.getPersonsByProjectId(projectId); for (final Map.Entry<Integer, Person> member : programMembers.entrySet()) { currentProgramMembers.put(String.valueOf(member.getKey()), member.getValue()); } return currentProgramMembers; }
Source:
public double calculateNonRefGenotypeConcordance(final GenotypeConcordanceScheme scheme, final boolean missingSitesFlag) { double numerator = 0.0; double denominator = 0.0; scheme.validateScheme(); final TruthState[] allTruthStates = TruthState.values(); final CallState[] allCallStates = CallState.values(); for (final TruthState truthState : allTruthStates) { for (final CallState callState : allCallStates) { if(!missingSitesFlag && isMissing(truthState, callState)) { continue; } else if (isVar(truthState, callState)) { final TruthAndCallStates truthAndCallStates = new TruthAndCallStates(truthState, callState); final int count = getCount(truthAndCallStates); if (truthState.getCode()==callState.getCode()) { numerator += count; denominator += count; } else { denominator += count; } } } } return (numerator / denominator); }

Target:
public double calculateNonRefGenotypeConcordance(final GenotypeConcordanceScheme scheme, final boolean missingSitesFlag) { return calculateGenotypeConcordanceUtil(scheme, missingSitesFlag, false); }
Source:
ZkJobCoordinator(Config config, MetricsRegistry metricsRegistry, ZkUtils zkUtils) { this.config = config; this.metrics = new ZkJobCoordinatorMetrics(metricsRegistry); this.processorId = createProcessorId(config); this.zkUtils = zkUtils; LeaderElector leaderElector = new ZkLeaderElector(processorId, zkUtils); leaderElector.setLeaderElectorListener(new LeaderElectorListenerImpl()); this.zkController = new ZkControllerImpl(processorId, zkUtils, this, leaderElector); this.barrier = new ZkBarrierForVersionUpgrade( zkUtils.getKeyBuilder().getJobModelVersionBarrierPrefix(), zkUtils, new ZkBarrierListenerImpl()); this.debounceTimeMs = new JobConfig(config).getDebounceTimeMs(); this.reporters = MetricsReporterLoader.getMetricsReporters(new MetricsConfig(config), processorId); debounceTimer = new ScheduleAfterDebounceTime(throwable -> { LOG.error("Received exception from in JobCoordinator Processing!", throwable); stop(); }); }

Target:
ZkJobCoordinator(Config config, MetricsRegistry metricsRegistry, ZkUtils zkUtils) { this.config = config; this.metrics = new ZkJobCoordinatorMetrics(metricsRegistry); this.processorId = createProcessorId(config); this.zkUtils = zkUtils; zkUtils.getZkClient().subscribeStateChanges(new ZkSessionStateChangedListener()); LeaderElector leaderElector = new ZkLeaderElector(processorId, zkUtils); leaderElector.setLeaderElectorListener(new LeaderElectorListenerImpl()); this.zkController = new ZkControllerImpl(processorId, zkUtils, this, leaderElector); this.barrier = new ZkBarrierForVersionUpgrade( zkUtils.getKeyBuilder().getJobModelVersionBarrierPrefix(), zkUtils, new ZkBarrierListenerImpl()); this.debounceTimeMs = new JobConfig(config).getDebounceTimeMs(); this.reporters = MetricsReporterLoader.getMetricsReporters(new MetricsConfig(config), processorId); debounceTimer = new ScheduleAfterDebounceTime(throwable -> { LOG.error("Received exception from in JobCoordinator Processing!", throwable); stop(); }); }
Source:
private void loadOMClientConfigs(Configuration config, String omSvcId) throws IOException { this.omProxies = new HashMap<>(); this.omProxyInfos = new HashMap<>(); this.omNodeIDList = new ArrayList<>(); Collection<String> omServiceIds; if (omSvcId == null) { omServiceIds = new ArrayList<>(); } else { omServiceIds = Collections.singletonList(omSvcId); } if (omServiceIds.size() > 1) { throw new IllegalArgumentException("Multi-OM Services is not supported." + " Please configure only one OM Service ID in " + OZONE_OM_SERVICE_IDS_KEY); } for (String serviceId : OmUtils.emptyAsSingletonNull(omServiceIds)) { Collection<String> omNodeIds = OmUtils.getOMNodeIds(config, serviceId); for (String nodeId : OmUtils.emptyAsSingletonNull(omNodeIds)) { String rpcAddrKey = OmUtils.addKeySuffixes(OZONE_OM_ADDRESS_KEY, serviceId, nodeId); String rpcAddrStr = OmUtils.getOmRpcAddress(config, rpcAddrKey); if (rpcAddrStr == null) { continue; } OMProxyInfo omProxyInfo = new OMProxyInfo(nodeId, rpcAddrStr); if (omProxyInfo.getAddress() != null) { ProxyInfo<OzoneManagerProtocolPB> proxyInfo = new ProxyInfo(null, omProxyInfo.toString()); if (nodeId == null) { nodeId = OzoneConsts.OM_NODE_ID_DUMMY; } omProxies.put(nodeId, proxyInfo); omProxyInfos.put(nodeId, omProxyInfo); omNodeIDList.add(nodeId); } else { LOG.error("Failed to create OM proxy for at address {}", nodeId, rpcAddrStr); } } } if (omProxies.isEmpty()) { throw new IllegalArgumentException("Could not find any configured " + "addresses for OM. Please configure the system with " + OZONE_OM_ADDRESS_KEY); } }

Target:
private void loadOMClientConfigs(Configuration config, String omSvcId) throws IOException { this.omProxies = new HashMap<>(); this.omProxyInfos = new HashMap<>(); this.omNodeIDList = new ArrayList<>(); Collection<String> omServiceIds = Collections.singletonList(omSvcId); for (String serviceId : OmUtils.emptyAsSingletonNull(omServiceIds)) { Collection<String> omNodeIds = OmUtils.getOMNodeIds(config, serviceId); for (String nodeId : OmUtils.emptyAsSingletonNull(omNodeIds)) { String rpcAddrKey = OmUtils.addKeySuffixes(OZONE_OM_ADDRESS_KEY, serviceId, nodeId); String rpcAddrStr = OmUtils.getOmRpcAddress(config, rpcAddrKey); if (rpcAddrStr == null) { continue; } OMProxyInfo omProxyInfo = new OMProxyInfo(nodeId, rpcAddrStr); if (omProxyInfo.getAddress() != null) { ProxyInfo<OzoneManagerProtocolPB> proxyInfo = new ProxyInfo(null, omProxyInfo.toString()); if (nodeId == null) { nodeId = OzoneConsts.OM_NODE_ID_DUMMY; } omProxies.put(nodeId, proxyInfo); omProxyInfos.put(nodeId, omProxyInfo); omNodeIDList.add(nodeId); } else { LOG.error("Failed to create OM proxy for at address {}", nodeId, rpcAddrStr); } } } if (omProxies.isEmpty()) { throw new IllegalArgumentException("Could not find any configured " + "addresses for OM. Please configure the system with " + OZONE_OM_ADDRESS_KEY); } }
Source:
public ResponseEntity<String> remove(@PathVariable("name") String documentName) { try { if (doesBucketContainObject(this.bucketName, documentName)) { DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(this.bucketName, documentName); s3Client.deleteObject(deleteObjectRequest); log.info("Delete " + documentName + " from S3 bucket " + this.bucketName + ": done"); } return new ResponseEntity<String>(HttpStatus.OK); } catch (Exception e) { log.error(e.getMessage(), e); return new ResponseEntity<String>(HttpStatus.NOT_FOUND); } }

Target:
public ResponseEntity<String> remove(@PathVariable("name") String documentName) throws SdkClientException, AmazonServiceException { if (s3Client.doesObjectExist(this.bucketName, documentName)) { DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(this.bucketName, documentName); s3Client.deleteObject(deleteObjectRequest); log.info("Delete " + documentName + " from S3 bucket " + this.bucketName + ": done"); return new ResponseEntity<String>(HttpStatus.NO_CONTENT); } else { return new ResponseEntity<String>(HttpStatus.NOT_FOUND); } }
Source:
public BookieNode selectFromNetworkLocation( String networkLoc, Set<Node> excludeBookies, Predicate<BookieNode> predicate, Ensemble<BookieNode> ensemble) throws BKNotEnoughBookiesException { try { return selectRandomFromRack(networkLoc, excludeBookies, predicate, ensemble); } catch (BKNotEnoughBookiesException e) { LOG.warn("Failed to choose a bookie from : " + "excluded {}, fallback to choose bookie randomly from the cluster.", networkLoc, excludeBookies); LOG.warn("Predicate Ensemble {}", predicate, ensemble); return selectRandom(1, excludeBookies, predicate, ensemble).get(0); } }

Target:
public BookieNode selectFromNetworkLocation( String networkLoc, Set<Node> excludeBookies, Predicate<BookieNode> predicate, Ensemble<BookieNode> ensemble) throws BKNotEnoughBookiesException { try { return selectRandomFromRack(networkLoc, excludeBookies, predicate, ensemble); } catch (BKNotEnoughBookiesException e) { LOG.warn("Failed to choose a bookie from : " + "excluded {}, fallback to choose bookie randomly from the cluster.", networkLoc, excludeBookies); return selectRandom(1, excludeBookies, predicate, ensemble).get(0); } }
Source:
public static void sendNotification(Context c, String text, Drawable icon) { NotificationManager notificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager == null) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) notificationManager.createNotificationChannel(new NotificationChannel(TEST_RUN, c.getString(R.string.Settings_Notifications_OnTestCompletion), NotificationManager.IMPORTANCE_DEFAULT)); NotificationCompat.Builder b = new NotificationCompat.Builder(c, TEST_RUN); b.setAutoCancel(true); b.setDefaults(Notification.DEFAULT_ALL); Bitmap bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); icon.draw(canvas); b.setLargeIcon(bitmap); b.setSmallIcon(R.drawable.notification_icon); b.setContentTitle(c.getString(R.string.General_AppName)); b.setContentText(text); b.setContentIntent(PendingIntent.getActivity(c, 0, MainActivity.newIntent(c, R.id.testResults), PendingIntent.FLAG_UPDATE_CURRENT)); notificationManager.notify(1, b.build()); }

Target:
public static void sendNotification(Context c, String text, Drawable icon) { NotificationManager notificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager == null) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationManager.createNotificationChannel( new NotificationChannel(TEST_RUN, c.getString(R.string.Settings_Notifications_OnTestCompletion), NotificationManager.IMPORTANCE_DEFAULT) ); } NotificationCompat.Builder b = new NotificationCompat.Builder(c, TEST_RUN); b.setAutoCancel(true); b.setDefaults(Notification.DEFAULT_ALL); Bitmap bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); icon.draw(canvas); b.setLargeIcon(bitmap); b.setSmallIcon(R.drawable.notification_icon); b.setContentTitle(c.getString(R.string.General_AppName)); b.setContentText(text); b.setContentIntent(PendingIntent.getActivity(c, 0, MainActivity.newIntent(c, R.id.testResults), PendingIntent.FLAG_UPDATE_CURRENT)); notificationManager.notify(1, b.build()); }
Source:
public void onCreate() { super.onCreate(); ACRA.init(this); if (BuildConfig.APPLICATION_ID.contains("beta")) { releaseType = RELEASE_BETA; } else if (BuildConfig.APPLICATION_ID.contains("alpha")) { releaseType = RELEASE_ALPHA; } bus = new Bus(); final Resources resources = getResources(); ViewAnimations.init(resources); screenDensity = resources.getDisplayMetrics().density; this.prefs = PreferenceManager.getDefaultSharedPreferences(this); PrefKeys.initPreferenceKeys(resources); sessionFunnel = new SessionFunnel(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } Api.setConnectionFactory(new OkHttpConnectionFactory(this)); appVersionString = BuildConfig.VERSION_NAME; zeroHandler = new WikipediaZeroHandler(this); pageCache = new PageCache(); new PerformMigrationsTask().execute(); }

Target:
public void onCreate() { super.onCreate(); ACRA.init(this); if (BuildConfig.APPLICATION_ID.contains("beta")) { releaseType = RELEASE_BETA; } else if (BuildConfig.APPLICATION_ID.contains("alpha")) { releaseType = RELEASE_ALPHA; } bus = new Bus(); final Resources resources = getResources(); ViewAnimations.init(resources); screenDensity = resources.getDisplayMetrics().density; this.prefs = PreferenceManager.getDefaultSharedPreferences(this); PrefKeys.initPreferenceKeys(resources); sessionFunnel = new SessionFunnel(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } Api.setConnectionFactory(new OkHttpConnectionFactory(this)); zeroHandler = new WikipediaZeroHandler(this); pageCache = new PageCache(); new PerformMigrationsTask().execute(); }
Source:
public void setCustomProperties(final Map<String, Object> customProperties) { this.customProperties = customProperties; }

Target:
public void setCustomProperties(final Map<String, Object> customProperties) { CommonHelper.assertNotNull("customProperties", customProperties); this.customProperties = customProperties; }
Source:
public Collection<Consumer> findByUuids(Collection<String> uuids) { Set<Consumer> consumers = new HashSet<>(); for (List<String> block : this.partition(uuids)) { Criteria criteria = this.createSecureCriteria() .add(Restrictions.in("uuid", uuids)); consumers.addAll(criteria.list()); } return consumers; }

Target:
public Collection<Consumer> findByUuids(Collection<String> uuids) { Set<Consumer> consumers = new HashSet<>(); for (List<String> block : this.partition(uuids)) { Criteria criteria = this.createSecureCriteria() .add(Restrictions.in("uuid", block)); consumers.addAll(criteria.list()); } return consumers; }
Source:
public static <T> T setClassField( Class<T> type, final T obj, final String fieldName, Object fieldObject) throws Exception { java.lang.reflect.Field field = type.getDeclaredField(fieldName); field.setAccessible(true); java.lang.reflect.Field modifiersField = java.lang.reflect.Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~java.lang.reflect.Modifier.FINAL); field.set(obj, fieldObject); return obj; }

Target:
public static <T> T setClassField( Class<T> type, final T obj, final String fieldName, Object fieldObject) throws Exception { Field field = type.getDeclaredField(fieldName); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(obj, fieldObject); return obj; }
Source:
private void updateEntryToStoreInDb(Externalizable extObj, boolean objectInDb, String filename, ByteArrayOutputStream bos, SQLiteDatabase db, int id) { ContentValues updatedContentValues = helper.getContentValuesWithCustomData(extObj, bos.toByteArray()); if (!objectInDb) { updatedContentValues.put(DatabaseHelper.FILE_COL, (String)null); updatedContentValues.put(DatabaseHelper.AES_COL, (byte[])null); File dataFile = new File(filename); dataFile.delete(); } db.update(table, updatedContentValues, DatabaseHelper.ID_COL + "=?", new String[]{String.valueOf(id)}); }

Target:
private void updateEntryToStoreInDb(Externalizable extObj, boolean objectInDb, String filename, ByteArrayOutputStream bos, SQLiteDatabase db, int id) { ContentValues updatedContentValues = helper.getContentValuesWithCustomData(extObj, bos.toByteArray()); if (!objectInDb) { updatedContentValues.put(DatabaseHelper.FILE_COL, (String)null); updatedContentValues.put(DatabaseHelper.AES_COL, (byte[])null); HybridFileBackedSqlHelpers.setFileAsOrphan(db, filename); } db.update(table, updatedContentValues, DatabaseHelper.ID_COL + "=?", new String[]{String.valueOf(id)}); }
Source:
@Override public RelRoot expandView(RelDataType rowType, String queryString, List<String> schemaPath, List<String> viewPath) { if (planner == null) { ready(); } SqlParser parser = SqlParser.create(queryString, parserConfig); SqlNode sqlNode; try { sqlNode = parser.parseQuery(); } catch (SqlParseException e) { throw new RuntimeException("parse failed", e); } final SqlConformance conformance = conformance(); final CalciteCatalogReader catalogReader = createCatalogReader().withSchemaPath(schemaPath); final SqlOperatorTable opTab = ChainedSqlOperatorTable.of(operatorTable, catalogReader); final SqlValidator validator = new CalciteSqlValidator(opTab, catalogReader, typeFactory, conformance); validator.setIdentifierExpansion(true); final RexBuilder rexBuilder = createRexBuilder(); final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder); final SqlToRelConverter.Config config = SqlToRelConverter .configBuilder() .withConfig(sqlToRelConverterConfig) .withTrimUnusedFields(false) .withConvertTableAccess(false) .build(); final SqlToRelConverter sqlToRelConverter = new SqlToRelConverter(this, validator, catalogReader, cluster, convertletTable, config); final RelRoot root = sqlToRelConverter.convertQuery(sqlNode, true, false); final RelRoot root2 = root.withRel(sqlToRelConverter.flattenTypes(root.rel, true)); final RelBuilder relBuilder = config.getRelBuilderFactory().create(cluster, null); return root2.withRel( RelDecorrelator.decorrelateQuery(root.rel, relBuilder)); }

Target:
@Override public RelRoot expandView(RelDataType rowType, String queryString, List<String> schemaPath, List<String> viewPath) { if (planner == null) { ready(); } SqlParser parser = SqlParser.create(queryString, parserConfig); SqlNode sqlNode; try { sqlNode = parser.parseQuery(); } catch (SqlParseException e) { throw new RuntimeException("parse failed", e); } final CalciteCatalogReader catalogReader = createCatalogReader().withSchemaPath(schemaPath); final SqlValidator validator = createSqlValidator(catalogReader); final RexBuilder rexBuilder = createRexBuilder(); final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder); final SqlToRelConverter.Config config = SqlToRelConverter .configBuilder() .withConfig(sqlToRelConverterConfig) .withTrimUnusedFields(false) .withConvertTableAccess(false) .build(); final SqlToRelConverter sqlToRelConverter = new SqlToRelConverter(this, validator, catalogReader, cluster, convertletTable, config); final RelRoot root = sqlToRelConverter.convertQuery(sqlNode, true, false); final RelRoot root2 = root.withRel(sqlToRelConverter.flattenTypes(root.rel, true)); final RelBuilder relBuilder = config.getRelBuilderFactory().create(cluster, null); return root2.withRel( RelDecorrelator.decorrelateQuery(root.rel, relBuilder)); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mediaListItem = (MediaListItem) getArguments().getSerializable(ARG_GALLERY_ITEM); pageTitle = getArguments().getParcelable(ARG_PAGETITLE); imageTitle = new PageTitle(Namespace.FILE.toLegacyString(), StringUtil.removeNamespace(mediaListItem.getTitle()), pageTitle.getWikiSite()); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mediaListItem = (MediaListItem) getArguments().getSerializable(ARG_GALLERY_ITEM); pageTitle = getArguments().getParcelable(ARG_PAGETITLE); if (pageTitle == null) { pageTitle = new PageTitle(mediaListItem.getTitle(), new WikiSite(Service.COMMONS_URL)); } imageTitle = new PageTitle(Namespace.FILE.toLegacyString(), StringUtil.removeNamespace(mediaListItem.getTitle()), pageTitle.getWikiSite()); }
Source:
public static Properties defaultProperties(Properties properties) { properties = properties == null ? new Properties() : properties; properties.put("oauth.identity", "foo"); properties.put("oauth.credential", "password"); properties.put("oauth.endpoint", "<LINK_0>"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); properties.put(PROPERTY_ZONES, "northeurope,eastus"); return properties; }

Target:
public static Properties defaultProperties(Properties properties) { properties = properties == null ? new Properties() : properties; properties.put("oauth.identity", "foo"); properties.put("oauth.credential", "password"); properties.put("oauth.endpoint", "<LINK_0>"); properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString()); properties.put(PROPERTY_REGIONS, "northeurope"); return properties; }
Source:
private void createNodeAndExecStopEffector(Effector<?> eff) throws Exception { BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) .configure(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION, Boolean.TRUE)); app.start(locs); log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true); final String id = brooklynNode.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ConfigBag.newInstance() .configure(DeployBlueprintEffector.BLUEPRINT_TYPE, BasicApplication.class.getName()) .getAllConfig()).get(); String baseUrl = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI).toString(); String entityUrl = baseUrl + "v1/applications/" + id + "/entities/" + id; Entity mirror = brooklynNode.addChild(EntitySpec.create(BrooklynEntityMirror.class) .configure(BrooklynEntityMirror.MIRRORED_ENTITY_URL, entityUrl) .configure(BrooklynEntityMirror.MIRRORED_ENTITY_ID, id)); Entities.manage(mirror); assertEquals(brooklynNode.getChildren().size(), 1); try { brooklynNode.stop(); fail("stop must throw when the node has running apps"); } catch (Exception e) { } brooklynNode.invoke(BrooklynNode.STOP_NODE_AND_KILL_APPS, Collections.<String, Object>emptyMap()).getUnchecked(); EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false); }

Target:
private void createNodeAndExecStopEffector(Effector<?> eff) throws Exception { BrooklynNode brooklynNode = setUpBrooklynNodeWithApp(); brooklynNode.invoke(eff, Collections.<String, Object>emptyMap()).getUnchecked(); EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false); assertFalse(getDriver(brooklynNode).isRunning(), "Service process still running"); }
Source:
public CharSequence toXML(XmlEnvironment xmlEnvironment) { XmlStringBuilder xml = new XmlStringBuilder(this).rightAngleBracket(); for (AffixElement affix : affixElements) { xml.append(affix); } xml.append(payload); return xml.closeElement(this); }

Target:
public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) { XmlStringBuilder xml = new XmlStringBuilder(this).rightAngleBracket(); xml.append(affixElements); xml.append(payload); return xml.closeElement(this); }
Source:
Map<String, Map<String, Long>> getContainerStorageUsage() throws Exception; interface Callback { void onNewContainerStorageUsage(Map<String, Map<String, Long>> containerStorageUsage); }

Target:
Map<String, Map<String, Long>> getContainerStorageUsage() throws Exception; interface Listener { void onNewContainerStorageUsage(Map<String, Map<String, Long>> containerStorageUsage); }
Source:
public void onCreate(SQLiteDatabase db) { String CREATE_TABLE_SORT = "CREATE TABLE " + TABLE_SORT + "(" + COLUMN_SORT_ID + " INTEGER PRIMARY KEY," + COLUMN_SORT_PATH + " TEXT," + COLUMN_SORT_TYPE + " TEXT" + ")"; db.execSQL(CREATE_TABLE_SORT); }

Target:
public void onCreate(SQLiteDatabase db) { String CREATE_TABLE_SORT = "CREATE TABLE " + TABLE_SORT + "(" + COLUMN_SORT_PATH + " TEXT PRIMARY KEY," + COLUMN_SORT_TYPE + " INTEGER" + ")"; db.execSQL(CREATE_TABLE_SORT); }
Source:
public static synchronized IBinder makeConnector(Context context) { if (sConnector == null) { sConnector = new TetheringConnector(context); } return sConnector; }

Target:
private static synchronized IBinder makeConnector(Context context) { if (sConnector == null) { sConnector = new TetheringConnector(context); } return sConnector; }
Source:
public Optional<InputStream> tryCreateInputStream() { try { if (inputStreamSupplier == null) { return Optional.empty(); } return Optional.ofNullable(inputStreamSupplier.apply(this)); } catch (Exception e) { throw handleErrorInCallback(e, "inputStreamSupplier"); } }

Target:
public Optional<InputStream> tryCreateInputStream() { try { if (!canCreateInputStream()) { return Optional.empty(); } return Optional.ofNullable(inputStreamSupplier.apply(this)); } catch (Exception e) { throw handleErrorInCallback(e, "inputStreamSupplier"); } }
Source:
public static <T> List<List<T>> partitionList(List<T> inputList, int batchSize) { Objects.requireNonNull(inputList, "Input list cannot be null"); if (batchSize < 1) { throw new IllegalArgumentException("Invalid batchSize: " + batchSize); } List<List<T>> partitionedLists = new ArrayList<>(); for (int j = 0; j < inputList.size() / batchSize + 1; j++) { int start = j * batchSize; if (start >= inputList.size()) { break; } int end = Math.min((j + 1) * batchSize, inputList.size()); partitionedLists.add(inputList.subList(start, end)); } return partitionedLists; }

Target:
public static <T> List<List<T>> partitionList(List<T> inputList, int batchSize) { Objects.requireNonNull(inputList, "Input list cannot be null"); if (batchSize < 1) { throw new IllegalArgumentException("Invalid batchSize: " + batchSize); } List<List<T>> partitionedLists = new ArrayList<>(); for (int start = 0; start < inputList.size(); start += batchSize) { int end = Math.min(start + batchSize, inputList.size()); partitionedLists.add(inputList.subList(start, end)); } return partitionedLists; }
Source:
public JiraChangeLogAnnotator() { super(); if(LOGGER.isLoggable(Level.FINE)) { LOGGER.info("JiraChangeLogAnnotator registered"); } }

Target:
public JiraChangeLogAnnotator() { super(); LOGGER.fine("JiraChangeLogAnnotator created"); }
Source:
final public Aggregator factorize(ColumnSelectorFactory metricFactory) { Pair<Aggregator, BaseNullableColumnValueSelector> pair = factorize2( metricFactory); return NullHandling.useDefaultValuesForNull() ? pair.lhs : new NullableAggregator(pair.lhs, pair.rhs); }

Target:
public final Aggregator factorize(ColumnSelectorFactory metricFactory) { Pair<Aggregator, BaseNullableColumnValueSelector> pair = factorize2( metricFactory); return NullHandling.useDefaultValuesForNull() ? pair.lhs : new NullableAggregator(pair.lhs, pair.rhs); }
Source:
JSONArray getLastChannelObjectsReceivedByNewId(String id) { JSONArray lastChannelObjectReceived; try { lastChannelObjectReceived = getLastChannelObjects(); } catch (JSONException exception) { logger.log(OneSignal.LOG_LEVEL.ERROR, "Generating IAM tracker getLastChannelObjects JSONObject ", exception); return new JSONArray(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { for (int i = 0; i < lastChannelObjectReceived.length(); i++) { try { String objectId = lastChannelObjectReceived.getJSONObject(i).getString(getIdTag()); if (id.equals(objectId)) { lastChannelObjectReceived.remove(i); break; } } catch (JSONException exception) { logger.log(OneSignal.LOG_LEVEL.ERROR, "Generating tracker lastChannelObjectReceived get JSONObject ", exception); } } } else { try { JSONArray auxLastChannelObjectReceived = new JSONArray(); for (int i = 0; i < lastChannelObjectReceived.length(); i++) { String objectId = lastChannelObjectReceived.getJSONObject(i).getString(getIdTag()); if (!id.equals(objectId)) { auxLastChannelObjectReceived.put(lastChannelObjectReceived.getJSONObject(i)); } } lastChannelObjectReceived = auxLastChannelObjectReceived; } catch (JSONException exception) { logger.log(OneSignal.LOG_LEVEL.ERROR, "Before KITKAT API, Generating tracker lastChannelObjectReceived get JSONObject ", exception); } } return lastChannelObjectReceived; }

Target:
JSONArray getLastChannelObjectsReceivedByNewId(String id) { JSONArray lastChannelObjectReceived; try { lastChannelObjectReceived = getLastChannelObjects(); } catch (JSONException exception) { logger.error("Generating IAM tracker getLastChannelObjects JSONObject ", exception); return new JSONArray(); } try { JSONArray auxLastChannelObjectReceived = new JSONArray(); for (int i = 0; i < lastChannelObjectReceived.length(); i++) { String objectId = lastChannelObjectReceived.getJSONObject(i).getString(getIdTag()); if (!id.equals(objectId)) { auxLastChannelObjectReceived.put(lastChannelObjectReceived.getJSONObject(i)); } } lastChannelObjectReceived = auxLastChannelObjectReceived; } catch (JSONException exception) { logger.error("Before KITKAT API, Generating tracker lastChannelObjectReceived get JSONObject ", exception); } return lastChannelObjectReceived; }
Source:
public RequestDispatcher getRequestDispatcher(String uriInContext) { if (uriInContext == null) return null; if (!uriInContext.startsWith("/")) return null; try { String contextPath = getContextPath(); HttpURI uri; String pathInfo; if (StringUtil.isEmpty(contextPath)) { uri = HttpURI.from(uriInContext); pathInfo = URIUtil.canonicalPath(uri.getDecodedPath()); if (StringUtil.isEmpty(pathInfo)) return null; } else { HttpURI.Mutable builder = HttpURI.build(uriInContext); if (StringUtil.isEmpty(URIUtil.canonicalPath(builder.getDecodedPath()))) return null; builder.path(URIUtil.addPaths(contextPath,builder.getPath())); uri = builder.asImmutable(); pathInfo = uri.getDecodedPath().substring(contextPath.length()); } return new Dispatcher(ContextHandler.this, uri, pathInfo); } catch (Exception e) { LOG.trace("IGNORED", e); } return null; }

Target:
public RequestDispatcher getRequestDispatcher(String uriInContext) { if (uriInContext == null) return null; if (!uriInContext.startsWith("/")) return null; try { String contextPath = getContextPath(); String pathInfo; HttpURI.Mutable uri = HttpURI.build(uriInContext); pathInfo = URIUtil.canonicalPath(uri.getDecodedPath()); if (StringUtil.isEmpty(pathInfo)) return null; if (!StringUtil.isEmpty(contextPath)) { uri.path(URIUtil.addPaths(contextPath,uri.getPath())); pathInfo = uri.getDecodedPath().substring(contextPath.length()); } return new Dispatcher(ContextHandler.this, uri, pathInfo); } catch (Exception e) { LOG.trace("IGNORED", e); } return null; }
Source:
public Set<EObject> findByFeatureValue(Object value_, EStructuralFeature _feature) { Preconditions.checkArgument(IndexingLevel.FULL == getIndexingLevel(_feature), "%s is not on full index", _feature); Object value = toCanonicalValueRepresentation(value_); Object feature = toKey(_feature); Set<EObject> retSet = new HashSet<EObject>(); Map<Object, Collection<EObject>> valMap = instanceStore.getValueToFeatureToHolderMap().row(value); final Collection<EObject> holders = valMap.get(feature); if (holders != null) { retSet.addAll(EMFBaseIndexInstanceStore.holderCollectionToUniqueSet(holders)); } return retSet; }

Target:
public Set<EObject> findByFeatureValue(Object value_, EStructuralFeature _feature) { Object value = toCanonicalValueRepresentation(value_); Object feature = toKey(_feature); Set<EObject> retSet = new HashSet<EObject>(); Map<Object, Collection<EObject>> valMap = instanceStore.getValueToFeatureToHolderMap().row(value); final Collection<EObject> holders = valMap.get(feature); if (holders != null) { retSet.addAll(EMFBaseIndexInstanceStore.holderCollectionToUniqueSet(holders)); } return retSet; }
Source:
public void skipsOnStream() throws IOException { final long skip = 25L; final InputStream stream = Mockito.mock(InputStream.class); final CapInputStream wrapper = new CapInputStream( stream, 50L ); wrapper.skip(skip); Mockito.verify(stream, Mockito.times(1)).skip(skip); }

Target:
public void skipsOnStream() throws Exception { final long skip = 25L; final InputStream stream = Mockito.mock(InputStream.class); final CapInputStream wrapper = new CapInputStream(stream, 50L); wrapper.skip(skip); Mockito.verify(stream, Mockito.times(1)).skip(skip); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent routeIntent = getIntent(); Bundle extras = routeIntent.getExtras(); if (null == routeIntent) { MPLog.i(LOGTAG, "Notification route activity given null intent."); return; } trackAction(routeIntent); Intent notificationIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(routeIntent.getExtras().getCharSequence("uri").toString())); if (!extras.getBoolean("sticky")) { cancelNotification(extras); } startActivity(notificationIntent); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent routeIntent = getIntent(); Bundle extras = routeIntent.getExtras(); if (null == routeIntent) { MPLog.d(LOGTAG, "Notification route activity given null intent."); return; } trackAction(routeIntent); final Intent notificationIntent = handleRouteIntent(routeIntent); if (!extras.getBoolean("sticky")) { MixpanelFCMMessagingService fcmMessagingService = new MixpanelFCMMessagingService(); NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE); fcmMessagingService.cancelNotification(extras, notificationManager); } startActivity(notificationIntent); }
Source:
public HttpClient get() { final DruidHttpClientConfig config = getConfigProvider().get().get(); final HttpClient httpClient; if (getSslContextBinding() != null) { final SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setSslContext(getSslContextBinding().getProvider().get()); httpClient = new HttpClient(sslContextFactory); } else { httpClient = new HttpClient(); } httpClient.setIdleTimeout(config.getReadTimeout().getMillis()); httpClient.setMaxConnectionsPerDestination(config.getNumConnections()); httpClient.setMaxRequestsQueuedPerDestination(config.getNumRequestsQueued()); httpClient.setConnectTimeout(500); final QueuedThreadPool pool = new QueuedThreadPool(config.getNumMaxThreads()); pool.setName(JettyHttpClientModule.class.getSimpleName() + "-threadPool-" + pool.hashCode()); httpClient.setExecutor(pool); final Lifecycle lifecycle = getLifecycleProvider().get(); try { lifecycle.addMaybeStartHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { } @Override public void stop() { try { httpClient.stop(); } catch (Exception e) { throw Throwables.propagate(e); } } } ); } catch (Exception e) { throw Throwables.propagate(e); } return httpClient; }

Target:
public HttpClient get() { final DruidHttpClientConfig config = getConfigProvider().get().get(); final HttpClient httpClient; if (getSslContextBinding() != null) { final SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setSslContext(getSslContextBinding().getProvider().get()); httpClient = new HttpClient(sslContextFactory); } else { httpClient = new HttpClient(); } httpClient.setIdleTimeout(config.getReadTimeout().getMillis()); httpClient.setMaxConnectionsPerDestination(config.getNumConnections()); httpClient.setMaxRequestsQueuedPerDestination(config.getNumRequestsQueued()); httpClient.setConnectTimeout(CLIENT_CONNECT_TIMEOUT); final QueuedThreadPool pool = new QueuedThreadPool(config.getNumMaxThreads()); pool.setName(JettyHttpClientModule.class.getSimpleName() + "-threadPool-" + pool.hashCode()); httpClient.setExecutor(pool); final Lifecycle lifecycle = getLifecycleProvider().get(); try { lifecycle.addMaybeStartHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { } @Override public void stop() { try { httpClient.stop(); } catch (Exception e) { throw Throwables.propagate(e); } } } ); } catch (Exception e) { throw Throwables.propagate(e); } return httpClient; }
Source:
public ConfigBuilder appendTo(URI uri) { setOverwrite(); return writeTo(uri); }

Target:
public ConfigBuilder appendTo(URI uri) { setAppend(); return writeTo(uri); }
Source:
public Matrix feedForward(final Matrix input) { if (output == null || output.getColumns() != input.getColumns()) { output = matrixFactory.create(NeuralNetworkUtils.getShapeLength(outputShape), input.getColumns()); } for (int n = 0; n < input.getColumns(); ++n) { final Matrix newValue = im2row(n, input).mmul(getLayerParameter().getWeightParam()); output.putColumn(n, newValue.reshape(NeuralNetworkUtils.getShapeLength(outputShape), 1)); } output.addiColumnVector(getLayerParameter().getBiasParam()); return output; }

Target:
public Matrix feedForward(final Matrix input) { final Matrix output = matrixFactory.create(NeuralNetworkUtils.getShapeLength(outputShape), input.getColumns()); for (int n = 0; n < input.getColumns(); ++n) { final Matrix newValue = im2row(n, input).mmul(getLayerParameter().getWeightParam()); output.putColumn(n, newValue.reshape(NeuralNetworkUtils.getShapeLength(outputShape), 1)); } output.addiColumnVector(getLayerParameter().getBiasParam()); return output; }
Source:
public void setEnvironment(Cache<K, V> cache, Set<K> inputKeys) { cacheManager = cache.getCacheManager(); cacheNotifier = cache.getAdvancedCache().getComponentRegistry().getComponent(CacheNotifier.class); cacheManagerNotifier = cache.getCacheManager().getGlobalComponentRegistry().getComponent( CacheManagerNotifier.class); distExecutor = new DefaultExecutorService(cache); ourAddress = cache.getCacheManager().getAddress(); }

Target:
public void setEnvironment(Cache<K, V> cache, Set<K> inputKeys) { cacheManager = cache.getCacheManager(); cacheNotifier = cache.getAdvancedCache().getComponentRegistry().getComponent(CacheNotifier.class); cacheManagerNotifier = cache.getCacheManager().getGlobalComponentRegistry().getComponent( CacheManagerNotifier.class); distExecutor = new DefaultExecutorService(cache, new WithinThreadExecutor()); ourAddress = cache.getCacheManager().getAddress(); }
Source:
public DataTransactionResult removePassenger(Entity entity) { checkNotNull(entity); if (!entity.getPassengers().contains(this)) { throw new IllegalArgumentException(String.format("Cannot remove entity %s as a passenger of %s, because the former is not a passenger " + "of the latter ", entity, this)); } final DataTransactionResult.Builder builder = DataTransactionResult.builder(); this.removePassenger((net.minecraft.entity.Entity) entity); final ImmutableList.Builder<EntitySnapshot> passengerSnapshotsBuilder = ImmutableList.builder(); passengerSnapshotsBuilder.addAll(getPassengers().stream().map(Entity::createSnapshot).collect(Collectors.toList())); return builder.result(DataTransactionResult.Type.SUCCESS).success(new ImmutableSpongeListValue<>(Keys.PASSENGERS, passengerSnapshotsBuilder .build())).build(); }

Target:
public void removePassenger(Entity entity) { checkNotNull(entity); if (!entity.getPassengers().contains(this)) { throw new IllegalArgumentException(String.format("Cannot remove entity %s, because it is not a passenger of %s ", entity, this)); } ((net.minecraft.entity.Entity) entity).dismountRidingEntity(); }
Source:
private static AbstractPollingScheduler createDisabledPollingScheduler() { return new AbstractPollingScheduler() { @Override protected void schedule(Runnable pollingRunnable) { LOGGER.info("Periodical polling of a configuration source is turned off!"); } @Override public void stop() { } }; }

Target:
private static AbstractPollingScheduler createDisabledPollingScheduler() { return new AbstractPollingScheduler() { @Override protected void schedule(Runnable pollingRunnable) { logger.info("Periodical polling of a configuration source is turned off!"); } @Override public void stop() { } }; }
Source:
static public void reportPhysicalMemory() { com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean(); long physicalMemorySize = os.getTotalPhysicalMemorySize(); System.out.println("************ SYSTEM Physical Memory:" + physicalMemorySize); int MB = 1024 * 1024; Runtime runtime = Runtime.getRuntime(); long free = runtime.freeMemory()/MB; long total = runtime.totalMemory()/MB; System.out.println("************ total memory:" + total + " free memory:" + free); }

Target:
static public void reportPhysicalMemory() { com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean(); long physicalMemorySize = os.getTotalPhysicalMemorySize(); System.out.println("************ SYSTEM Physical Memory:" + physicalMemorySize); long MB = 1024 * 1024; Runtime runtime = Runtime.getRuntime(); long free = runtime.freeMemory()/MB; long total = runtime.totalMemory()/MB; System.out.println("************ total memory:" + total + " free memory:" + free); }
Source:
FunctionExpr(Function function, String name, List<Expr> args) { this.function = function; this.name = name; this.args = args; }

Target:
FunctionExpr(Function function, String name, List<Expr> args) { this.function = function; this.name = name; this.args = ImmutableList.copyOf(args); function.validateArguments(args); }
Source:
private String getReason(MergeFailureReason mergeFailureReason) { switch (mergeFailureReason) { case COULD_NOT_DELETE: return UIText.CherryPickHandler_CouldNotDeleteFile; case DIRTY_INDEX: return UIText.CherryPickHandler_IndexDirty; case DIRTY_WORKTREE: return UIText.CherryPickHandler_WorktreeDirty; } return "unknown"; }

Target:
private String getReason(MergeFailureReason mergeFailureReason) { switch (mergeFailureReason) { case COULD_NOT_DELETE: return UIText.CherryPickHandler_CouldNotDeleteFile; case DIRTY_INDEX: return UIText.CherryPickHandler_IndexDirty; case DIRTY_WORKTREE: return UIText.CherryPickHandler_WorktreeDirty; } return UIText.CherryPickHandler_unknown; }
Source:
protected LockProperties applyLockProperties(LockProperties lockProperties) { return lockProperties.withScope(Scope.Command); }

Target:
protected LockProperties applyLockProperties(LockProperties lockProperties) { return lockProperties.withScope(Scope.Execution); }
Source:
public void cleanup() { synchronizer.globalBarrier(); final long sleepMillis = 100; int numRetries = 20; while (numRetries > 0) { numRetries--; try { if (validate()) { return; } } catch (final IntegerValidationException e) { if (numRetries > 0) { try { Thread.sleep(sleepMillis); } catch (final InterruptedException e1) { LOG.log(Level.WARNING, "Interrupted while sleeping to compare the result with expected value", e); } } else { throw new RuntimeException(e); } } } }

Target:
public void cleanup() { synchronizer.globalBarrier(); int numRetries = NUM_VALIDATE_RETRIES; while (numRetries-- > 0) { if (validate()) { return; } try { Thread.sleep(VALIDATE_SLEEP_MS); } catch (final InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while sleeping to compare the result with expected value", e); } } LOG.log(Level.WARNING, "Validation test is failed"); throw new RuntimeException(); }
Source:
protected static void writeException(JsonGenerator jg, Throwable t, MediaType mediaType, int statusCode) throws IOException { jg.writeStartObject(); jg.writeStringField("entity-type", "exception"); jg.writeNumberField("status", statusCode); jg.writeStringField("message", t.getMessage()); if (jsonFactoryManager.isStackDisplay() || MediaType.valueOf(MediaType.APPLICATION_JSON + "+nxentity").equals(mediaType) || true) { jg.writeStringField("stacktrace", getStackTraceString(t)); jg.writeObjectField("exception", t); } jg.writeEndObject(); jg.flush(); }

Target:
protected static void writeException(JsonGenerator jg, Throwable t, MediaType mediaType, int statusCode) throws IOException { jg.writeStartObject(); jg.writeStringField("entity-type", "exception"); jg.writeNumberField("status", statusCode); jg.writeStringField("message", t.getMessage()); if (jsonFactoryManager.isStackDisplay() || MediaType.valueOf(MediaType.APPLICATION_JSON + "+nxentity").equals(mediaType)) { jg.writeStringField("stacktrace", getStackTraceString(t)); jg.writeObjectField("exception", t); } jg.writeEndObject(); jg.flush(); }
Source:
public void testClearState() throws Exception { final HiddenFieldCheck check = new HiddenFieldCheck(); final Optional<DetailAST> classDef = TestUtil.findTokenInAstByPredicate( JavaParser.parseFile( new File(getPath("InputHiddenField.java")), JavaParser.Options.WITHOUT_COMMENTS), ast -> ast.getType() == TokenTypes.CLASS_DEF); assertTrue("Ast should contain CLASS_DEF", classDef.isPresent()); assertTrue("State is not cleared on beginTree", TestUtil.isStatefulFieldClearedDuringBeginTree( check, classDef.get(), "frame", frame -> { boolean result = frame != null; if (result) { final Class<?> frameClass = frame.getClass(); try { if (TestUtil.getClassDeclaredField(frameClass, "parent").get( frame) != null || !((Boolean) TestUtil.getClassDeclaredField(frameClass, "staticType").get(frame)) || TestUtil.getClassDeclaredField(frameClass, "frameName").get(frame) != null) { result = false; } } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException ex) { throw new IllegalStateException(ex); } } return result; })); }

Target:
public void testClearState() throws Exception { final HiddenFieldCheck check = new HiddenFieldCheck(); final DetailAST root = JavaParser.parseFile(new File(getPath("InputHiddenField.java")), JavaParser.Options.WITHOUT_COMMENTS); final Optional<DetailAST> classDef = TestUtil.findTokenInAstByPredicate(root, ast -> ast.getType() == TokenTypes.CLASS_DEF); assertTrue("Ast should contain CLASS_DEF", classDef.isPresent()); assertTrue("State is not cleared on beginTree", TestUtil.isStatefulFieldClearedDuringBeginTree(check, classDef.get(), "frame", new CheckIfStatefulFieldCleared())); }
Source:
public QuotaCreditsResponse addQuotaCredits(final Long accountId, final Long domainId, final Double amount, final Long updatedBy, final Date despositedOn) { final short opendb = TransactionLegacy.currentTxn().getDatabaseId(); QuotaCreditsVO result = null; try (TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB)) { QuotaCreditsVO credits = new QuotaCreditsVO(accountId, domainId, new BigDecimal(amount), updatedBy); s_logger.info("addQuotaCredits: Depositing " + amount + " on adjusted date " + despositedOn); credits.setUpdatedOn(despositedOn); result = _quotaCreditsDao.saveCredits(credits); } TransactionLegacy.open(TransactionLegacy.CLOUD_DB).close(); final AccountVO account = _accountDao.findById(accountId); final boolean lockAccountEnforcement = "true".equalsIgnoreCase(QuotaConfig.QuotaEnableEnforcement.value()); final BigDecimal currentAccountBalance = _quotaBalanceDao.lastQuotaBalance(accountId, domainId, startOfNextDay(despositedOn)); if (lockAccountEnforcement && (currentAccountBalance.compareTo(new BigDecimal(0)) >= 0)) { if (account.getState() == Account.State.locked) { _regionMgr.enableAccount(account.getAccountName(), domainId, accountId); } } String creditor = String.valueOf(Account.ACCOUNT_ID_SYSTEM); User creditorUser = _userDao.getUser(updatedBy); if (creditorUser != null) { creditor = creditorUser.getUsername(); } TransactionLegacy.open(opendb).close(); QuotaCreditsResponse response = new QuotaCreditsResponse(result, creditor); response.setCurrency(QuotaConfig.QuotaCurrencySymbol.value()); return response; }

Target:
public QuotaCreditsResponse addQuotaCredits(final Long accountId, final Long domainId, final Double amount, final Long updatedBy, final Date despositedOn) { QuotaCreditsVO credits = new QuotaCreditsVO(accountId, domainId, new BigDecimal(amount), updatedBy); s_logger.debug("AddQuotaCredits: Depositing " + amount + " on adjusted date " + despositedOn); credits.setUpdatedOn(despositedOn); QuotaCreditsVO result = _quotaCreditsDao.saveCredits(credits); final AccountVO account = _accountDao.findById(accountId); final boolean lockAccountEnforcement = "true".equalsIgnoreCase(QuotaConfig.QuotaEnableEnforcement.value()); final BigDecimal currentAccountBalance = _quotaBalanceDao.lastQuotaBalance(accountId, domainId, startOfNextDay(despositedOn)); if (lockAccountEnforcement && (currentAccountBalance.compareTo(new BigDecimal(0)) >= 0)) { if (account.getState() == Account.State.locked) { _regionMgr.enableAccount(account.getAccountName(), domainId, accountId); } } String creditor = String.valueOf(Account.ACCOUNT_ID_SYSTEM); User creditorUser = _userDao.getUser(updatedBy); if (creditorUser != null) { creditor = creditorUser.getUsername(); } QuotaCreditsResponse response = new QuotaCreditsResponse(result, creditor); response.setCurrency(QuotaConfig.QuotaCurrencySymbol.value()); return response; }