auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void addProfileDataToNic(Map<String, Object> struct, VM vm, VmDevice vmDevice, VmNic nic) { VnicProfile vnicProfile = null; Network network = null; String networkName = ""; if (nic.getVnicProfileId() != null) { vnicProfile = DbFacade.getInstance().getVnicProfileDao().get(nic.getVnicProfileId()); if (vnicProfile != null) { network = DbFacade.getInstance().getNetworkDao().get(vnicProfile.getNetworkId()); networkName = network == null ? "" : network.getName(); log.debugFormat("VNIC {0} is using profile {1} on network {2}", nic.getName(), vnicProfile, networkName); addQosForDevice(struct, vnicProfile, vm.getVdsGroupCompatibilityVersion()); } } struct.put(VdsProperties.NETWORK, networkName); if (vnicProfile != null && vnicProfile.isPortMirroring()) { struct.put(VdsProperties.PORT_MIRRORING, network == null ? Collections.<String> emptyList() : Collections.singletonList(networkName)); } addCustomPropertiesForDevice(struct, vm, vmDevice, vm.getVdsGroupCompatibilityVersion(), getVnicCustomProperties(vnicProfile)); }

Target:
public static void addProfileDataToNic(Map<String, Object> struct, VM vm, VmDevice vmDevice, VmNic nic) { VnicProfile vnicProfile = null; Network network = null; String networkName = ""; if (nic.getVnicProfileId() != null) { vnicProfile = DbFacade.getInstance().getVnicProfileDao().get(nic.getVnicProfileId()); if (vnicProfile != null) { network = DbFacade.getInstance().getNetworkDao().get(vnicProfile.getNetworkId()); networkName = network.getName(); log.debugFormat("VNIC {0} is using profile {1} on network {2}", nic.getName(), vnicProfile, networkName); addQosForDevice(struct, vnicProfile, vm.getVdsGroupCompatibilityVersion()); } } struct.put(VdsProperties.NETWORK, networkName); if (vnicProfile != null && vnicProfile.isPortMirroring()) { struct.put(VdsProperties.PORT_MIRRORING, network == null ? Collections.<String> emptyList() : Collections.singletonList(networkName)); } addCustomPropertiesForDevice(struct, vm, vmDevice, vm.getVdsGroupCompatibilityVersion(), getVnicCustomProperties(vnicProfile)); }
Source:
public void shouldNotWipeStateStoresIfUnableToLockTaskDirectory() throws IOException { final File unknownFile = new File("/unknown/path"); expect(stateManager.taskId()).andReturn(taskId); expect(stateDirectory.lock(taskId)).andReturn(false); expect(stateManager.baseDir()).andReturn(unknownFile); Utils.delete(unknownFile); expectLastCall().andThrow(new StreamsException("Should not be trying to wipe state you don't own!")); ctrl.checkOrder(true); ctrl.replay(); replayAll(); StateManagerUtil.closeStateManager( logger, "logPrefix:", false, true, stateManager, stateDirectory, TaskType.ACTIVE); }

Target:
public void shouldNotWipeStateStoresIfUnableToLockTaskDirectory() throws IOException { final File unknownFile = new File("/unknown/path"); expect(stateManager.taskId()).andReturn(taskId); expect(stateDirectory.lock(taskId)).andReturn(false); expect(stateManager.baseDir()).andReturn(unknownFile); Utils.delete(unknownFile); expectLastCall().andThrow(new AssertionError("Should not be trying to wipe state you don't own!")); ctrl.checkOrder(true); ctrl.replay(); replayAll(); StateManagerUtil.closeStateManager( logger, "logPrefix:", false, true, stateManager, stateDirectory, TaskType.ACTIVE); }
Source:
public synchronized String load(Properties configuration) { return loadImpl(configuration, null); }

Target:
public String load(Properties configuration) { return loadImpl(configuration, null); }
Source:
private boolean isDistinctNode(AggregationNode aggregationNode) { return aggregationNode.getOutputSymbols().size() == 1 && aggregationNode.getGroupingKeys().size() == 1 && aggregationNode.getOutputSymbols().get(0) == aggregationNode.getGroupingKeys().get(0); }

Target:
private boolean isDistinctNode(AggregationNode aggregationNode) { List<Symbol> outputSymbols = aggregationNode.getOutputSymbols(); List<Symbol> groupingKeys = aggregationNode.getGroupingKeys(); return aggregationNode.getStep() == SINGLE && outputSymbols.size() == 1 && groupingKeys.size() == 1 && outputSymbols.get(0).equals(groupingKeys.get(0)); }
Source:
public int hashCode() { int result; long temp; result = dofM; result = 31 * result + carrier.hashCode(); result = 31 * result + dofW; result = 31 * result + (tailNum != null ? tailNum.hashCode() : 0); result = 31 * result + flightNum; result = 31 * result + (originID != null ? originID.hashCode() : 0); result = 31 * result + origin.hashCode(); result = 31 * result + (destId != null ? destId.hashCode() : 0); result = 31 * result + dest.hashCode(); temp = Double.doubleToLongBits(scheduleDepTime); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + (deptime != null ? deptime.hashCode() : 0); result = 31 * result + depDelayMins.hashCode(); result = 31 * result + (scheduledArrTime != null ? scheduledArrTime.hashCode() : 0); result = 31 * result + (arrTime != null ? arrTime.hashCode() : 0); result = 31 * result + (arrDelay != null ? arrDelay.hashCode() : 0); result = 31 * result + (elapsedTime != null ? elapsedTime.hashCode() : 0); result = 31 * result + distance; result = 31 * result + delayed.hashCode(); return result; }

Target:
public int hashCode() { return Objects.hash(dofM, dofW, carrier, tailNum, flightNum, originId, origin, destId, dest, scheduleDepTime, deptime, depDelayMins, scheduledArrTime, arrTime, arrDelay, elapsedTime, distance, delayed); }
Source:
public NoSuchPartitionException(String tableName, String partitionName) { super(String.format("ERROR: \"%s\" does not exist in \"%s\".", partitionName, tableName)); }

Target:
public NoSuchPartitionException(String tableName, String partitionName) { super(String.format("ERROR: \"%s\" is not the partition of \"%s\".", partitionName, tableName)); }
Source:
public void registerAdditionalCatalog(Achievement achievement) { String lowerId = achievement.getId().toLowerCase(Locale.ENGLISH); this.achievementMappings.putIfAbsent(lowerId, achievement); this.achievementMappings.putIfAbsent(lowerId.replaceFirst("^achievement.", ""), achievement); String underscoreId = achievement.getId().replaceAll("[A-Z]", "_$0").toLowerCase(Locale.ENGLISH); this.achievementMappings.putIfAbsent(underscoreId, achievement); this.achievementMappings.putIfAbsent(underscoreId.replaceFirst("^achievement.", ""), achievement); }

Target:
public void registerAdditionalCatalog(Achievement achievement) { String lowerId = achievement.getId().toLowerCase(Locale.ENGLISH); this.achievementMappings.putIfAbsent(lowerId, achievement); this.achievementMappings.putIfAbsent(lowerId.replaceFirst("^achievement.", ""), achievement); String underscoreId = achievement.getId().replaceAll("[A-Z]", "_$0").toLowerCase(Locale.ENGLISH); this.achievementMappings.putIfAbsent(underscoreId, achievement); this.achievementMappings.putIfAbsent(underscoreId.replaceFirst("^achievement.", ""), achievement); this.achievements = null; }
Source:
private boolean isInterruptedOrCanceled(IProgressMonitor monitor) { if (Thread.currentThread().isInterrupted()) { return true; } else if (monitor.isCanceled()) { if (shutdownInProgress.compareAndSet(false, true)) { Runnable runnable = new Runnable() { public void run() { shutdownPools(); } }; ListenableFuture<?> listenableFuture = terminator.submit(runnable); Futures.addCallback(listenableFuture, new FutureCallback<Object>() { public void onSuccess(Object result) { shutdownInProgress.set(false); } public void onFailure(Throwable t) { shutdownInProgress.set(false); EMFCompareIDEUIPlugin.getDefault().log(t); } }); } return true; } else { return false; } }

Target:
private boolean isInterruptedOrCanceled(IProgressMonitor monitor) { return Thread.currentThread().isInterrupted() || monitor.isCanceled(); }
Source:
public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); if (method == null) { return invocation.proceed(); } Method mostSpecificMethod = AopUtils .getMostSpecificMethod(invocation.getMethod(), invocation.getThis().getClass()); NewSpan newSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, NewSpan.class); ContinueSpan continueSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, ContinueSpan.class); if (newSpan == null && continueSpan == null) { return invocation.proceed(); } Class<?> returnType = method.getReturnType(); if(isReactiveReturnType(returnType)){ return proceedUnderSpanReactively(invocation, newSpan, continueSpan); } else { return proceedUnderSpanSynchronously(invocation, newSpan, continueSpan); } }

Target:
public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); if (method == null) { return invocation.proceed(); } Method mostSpecificMethod = AopUtils .getMostSpecificMethod(method, invocation.getThis().getClass()); NewSpan newSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, NewSpan.class); ContinueSpan continueSpan = SleuthAnnotationUtils.findAnnotation(mostSpecificMethod, ContinueSpan.class); if (newSpan == null && continueSpan == null) { return invocation.proceed(); } if(isReactorReturnType(method.getReturnType())){ return proceedUnderReactorSpan(invocation, newSpan, continueSpan); } else { return proceedUnderSynchronousSpan(invocation, newSpan, continueSpan); } }
Source:
private boolean validateServerURL(String userUrl) { if (userUrl == null || userUrl.trim().length() == 0) { EditTextPreference preference = (EditTextPreference) findPreference(KEY_URL); preference.setText(getString(R.string.settings_url_default_value)); return false; } int port = Uri.parse(userUrl).getPort(); if (URLUtil.isValidUrl(userUrl) && (port >= -1 && port <= 65535) && (URLUtil.isHttpUrl(userUrl) || URLUtil.isHttpsUrl(userUrl))) { return true; } Toast.makeText(MainActivity.this, R.string.error_msg_invalid_url, Toast.LENGTH_LONG).show(); return false; }

Target:
private boolean validateServerURL(String userUrl) { int port = Uri.parse(userUrl).getPort(); if (URLUtil.isValidUrl(userUrl) && (port == -1 || (port > 0 && port <= 65535)) && (URLUtil.isHttpUrl(userUrl) || URLUtil.isHttpsUrl(userUrl))) { return true; } Toast.makeText(MainActivity.this, R.string.error_msg_invalid_url, Toast.LENGTH_LONG).show(); return false; }
Source:
public void run() { System.out.println("Running DownloadMediaUseCase"); final List<Media> currentMedias = mMediaRepository.getAll(); if (mConnectivityManager.isDeviceOnline()) { if(mFileDownloader.isFileDownloaderIProgress()) { System.out.println("File downloader is already downloading"); return; } mFileDownloader.download(currentMedias, PreferencesState.getInstance().getDriveRootFolderUid(), mProgramRepository.getUserProgram().getCode(), new IFileDownloader.Callback() { @Override public void onError(FileDownloadException ex) { mCallback.onError(ex); mFileDownloader.changeFileDownloaderIProgress(false); } @Override public void onProgress() { mCallback.onProgress(); } @Override public void onSuccess(List<Media> syncMedias) { int numOfSyncedFiles = saveDownloadedMedia(syncMedias); removeNotDownloadedMedia(syncMedias, currentMedias); mCallback.onSuccess(numOfSyncedFiles); mFileDownloader.changeFileDownloaderIProgress(false); } }); } else { System.out.println(this.getClass().getSimpleName() + ": No wifi connection available. Media will not be synced"); mFileDownloader.changeFileDownloaderIProgress(false); } }

Target:
public void run() { System.out.println("Running DownloadMediaUseCase"); final List<Media> currentMedias = mMediaRepository.getAll(); if (mConnectivityManager.isDeviceOnline()) { if(mFileDownloader.isFileDownloaderIProgress()) { System.out.println("File downloader is already downloading"); return; } mCallback.onDownloadInProgressChanged(true); mFileDownloader.changeFileDownloaderIProgress(true); mFileDownloader.download(currentMedias, PreferencesState.getInstance().getDriveRootFolderUid(), mProgramRepository.getUserProgram().getCode(), new IFileDownloader.Callback() { @Override public void onError(FileDownloadException ex) { mCallback.onError(ex); mFileDownloader.changeFileDownloaderIProgress(false); mCallback.onDownloadInProgressChanged(false); } @Override public void onSuccess(List<Media> syncMedias) { int numOfSyncedFiles = saveDownloadedMedia(syncMedias); removeNotDownloadedMedia(syncMedias, currentMedias); mCallback.onSuccess(numOfSyncedFiles); mFileDownloader.changeFileDownloaderIProgress(false); mCallback.onDownloadInProgressChanged(false); } }); } else { System.out.println(this.getClass().getSimpleName() + ": No wifi connection available. Media will not be synced"); mFileDownloader.changeFileDownloaderIProgress(false); } }
Source:
private Request makeCreateRequest(String path, long sessionId) throws IOException { ByteArrayOutputStream boas = new ByteArrayOutputStream(); BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas); CreateRequest createRequest = new CreateRequest(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag()); createRequest.serialize(boa, "request"); ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray()); return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb, new ArrayList<>()); }

Target:
private Request makeCreateRequest(String path, long sessionId) throws IOException { ByteArrayOutputStream boas = new ByteArrayOutputStream(); BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas); CreateRequest createRequest = new CreateRequest(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag()); createRequest.serialize(boa, "request"); ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray()); return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb, new ArrayList<Id>()); }
Source:
public void close() throws IOException { innerScanner.close(); if (verify) { try { verificationResultRepository.logToIndexToolResultTable(verificationResult, verifyType, region.getRegionInfo().getRegionName()); } finally { this.pool.stop("IndexerRegionScanner is closing"); hTableFactory.shutdown(); indexHTable.close(); verificationResultRepository.close(); } } }

Target:
public void close() throws IOException { innerScanner.close(); try { verificationResultRepository.logToIndexToolResultTable(verificationResult, IndexTool.IndexVerifyType.ONLY, region.getRegionInfo().getRegionName()); } finally { this.pool.stop("IndexerRegionScanner is closing"); hTableFactory.shutdown(); indexHTable.close(); verificationResultRepository.close(); } }
Source:
public void exportMesh( final AtlasSourceState< ?, ? > state, final long id, final int scaleIndex, String path ) { final Cache< Long, Interval[] >[] blockListCache = state.blocklistCacheProperty().get(); final Cache< ShapeKey, Pair< float[], float[] > >[] meshCache = state.meshesCacheProperty().get(); Interval[] blocks = null; try { blocks = blockListCache[ scaleIndex ].get( id ); } catch ( ExecutionException e ) { LOG.warn( "Could not get mesh block list for id {}: {}", id, e.getMessage() ); } final List< ShapeKey > keys = new ArrayList<>(); for ( final Interval block : blocks ) keys.add( new ShapeKey( id, scaleIndex, 0, Intervals.minAsLongArray( block ), Intervals.maxAsLongArray( block ) ) ); float[] allVertices = null; float[] allNormals = null; for ( final ShapeKey key : keys ) { Pair< float[], float[] > verticesAndNormals; try { verticesAndNormals = meshCache[ scaleIndex ].get( key ); allVertices = ArrayUtils.addAll( allVertices, verticesAndNormals.getA() ); allNormals = ArrayUtils.addAll( allNormals, verticesAndNormals.getB() ); } catch ( final ExecutionException e ) { LOG.warn( "Was not able to retrieve mesh for {}: {}", key, e.getMessage() ); } catch ( final RuntimeException e ) { LOG.warn( "{} : {}", e.getClass(), e.getMessage() ); e.printStackTrace(); throw e; } } assert allVertices.length == allNormals.length: "Vertices and normals must have the same size."; save( path, id, allVertices, allNormals ); }

Target:
public void exportMesh( final AtlasSourceState< ?, ? > state, final long id, final int scaleIndex, String path ) { final Cache< Long, Interval[] >[] blockListCache = state.blocklistCacheProperty().get(); final Cache< ShapeKey, Pair< float[], float[] > >[] meshCache = state.meshesCacheProperty().get(); Interval[] blocks = null; try { blocks = blockListCache[ scaleIndex ].get( id ); } catch ( ExecutionException e ) { LOG.warn( "Could not get mesh block list for id {}: {}", id, e.getMessage() ); } final List< ShapeKey > keys = new ArrayList<>(); for ( final Interval block : blocks ) keys.add( new ShapeKey( id, scaleIndex, 0, Intervals.minAsLongArray( block ), Intervals.maxAsLongArray( block ) ) ); for ( final ShapeKey key : keys ) { Pair< float[], float[] > verticesAndNormals; try { verticesAndNormals = meshCache[ scaleIndex ].get( key ); assert verticesAndNormals.getA().length == verticesAndNormals.getB().length: "Vertices and normals must have the same size."; save( path, id, verticesAndNormals.getA(), verticesAndNormals.getB(), BooleanUtils.toBoolean( numberOfFaces ) ); numberOfFaces += verticesAndNormals.getA().length / 3; } catch ( final ExecutionException e ) { LOG.warn( "Was not able to retrieve mesh for {}: {}", key, e.getMessage() ); } catch ( final RuntimeException e ) { LOG.warn( "{} : {}", e.getClass(), e.getMessage() ); e.printStackTrace(); throw e; } } }
Source:
public String show(Request request, Response response) throws IOException { long id = getIdFromRequest(request.params("id")); User user = userService.findUserByName(currentUsernameString()); Optional<NotificationFilter> optionalFilter = user.getNotificationFilters().stream() .filter(filter -> filter.getId() == id) .findFirst(); if (optionalFilter.isEmpty()) { throw new RecordNotFoundException(EntityType.NotificationFilter, id); } return writerForTopLevelObject(request, response, writer -> NotificationFilterRepresenter.toJSON(writer, optionalFilter.get())); }

Target:
public String show(Request request, Response response) throws IOException { NotificationFilter notificationFilter = doFetchEntityFromConfig(request.params("id")); if (notificationFilter == null) { throw new RecordNotFoundException(EntityType.NotificationFilter, parseIdToLong(request.params("id"))); } return writerForTopLevelObject(request, response, writer -> NotificationFilterRepresenter.toJSON(writer, notificationFilter)); }
Source:
public void handleUpdateData(UpdateData data) { if (data.getDao() == null || !data.getDao().getClass().isAnnotationPresent(MaterializedView.class)) { return; } String entityName = null; for (Class<?> clz : data.getDao().getClass().getInterfaces()) { if (DAO.class.isAssignableFrom(clz)) { for (Type t : clz.getGenericInterfaces()) { if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; if (pt.getActualTypeArguments().length > 0) { Type actualParameter = pt.getActualTypeArguments()[0]; if (actualParameter instanceof Class) { Class<?> entityClass = (Class<?>) actualParameter; entityName = entityClass.getSimpleName(); } } } } } } if (entityName == null) { log.error("MaterializedViewListener could not discover activated entity for DAO " + data.getDao() + " . Data inconsistency might occur."); } else { log.info("Refreshing materialized view for entity " + entityName); } }

Target:
public void handleUpdateData(UpdateData data) { if (data.getDao() == null || !data.getDao().getClass().isAnnotationPresent(MaterializedView.class)) { return; } MaterializedView mView = data.getDao().getClass().getAnnotation(MaterializedView.class); String[] effectedViews = mView.effectedViews(); MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("matviews", effectedViews); DbFacade.getInstance().getCallsHandler().executeModification("RefreshManyMaterializedViews", params); log.info("Refreshing materialized view for entities " + Arrays.toString(effectedViews)); }
Source:
private void showRemoveTemplateWithDependentVMConfirmationWindow(HashMap<String, List<String>> problematicVmNames) { ArrayList<String> missingTemplatesFromVms = new ArrayList<>(); for (Map.Entry<String, List<String>> templateName : problematicVmNames.entrySet()) { List<String> vms = problematicVmNames.get(templateName.getKey()); String vmsListString = StringUtils.join(vms, ","); missingTemplatesFromVms.add(ConstantsManager.getInstance() .getMessages() .templatesWithDependentVMs(templateName.getKey(), vmsListString)); } ConfirmationModel confirmModel = new ConfirmationModel(); setConfirmWindow(confirmModel); confirmModel.setTitle(ConstantsManager.getInstance() .getConstants() .removeBackedUpTemplatesWithDependentsVMTitle()); confirmModel.setHelpTag(HelpTag.remove_backed_up_template); confirmModel.setHashName("remove_backed_up_template"); confirmModel.setMessage(ConstantsManager.getInstance() .getConstants() .theFollowingTemplatesHaveDependentVmsBackupOnExportDomainMsg()); confirmModel.setItems(missingTemplatesFromVms); UICommand removeTemplateUiCommand = UICommand.createDefaultOkUiCommand("RemoveVmTemplates", this); confirmModel.getCommands().add(removeTemplateUiCommand); UICommand cancelConfirmationUiCommand = UICommand.createCancelUiCommand("CancelConfirmation", this); confirmModel.getCommands().add(cancelConfirmationUiCommand); }

Target:
private void showRemoveTemplateWithDependentVMConfirmationWindow(HashMap<String, List<String>> problematicVmNames) { ArrayList<String> missingTemplatesFromVms = new ArrayList<>(); for (Map.Entry<String, List<String>> templateName : problematicVmNames.entrySet()) { List<String> vms = problematicVmNames.get(templateName.getKey()); String vmsListString = StringUtils.join(vms, ", "); missingTemplatesFromVms.add(ConstantsManager.getInstance() .getMessages() .templatesWithDependentVMs(templateName.getKey(), vmsListString)); } setConfirmWindow(null); ConfirmationModel confirmModel = new ConfirmationModel(); setConfirmWindow(confirmModel); confirmModel.setTitle(ConstantsManager.getInstance() .getConstants() .removeBackedUpTemplatesWithDependentsVMTitle()); confirmModel.setHelpTag(HelpTag.remove_backed_up_template); confirmModel.setHashName("remove_backed_up_template"); confirmModel.setMessage(ConstantsManager.getInstance() .getConstants() .theFollowingTemplatesHaveDependentVmsBackupOnExportDomainMsg()); confirmModel.setItems(missingTemplatesFromVms); UICommand removeTemplateUiCommand = UICommand.createDefaultOkUiCommand("RemoveVmTemplates", this); confirmModel.getCommands().add(removeTemplateUiCommand); UICommand cancelConfirmationUiCommand = UICommand.createCancelUiCommand("CancelConfirmation", this); confirmModel.getCommands().add(cancelConfirmationUiCommand); }
Source:
public void draw(Context context, GL10 gl) { gl.glPushMatrix(); OpenGlTransform.apply(gl, getTransform()); scale(gl); innerDraw(context, gl); gl.glPopMatrix(); }

Target:
public void draw(Context context, GL10 gl) { gl.glPushMatrix(); OpenGlTransform.apply(gl, getTransform()); scale(gl); drawShape(context, gl); gl.glPopMatrix(); }
Source:
private static String validate(String path) { if (path == null) { log.error("Path is null"); return null; } if (path.length() - 4 < 0) { log.error("File name too short (should at least end with .jyn) (got {})", path); return null; } if (path.endsWith(File.separator)) { path = path.substring(0, path.length()-File.separator.length()); } File f = new File(path); if (!f.isDirectory()) { log.debug("Not a directory, trying parent"); return null; } if (! path.toLowerCase().startsWith(".jyn", path.length() - 4)) { log.debug("Not an instrument (folder name not ending with .jyn) (got {})", path); return null; } String[] children = f.list(); String className = null; if (children == null) { log.error("Didn't find any files in {}", f); return className; } String assumedClassName = f.getName().substring(0, f.getName().length() - 4); for (String c : children) { if ((c).compareToIgnoreCase(assumedClassName + ".py") == 0) { return assumedClassName; } } log.warn("Coulnd't find best candidate ({}), reverting to first one", assumedClassName + ".py"); for (String c : children) { if (c.substring(c.length() - 3).compareToIgnoreCase(".py") == 0) { className = c.substring(0, c.length() - 3); } } log.warn("Using {}", className); return className; }

Target:
private static String validate(String path) { if (path == null) { log.error("Path is null"); return null; } if (path.length() - 4 < 0) { log.error("File name too short (should at least end with .jyn) (got {})", path); return null; } if (path.endsWith(File.separator)) { path = path.substring(0, path.length()-File.separator.length()); } File f = new File(path); if (!f.isDirectory()) { log.debug("Not a directory, trying parent"); return null; } if (! path.toLowerCase().endsWith(".jyn")) { log.debug("Not an instrument (folder name not ending with .jyn) (got {})", path); return null; } String[] children = f.list(); String className = null; if (children == null) { log.error("Didn't find any files in {}", f); return className; } String assumedClassName = f.getName().substring(0, f.getName().length() - 4); for (String c : children) { if ((c).compareToIgnoreCase(assumedClassName + ".py") == 0) { return assumedClassName; } } log.warn("Coulnd't find best candidate ({}), reverting to first one", assumedClassName + ".py"); for (String c : children) { if (c.substring(c.length() - 3).compareToIgnoreCase(".py") == 0) { className = c.substring(0, c.length() - 3); } } log.warn("Using {}", className); return className; }
Source:
private boolean checkForManagementPortException() { if (this.getStatusCode() == FailedRequestUsingMgmtPortException.MGMT_PORT_STATUS_CODE) { if (getFirstHeaderValue(getResponse().getHeaders(), FailedRequestUsingMgmtPortException.MGMT_PORT_HEADER) != null) { return true; } } return false; }

Target:
private boolean checkForManagementPortException() { return ((this.getStatusCode() == FailedRequestUsingMgmtPortException.MGMT_PORT_STATUS_CODE) && (getFirstHeaderValue(getResponse().getHeaders(), FailedRequestUsingMgmtPortException.MGMT_PORT_HEADER) != null)); }
Source:
public void onAcquiredLockNotification() { synchronized (ZKDistributedNonblockingLock.this) { _isLocked = true; ZKDistributedNonblockingLock.this.notify(); } }

Target:
public void onAcquiredLockNotification() { _lockStatus = LockConstants.LockStatus.LOCKED; _countDownLatch.countDown(); }
Source:
public GameProfile call() throws Exception { if (this.id != null) { return this.fromId(this.id); } else if (this.name != null) { return this.fromNames(Lists.newArrayList(this.name)).get(0); } throw new IllegalStateException("Impossibru"); }

Target:
public GameProfile call() throws Exception { if (this.id != null) { return this.fromId(this.id); } else if (this.name != null) { return this.fromNames(Lists.newArrayList(this.name)).get(0); } throw new IllegalStateException("Impossible! The query if not for a name or a uuid."); }
Source:
public Favicon(File fav) { if ( fav == null ) { return; } try { if ( !fav.exists() ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load server icon because it does not exist!" ); return; } if ( !fav.getName().endsWith( ".png" ) ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load server icon because it is not a PNG file!" ); return; } if ( !fav.isFile() ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load server icon because it is not a file!" ); return; } BufferedImage image = ImageIO.read( fav ); if ( image != null ) { if ( image.getHeight() == 64 && image.getWidth() == 64 ) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ImageIO.write( image, "png", bytes ); favicon = "data:image/png;base64," + BaseEncoding.base64().encode( bytes.toByteArray() ); if ( favicon.length() > Short.MAX_VALUE ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Favicon file too large for server to process" ); favicon = null; } } else { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Server icon must be exactly 64x64 pixels" ); } } else { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Could not load server icon for unknown reason. Please double check its format." ); } } catch ( IOException e ) { e.printStackTrace(); } }

Target:
public Favicon(File fav) throws FaviconException { if ( fav == null ) { return; } try { if ( !fav.exists() ) { throw new FaviconException( "Could not load server icon because it does not exist!" ); } if ( !fav.isFile() ) { throw new FaviconException( "Could not load server icon because it is not a file!" ); } if ( !fav.getName().toLowerCase().endsWith( ".png" ) ) { throw new FaviconException( "Could not load server icon because it is not a PNG file!" ); } BufferedImage image = ImageIO.read( fav ); if ( image != null ) { if ( image.getHeight() == 64 && image.getWidth() == 64 ) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ImageIO.write( image, "png", bytes ); favicon = "data:image/png;base64," + BaseEncoding.base64().encode( bytes.toByteArray() ); if ( favicon.length() > Short.MAX_VALUE ) { throw new FaviconException( "Favicon file too large for server to process" ); } } else { throw new FaviconException( "Server icon must be exactly 64x64 pixels" ); } } else { throw new FaviconException( "Could not load server icon for unknown reason. Please double check its format." ); } } catch ( IOException e ) { throw new FaviconException( e.getMessage() ); } }
Source:
public static <T> String toSerializedPersistent(T object) { return toSerializedPersistent(object); }

Target:
public static <T> String toSerializedPersistent(T object) { return toSerialized(object, PERSISTENT); }
Source:
public boolean dispatch(InternetAddress recipient, String subject, String templatePlain, String templateHtml, Map<String, Object> properties) { Message message = new MimeMessage(mailSession); String processedContentPlain; String processedContentHtml; try { processedContentPlain = templateService.getProcessedTemplate("invitation_plain.ftl", Locale.US, properties); processedContentHtml = templateService.getProcessedTemplate("invitation_html.ftl", Locale.US, properties); message.setFrom(fromAddress); message.setRecipient(Message.RecipientType.TO, recipient); message.setSubject(subject); MimeBodyPart text = new MimeBodyPart(); text.setContent(processedContentPlain, "text/plain"); MimeBodyPart rich = new MimeBodyPart(); rich.setContent(processedContentHtml, "text/html"); Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(rich); multipart.addBodyPart(text); message.setContent(multipart); } catch (MessagingException | TemplateException | IOException e) { logger.exceptionPreparingMessage(recipient.getAddress(), e); return false; } try { Transport.send(message); } catch (MessagingException e) { logger.exceptionSendingMessage(recipient.getAddress(), e); return false; } return true; }

Target:
public boolean dispatch(InternetAddress recipient, String subject, String templatePlain, String templateHtml, Map<String, Object> properties) { Message message = new MimeMessage(mailSession); String processedContentPlain; String processedContentHtml; try { processedContentPlain = templateService.getProcessedTemplate(templatePlain, Locale.US, properties); processedContentHtml = templateService.getProcessedTemplate(templateHtml, Locale.US, properties); message.setFrom(fromAddress); message.setRecipient(Message.RecipientType.TO, recipient); message.setSubject(subject); MimeBodyPart text = new MimeBodyPart(); text.setContent(processedContentPlain, "text/plain"); MimeBodyPart rich = new MimeBodyPart(); rich.setContent(processedContentHtml, "text/html"); Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(rich); multipart.addBodyPart(text); message.setContent(multipart); } catch (MessagingException | TemplateException | IOException e) { logger.exceptionPreparingMessage(recipient.getAddress(), e); return false; } try { Transport.send(message); } catch (MessagingException e) { logger.exceptionSendingMessage(recipient.getAddress(), e); return false; } return true; }
Source:
public TransactionImportResult importRemoteTransaction(Xid xid, int timeout) throws XAException { if (xid == null) { throw new IllegalArgumentException(jtaLogger.i18NLogger.get_error_imported_transaction_uid_is_null()); } return addImportedTransaction(null, convertXid(xid), xid, timeout); }

Target:
public TransactionImportResult importRemoteTransaction(Xid xid, int timeout) throws XAException { if (xid == null) { throw new IllegalArgumentException(jtaLogger.i18NLogger.get_error_xid_is_null()); } return addImportedTransaction(null, convertXid(xid), xid, timeout); }
Source:
public StorageDiskListModel() { setTitle(ConstantsManager.getInstance().getConstants().disksTitle()); setHelpTag(HelpTag.disks); setHashName("disks"); diskOperationsHelper = new DiskOperationsHelper(); setMoveCommand(new UICommand("Move", this)); setCopyCommand(new UICommand("Copy", this)); setRemoveCommand(new UICommand("Remove", this)); setUploadCommand(new UICommand("Upload", this)); setCancelUploadCommand(new UICommand("CancelUpload", this)); setPauseUploadCommand(new UICommand("PauseUpload", this)); setResumeUploadCommand(new UICommand("ResumeUpload", this)); setDownloadCommand(new UICommand("Download", this)); updateActionAvailability(); }

Target:
public StorageDiskListModel() { setTitle(ConstantsManager.getInstance().getConstants().disksTitle()); setHelpTag(HelpTag.disks); setHashName("disks"); setMoveCommand(new UICommand("Move", this)); setCopyCommand(new UICommand("Copy", this)); setRemoveCommand(new UICommand("Remove", this)); setUploadCommand(new UICommand("Upload", this)); setCancelUploadCommand(new UICommand("CancelUpload", this)); setPauseUploadCommand(new UICommand("PauseUpload", this)); setResumeUploadCommand(new UICommand("ResumeUpload", this)); setDownloadCommand(new UICommand("Download", this)); updateActionAvailability(); }
Source:
private static void maybeWarnAboutCodeInRocksDBConfigSetter(final Logger log, final StreamsConfig config) { if (config.getClass(StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG) != null) { log.warn("Kafka Streams cannot guarantee backwards compatibility of code in the RocksDB config setter " + "because RocksDB may remove methods without deprecating them."); } }

Target:
private static void maybeWarnAboutCodeInRocksDBConfigSetter(final Logger log, final StreamsConfig config) { if (config.getClass(StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG) != null) { RocksDBGenericOptionsToDbOptionsColumnFamilyOptionsAdapter.logWarning(log); } }
Source:
public Firehose connect(StringInputRowParser firehoseParser, File temporaryDirectory) throws IOException { final List<ObjectType> objects = ImmutableList.copyOf(Preconditions.checkNotNull(initObjects(), "initObjects")); final Iterator<ObjectType> iterator = objects.iterator(); return new FileIteratingFirehose( new Iterator<LineIterator>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public LineIterator next() { if (!hasNext()) { throw new NoSuchElementException(); } final ObjectType object = iterator.next(); try { return IOUtils.lineIterator( new BufferedReader( new InputStreamReader(openStream(object), Charsets.UTF_8) ) ); } catch (Exception e) { LOG.error( e, "Exception reading object[%s]", object ); throw Throwables.propagate(e); } } }, firehoseParser ); }

Target:
public Firehose connect(StringInputRowParser firehoseParser, File temporaryDirectory) throws IOException { if (objects == null) { objects = ImmutableList.copyOf(Preconditions.checkNotNull(initObjects(), "initObjects")); } final Iterator<ObjectType> iterator = objects.iterator(); return new FileIteratingFirehose( new Iterator<LineIterator>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public LineIterator next() { if (!hasNext()) { throw new NoSuchElementException(); } final ObjectType object = iterator.next(); try { return IOUtils.lineIterator(wrapObjectStream(object, openObjectStream(object)), Charsets.UTF_8); } catch (Exception e) { LOG.error( e, "Exception reading object[%s]", object ); throw Throwables.propagate(e); } } }, firehoseParser ); }
Source:
protected Appender<ILoggingEvent> wrapAppenderAsAsyncIfNecessary(Appender<ILoggingEvent> delegate) { if (this.async) { AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.addAppender(delegate); asyncAppender.setQueueSize(this.asyncQueueLength); asyncAppender.setDiscardingThreshold(this.discarding ? 5 : 0); asyncAppender.setIncludeCallerData(this.calleeData); return asyncAppender; } else { return delegate; } }

Target:
protected Appender<ILoggingEvent> wrapAppenderAsAsyncIfNecessary(Appender<ILoggingEvent> delegate) { if (this.async) { AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.addAppender(delegate); asyncAppender.setQueueSize(this.asyncQueueLength); asyncAppender.setDiscardingThreshold(this.discarding ? DISCARD_20_PCT_HEADROOM : DONT_DISCARD); asyncAppender.setIncludeCallerData(this.calleeData); return asyncAppender; } else { return delegate; } }
Source:
private void deletePaaSDB(ClaudiaData claudiaData, EnvironmentInstance envInstance, TierInstance tierInstance, boolean error) throws InvalidEntityException, InfrastructureException { log.info("Deleting the environment instance " + envInstance.getBlueprintName() + " in the database "); envInstance = environmentInstanceDao.update(envInstance); try { infrastructureManager.deleteNetworksInTierInstance(claudiaData, tierInstance); } catch (Exception e) { log.error(e.getMessage()); error = true; } finally { log.info("Deleting security group from in tier " + tierInstance.getName() + " in TierInstance"); if (tierInstance.getSecurityGroup() != null && !tierInstance.getVdc().isEmpty()) { SecurityGroup securityGroup=null; try { securityGroup = securityGroupDao.loadWithRules(tierInstance.getSecurityGroup().getName()); } catch (EntityNotFoundException e1) { String msg = "SecurityGroup is not present in database " + securityGroup.getName(); log.error(msg); e1.printStackTrace(); throw new InvalidEntityException(msg); } log.info("Deleting security group " + securityGroup.getName() + " in tier " + tierInstance.getName()); tierInstance.setSecurityGroup(null); tierInstanceDao.update(tierInstance); securityGroupManager.destroy(tierInstance.getTier().getRegion(), claudiaData.getUser().getToken(), tierInstance.getVdc(), securityGroup); } tierInstanceManager.remove(tierInstance); } }

Target:
private void deletePaaSDB(ClaudiaData claudiaData, EnvironmentInstance envInstance, TierInstance tierInstance, boolean error) throws InvalidEntityException, InfrastructureException { log.info("Deleting the environment instance " + envInstance.getBlueprintName() + " in the database "); envInstance = environmentInstanceDao.update(envInstance); try { infrastructureManager.deleteNetworksInTierInstance(claudiaData, tierInstance); } catch (Exception e) { log.error(e.getMessage()); error = true; } finally { log.info("Deleting security group from tierInstance " + tierInstance.getName() + " in TierInstance"); SecurityGroup secGroup = tierInstance.getSecurityGroup(); if (secGroup != null) { SecurityGroup securityGroup=null; try { securityGroup = securityGroupDao.loadWithRules(secGroup.getName()); } catch (EntityNotFoundException e1) { String msg = "SecurityGroup is not present in database " + securityGroup.getName(); log.error(msg); e1.printStackTrace(); throw new InvalidEntityException(msg); } log.info("Deleting security group " + securityGroup.getName() + " associated to tierInstance " + tierInstance.getName()); tierInstance.setSecurityGroup(null); tierInstanceDao.update(tierInstance); securityGroupManager.destroy(tierInstance.getTier().getRegion(), claudiaData.getUser().getToken(), tierInstance.getVdc(), securityGroup); } tierInstanceManager.remove(tierInstance); } }
Source:
public void createPartControl(final Composite parent) { super.createPartControl(parent); if (getTreeModel() == null) { final Label errorLabel = new Label(parent, SWT.CENTER); errorLabel.setText(Messages.DTreeEditor_treeModelUnsaved); return; } treeViewerManager = new DTreeViewerManager(parent, getTreeModel(), getEditingDomain(), accessor, emfCommandFactory, this); getSite().setSelectionProvider(treeViewerManager.getTreeViewer()); if (session != null) { InterpreterRegistry.prepareImportsFromSession(session.getInterpreter(), session); } ((DTreeActionBarContributor) getEditorSite().getActionBarContributor()).addCreateTreeItemMenu(((DTreeViewerManager) this.getTableViewer()).getCreateTreeItemMenu()); refreshAtOpeningActivator = new RefreshAtOpeningActivator(this); getSite().getPage().addPartListener(refreshAtOpeningActivator); IContextService contextService = getSite().getService(IContextService.class); contextService.activateContext(CONTEXT_ID); }

Target:
public void createPartControl(final Composite parent) { super.createPartControl(parent); if (getTreeModel() == null) { final Label errorLabel = new Label(parent, SWT.CENTER); errorLabel.setText(Messages.DTreeEditor_treeModelUnsaved); return; } treeViewerManager = new DTreeViewerManager(parent, getTreeModel(), getEditingDomain(), accessor, emfCommandFactory, this); getSite().setSelectionProvider(treeViewerManager.getTreeViewer()); if (session != null) { InterpreterRegistry.prepareImportsFromSession(session.getInterpreter(), session); } ((DTreeActionBarContributor) getEditorSite().getActionBarContributor()).addCreateTreeItemMenu(((DTreeViewerManager) this.getTableViewer()).getCreateTreeItemMenu()); refreshAtOpeningActivator = new RefreshAtOpeningActivator(this); getSite().getPage().addPartListener(refreshAtOpeningActivator); IContextService contextService = (IContextService) getSite().getService(IContextService.class); contextService.activateContext(CONTEXT_ID); }
Source:
private void organiseResponses(String courseId) { questionToResponses = new HashMap<>(); for (int i = 1; i <= 3; i++) { FeedbackQuestionAttributes question = testData.feedbackQuestions.get("qn" + i); List<FeedbackResponseAttributes> responses = getResponsesByQuestion(courseId, i); questionToResponses.put(question, responses); } questionToGiverToResponses = new HashMap<>(); questionToRecipientToResponses = new HashMap<>(); for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> entry : questionToResponses.entrySet()) { FeedbackQuestionAttributes question = entry.getKey(); List<FeedbackResponseAttributes> responses = entry.getValue(); Map<String, List<FeedbackResponseAttributes>> recipientToResponse = new HashMap<>(); Map<String, List<FeedbackResponseAttributes>> giverToResponse = new HashMap<>(); for (FeedbackResponseAttributes response : responses) { String recipient = response.getRecipient(); String giver = response.getGiver(); if (!recipientToResponse.containsKey(recipient)) { recipientToResponse.put(recipient, new ArrayList<>()); } if (!giverToResponse.containsKey(giver)) { giverToResponse.put(giver, new ArrayList<>()); } recipientToResponse.get(recipient).add(response); giverToResponse.get(giver).add(response); } questionToRecipientToResponses.put(question, recipientToResponse); questionToGiverToResponses.put(question, giverToResponse); } }

Target:
private void organiseResponses(String courseId) { List<FeedbackQuestionAttributes> questions = getQuestionsByCourse(courseId); questionToResponses = new HashMap<>(); for (FeedbackQuestionAttributes question : questions) { List<FeedbackResponseAttributes> responses = getResponsesByQuestion(courseId, question.getQuestionNumber()); questionToResponses.put(question, responses); } questionToGiverToResponses = new HashMap<>(); questionToRecipientToResponses = new HashMap<>(); for (Map.Entry<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> entry : questionToResponses.entrySet()) { FeedbackQuestionAttributes question = entry.getKey(); List<FeedbackResponseAttributes> responses = entry.getValue(); Map<String, List<FeedbackResponseAttributes>> recipientToResponse = new HashMap<>(); Map<String, List<FeedbackResponseAttributes>> giverToResponse = new HashMap<>(); for (FeedbackResponseAttributes response : responses) { String recipient = response.getRecipient(); String giver = response.getGiver(); if (!recipientToResponse.containsKey(recipient)) { recipientToResponse.put(recipient, new ArrayList<>()); } if (!giverToResponse.containsKey(giver)) { giverToResponse.put(giver, new ArrayList<>()); } recipientToResponse.get(recipient).add(response); giverToResponse.get(giver).add(response); } questionToRecipientToResponses.put(question, recipientToResponse); questionToGiverToResponses.put(question, giverToResponse); } }
Source:
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!ctx.channel().isOpen()) { logger.debug("Channel closed when write. Channel: {}", ctx.channel()); promise.setFailure(new ChannelException("Channel has been closed when write.")); } if (!(msg instanceof Send)) { ctx.write(msg, promise); return; } Send send = (Send) msg; Http2Headers http2Headers; if (forServer) { logger.trace("Write content to channel as server {}", ctx.channel()); http2Headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); } else { logger.trace("Write content to channel as client {}", ctx.channel()); http2Headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName()).scheme("https").path("/"); } DefaultHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(http2Headers, false); ctx.write(headersFrame); ByteBuf dataContent = send.content(); if (dataContent == null) { ByteBufChannel byteBufChannel = new ByteBufChannel(); try { send.writeTo(byteBufChannel); dataContent = byteBufChannel.getBuf(); send.release(); } catch (IOException e) { promise.setFailure(e); return; } } DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(dataContent, true); ctx.write(dataFrame, promise); }

Target:
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!ctx.channel().isOpen()) { logger.debug("Channel closed when write. Channel: {}", ctx.channel()); promise.setFailure(new ChannelException("Channel has been closed when write.")); } if (!(msg instanceof Send)) { ctx.write(msg, promise); return; } Send send = (Send) msg; Http2Headers http2Headers; if (forServer) { logger.trace("Write content to channel as server {}", ctx.channel()); http2Headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); } else { logger.trace("Write content to channel as client {}", ctx.channel()); http2Headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName()).scheme("https").path("/"); } DefaultHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(http2Headers, false); ctx.write(headersFrame); ByteBuf dataContent = send.content(); if (dataContent == null) { ByteBufChannel byteBufChannel = new ByteBufChannel(); try { send.writeTo(byteBufChannel); dataContent = byteBufChannel.getBuf(); } catch (IOException e) { promise.setFailure(e); return; } finally { send.release(); } } DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(dataContent, true); ctx.write(dataFrame, promise); }