auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Response send(Command entity) throws Exception { Context.getPermissionsManager().checkReadonly(getUserId()); long deviceId = entity.getDeviceId(); long id = entity.getId(); Context.getPermissionsManager().checkDevice(getUserId(), deviceId); if (id != 0) { Context.getPermissionsManager().checkPermission(Command.class, getUserId(), id); Context.getPermissionsManager().checkUserDeviceCommand(getUserId(), deviceId, id); } else { Context.getPermissionsManager().checkLimitCommands(getUserId()); } boolean sent = Context.getCommandsManager().sendCommand(entity); if (!sent) { return Response.accepted(entity).build(); } return Response.ok(entity).build(); }

Target:
public Response send(Command entity) throws Exception { Context.getPermissionsManager().checkReadonly(getUserId()); long deviceId = entity.getDeviceId(); long id = entity.getId(); Context.getPermissionsManager().checkDevice(getUserId(), deviceId); if (id != 0) { Context.getPermissionsManager().checkPermission(Command.class, getUserId(), id); Context.getPermissionsManager().checkUserDeviceCommand(getUserId(), deviceId, id); } else { Context.getPermissionsManager().checkLimitCommands(getUserId()); } if (!Context.getCommandsManager().sendCommand(entity)) { return Response.accepted(entity).build(); } return Response.ok(entity).build(); }
Source:
protected SSHClient _getSSHClient() { EngineSSHClient client = new EngineSSHClient(); client.setVds(_vds); return (SSHClient) client; }

Target:
protected SSHClient _getSSHClient() { EngineSSHClient client = new EngineSSHClient(); if (_client != null) { VDS vds = ((EngineSSHClient)_client).getVds(); if (vds != null) { client.setVds(vds); } } return client; }
Source:
private static final Type entryType(Type keyType, Type valueType) { return new ArrayType(new RowType(ImmutableList.of(keyType, valueType), Optional.empty())); }

Target:
private static Type entryType(Type keyType, Type valueType) { return new ArrayType(new RowType(ImmutableList.of(keyType, valueType), Optional.empty())); }
Source:
public boolean removeRaider(Raider raider) { if (raider.getRaid().isPresent()) { if (this.equals(raider.getRaid().get())) { this.raid.leaveRaid((AbstractRaiderEntity) raider, true); return true; } } return false; }

Target:
public boolean removeRaider(Raider raider) { checkNotNull(raider, "Raider cannot be null."); if (raider.getRaid().isPresent()) { if (this.equals(raider.getRaid().get().getWaves().get(this.waveId))) { this.raid.leaveRaid((AbstractRaiderEntity) raider, true); return true; } } return false; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IEvaluationContext context = (IEvaluationContext) event.getApplicationContext(); IWorkbench workbench = (IWorkbench) context.getVariable(IWorkbench.class.getName()); workbench.getDisplay().close(); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbench workbench = HandlerUtil.getActiveWorkbenchWindow(event).getService(IWorkbench.class); workbench.getDisplay().close(); return null; }
Source:
private static CoordinationStore<VersionedInternalSchemaMetadata> createCoordinationStore( KeyValueService keyValueService, LongSupplier timestampSupplier, boolean initializeAsync) { return createRawCoordinationStore(keyValueService, timestampSupplier, initializeAsync); }

Target:
private static CoordinationStore<VersionedInternalSchemaMetadata> createCoordinationStore( KeyValueService keyValueService, LongSupplier timestampSupplier, boolean initializeAsync) { return KeyValueServiceCoordinationStore.create( ObjectMappers.newServerObjectMapper(), keyValueService, AtlasDbConstants.DEFAULT_METADATA_COORDINATION_KEY, timestampSupplier, VersionedInternalSchemaMetadata::knowablySemanticallyEquivalent, VersionedInternalSchemaMetadata.class, initializeAsync); }
Source:
protected synchronized void handleEvent(CoordinatorEvent event) { LOG.info("START: Handle event " + event.getType() + ", Instance: " + _adapter.getInstanceName()); try { switch (event.getType()) { case LEADER_DO_ASSIGNMENT: assignDatastreamTasksToInstances(); break; case HANDLE_ASSIGNMENT_CHANGE: handleAssignmentChange(); break; case HANDLE_NEW_DATASTREAM: handleNewDatastream(); break; case HANDLE_INSTANCE_ERROR: handleInstanceError(event); } } catch (Exception e) { LOG.error("ERROR: event + " + event + " failed."); } LOG.info("END: Handle event " + event); }

Target:
protected synchronized void handleEvent(CoordinatorEvent event) { LOG.info("START: Handle event " + event.getType() + ", Instance: " + _adapter.getInstanceName()); try { switch (event.getType()) { case LEADER_DO_ASSIGNMENT: assignDatastreamTasksToInstances(); break; case HANDLE_ASSIGNMENT_CHANGE: handleAssignmentChange(); break; case HANDLE_NEW_DATASTREAM: handleNewDatastream(); break; case HANDLE_INSTANCE_ERROR: handleInstanceError(event); } } catch (Throwable e) { LOG.error("ERROR: event + " + event + " failed.", e); } LOG.info("END: Handle event " + event); }
Source:
private static void addN90s(Map<String, List<JsonNode>> subClasses) { JsonNode wikidataJson = WikidataLocations.load(); Pair<List<JsonNode>, Map<String, List<JsonNode>>> topAndSub = Classification.buildHierarchyWikidata(wikidataJson); String n9 = "<LINK_0>"; String euregio = "<LINK_0>1"; List<JsonNode> n9Sub = new ArrayList<>(); n9Sub.addAll(topAndSub.getLeft()); n9Sub.add(subClasses.get(n9).stream() .filter(json -> json.get("value").textValue().equals(euregio)) .iterator().next()); subClasses.put(n9, n9Sub); subClasses.putAll(topAndSub.getRight()); }

Target:
private static void addN90s(Map<String, List<JsonNode>> subClasses) { JsonNode wikidataJson = WikidataLocations.load(); Pair<List<JsonNode>, Map<String, List<JsonNode>>> topAndSub = Classification.buildHierarchyWikidata(wikidataJson); String n9 = NWBIB_SPATIAL + "N9"; String euregio = NWBIB_SPATIAL + "N91"; List<JsonNode> n9Sub = new ArrayList<>(); n9Sub.addAll(topAndSub.getLeft()); n9Sub.add(subClasses.get(n9).stream() .filter(json -> json.get("value").textValue().equals(euregio)) .iterator().next()); subClasses.put(n9, n9Sub); subClasses.putAll(topAndSub.getRight()); }
Source:
public PermissionsPolicyHeaderWriter() { this(""); }

Target:
public PermissionsPolicyHeaderWriter() { }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IProject project = null; IEditorPart editorPart = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getActiveEditor(); if (editorPart != null) { IFileEditorInput input = (IFileEditorInput) editorPart.getEditorInput(); IFile file = input.getFile(); project = file.getProject(); } else { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event); if (window != null) { IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection(); if (selection instanceof TreeSelection) { TreeSelection treeSelection = (TreeSelection) selection; TreePath path = treeSelection.getPaths()[0]; Object first = path.getFirstSegment(); if (first instanceof IAdaptable) { project = ((IAdaptable) first).getAdapter(IProject.class); } } else { Object firstElement = selection.getFirstElement(); if (firstElement instanceof IAdaptable) { project = ((IAdaptable) firstElement).getAdapter(IProject.class); } } } } if (project != null) { IFile file = project.getFile("/gulpfile.js"); if (file.exists()) { StructuredSelection fileSelection = new StructuredSelection(file); GulpLaunch launch = new GulpLaunch(); launch.launch(fileSelection, null); } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IContainer container = null; IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { IWorkbenchPart part = page.getActivePart(); if (part != null) { IFile activeEditorFile = getEditorFile(part); if (activeEditorFile != null) { if (GULP_FILE_NAME.equals(activeEditorFile.getName())) { new GulpLaunch().launch(new StructuredSelection(activeEditorFile), GULP_TASK_RUN); return null; } else { container = activeEditorFile.getProject(); } } } if (container == null) { IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection(); if (selection instanceof TreeSelection) { TreeSelection treeSelection = (TreeSelection) selection; Object element = treeSelection.getFirstElement(); if (element != null) { element.toString(); if (element instanceof IFile && GULP_FILE_NAME.equals(((IFile) element).getName())) { new GulpLaunch().launch(treeSelection, GULP_TASK_RUN); return null; } else if (element instanceof ITask) { new GulpLaunch().launch(selection, GULP_TASK_RUN); return null; } } TreePath path = treeSelection.getPaths()[0]; Object first = path.getFirstSegment(); if (first instanceof IAdaptable) { container = ((IAdaptable) first).getAdapter(IContainer.class); } } else { Object firstElement = selection.getFirstElement(); if (firstElement instanceof IAdaptable) { container = ((IAdaptable) firstElement).getAdapter(IContainer.class); } } } } } if (container != null) { IFile file = container.getFile(new Path(GULP_FILE_NAME)); if (file.exists()) { StructuredSelection fileSelection = new StructuredSelection(file); new GulpLaunch().launch(fileSelection, GULP_TASK_RUN); } } return null; }
Source:
private Algorithm parseAlgorithm() throws TypeImportException, XMLStreamException { String name = getAttributeValue(LibraryElementTags.NAME_ATTRIBUTE); String comment = getAttributeValue(LibraryElementTags.COMMENT_ATTRIBUTE); Algorithm retVal = null; while (getReader().hasNext()) { int event = getReader().next(); if (event == XMLStreamConstants.START_ELEMENT) { switch (getReader().getLocalName()) { case LibraryElementTags.FBD_ELEMENT: throw new TypeImportException("Algorithm: Unsupported Algorithmtype (only ST and Other possible)!"); case LibraryElementTags.ST_ELEMENT: retVal = LibraryElementFactory.eINSTANCE.createSTAlgorithm(); parseST((STAlgorithm) retVal); break; case LibraryElementTags.LD_ELEMENT: throw new TypeImportException("Algorithm: Unsupported Algorithmtype (only ST and Other possible)!"); case LibraryElementTags.OTHER_ELEMENT: retVal = LibraryElementFactory.eINSTANCE.createOtherAlgorithm(); parseOtherAlg((OtherAlgorithm) retVal); break; default: throw new XMLStreamException("Unexpected xml child (" + getReader().getLocalName() + ") found!"); } } else if (event == XMLStreamConstants.END_ELEMENT) { if (!getReader().getLocalName().equals(LibraryElementTags.ALGORITHM_ELEMENT)) { throw new XMLStreamException("Unexpected xml end tag found in " + LibraryElementTags.ALGORITHM_ELEMENT + ": " + getReader().getLocalName()); } break; } } if (null != retVal) { retVal.setName(name); retVal.setComment(comment); } return retVal; }

Target:
private Algorithm parseAlgorithm() throws TypeImportException, XMLStreamException { String name = getAttributeValue(LibraryElementTags.NAME_ATTRIBUTE); String comment = getAttributeValue(LibraryElementTags.COMMENT_ATTRIBUTE); Algorithm retVal = null; while (getReader().hasNext()) { int event = getReader().next(); if (XMLStreamConstants.START_ELEMENT == event) { switch (getReader().getLocalName()) { case LibraryElementTags.FBD_ELEMENT: throw new TypeImportException("Algorithm: Unsupported Algorithmtype (only ST and Other possible)!"); case LibraryElementTags.ST_ELEMENT: retVal = LibraryElementFactory.eINSTANCE.createSTAlgorithm(); parseST((STAlgorithm) retVal); break; case LibraryElementTags.LD_ELEMENT: throw new TypeImportException("Algorithm: Unsupported Algorithmtype (only ST and Other possible)!"); case LibraryElementTags.OTHER_ELEMENT: retVal = LibraryElementFactory.eINSTANCE.createOtherAlgorithm(); parseOtherAlg((OtherAlgorithm) retVal); break; default: throw new XMLStreamException("Unexpected xml child (" + getReader().getLocalName() + ") found!"); } } else if (XMLStreamConstants.END_ELEMENT == event) { if (!getReader().getLocalName().equals(LibraryElementTags.ALGORITHM_ELEMENT)) { throw new XMLStreamException("Unexpected xml end tag found in " + LibraryElementTags.ALGORITHM_ELEMENT + ": " + getReader().getLocalName()); } break; } } if (null != retVal) { retVal.setName(name); retVal.setComment(comment); } return retVal; }
Source:
private void postConstruct() { CLASS_TO_MAPPER_MAP.put(MeterReads.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(EventMessageDataContainer.class, this.managementMapper); CLASS_TO_MAPPER_MAP.put(ActionValueResponseObject.class, this.commonMapper); }

Target:
private void postConstruct() { CLASS_TO_MAPPER_MAP.put(MeterReads.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(MeterReadsGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(EventMessageDataContainer.class, this.managementMapper); CLASS_TO_MAPPER_MAP.put(ActionResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(AlarmRegister.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(AdministrativeStatusTypeResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainer.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainerGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(GetConfigurationResponseContainer.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(FirmwareVersionResponseContainer.class, this.monitoringMapper); }
Source:
public CuratorFramework newClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy) { CuratorFramework curator = mock(CuratorFramework.class); RetryLoop retryLoop = mock(RetryLoop.class); when(retryLoop.shouldContinue()).thenReturn(false); CuratorZookeeperClient czkClient = mock(CuratorZookeeperClient.class); when(czkClient.newRetryLoop()).thenReturn(retryLoop); when(curator.getZookeeperClient()).thenReturn(czkClient); when(curator.getConnectionStateListenable()).thenReturn(mock(Listenable.class)); when(curator.getChildren()).thenThrow(KeeperException.ConnectionLossException.class); when(curator.newNamespaceAwareEnsurePath(anyString())).thenReturn(mock(EnsurePath.class)); return curator; }

Target:
public CuratorFramework newClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy) { final CuratorFramework curator = mock(CuratorFramework.class); final RetryLoop retryLoop = mock(RetryLoop.class); when(retryLoop.shouldContinue()).thenReturn(false); final CuratorZookeeperClient czkClient = mock(CuratorZookeeperClient.class); when(czkClient.newRetryLoop()).thenReturn(retryLoop); when(curator.getZookeeperClient()).thenReturn(czkClient); when(curator.getConnectionStateListenable()).thenReturn(mock(Listenable.class)); when(curator.getChildren()).thenThrow(KeeperException.ConnectionLossException.class); when(curator.newNamespaceAwareEnsurePath(anyString())).thenReturn(mock(EnsurePath.class)); return curator; }
Source:
public String getCourseId() { return browser.driver.findElement(By.id(Const.ParamsNames.COURSE_ID)).getAttribute("value"); }

Target:
public String getCourseId() { return courseIdTextBox.getAttribute("value"); }
Source:
private static String getLocalIP(NetworkInterface intf) { String result = null; for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements(); ) { String calculated; InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { InetAddressValidator validator = InetAddressValidator.getInstance(); calculated = inetAddress.getHostAddress().toString(); if (validator.isValid(calculated)) { result = calculated; break; } } } return result; }

Target:
private static String getLocalIP(NetworkInterface intf) { for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { InetAddressValidator validator = InetAddressValidator.getInstance(); String calculated = inetAddress.getHostAddress().toString(); if (validator.isValid(calculated)) { return calculated; } } } return null; }
Source:
private void publishEvent(String event, Message msg, Map<String, String> parameters) { Map<String, String> map = new HashMap<String, String>(); map.putAll(parameters); map.put(MESSAGE_CLASS, msg.getClass().getCanonicalName()); ZAP.getEventBus().publishSyncEvent( getPublisher(), new Event(getPublisher(), event, null, map)); }

Target:
private void publishEvent(String event, Message msg, Map<String, String> parameters) { Map<String, String> map = new HashMap<String, String>(); map.putAll(parameters); map.put(MESSAGE_TYPE, msg.getType()); ZAP.getEventBus().publishSyncEvent( getPublisher(), new Event(getPublisher(), event, null, map)); }
Source:
protected final void connect() throws ConnectionException { final SslContext sslCtx = null; final InetSocketAddress remoteAddress = new InetSocketAddress(getURI().getHost(), getURI().getPort()); if (remoteAddress.isUnresolved()) { throw new ConnectionException("Remote address does not exist " + remoteAddress.getHostString()); } final EventLoopGroup group = new NioEventLoopGroup(); try { final ClientWebSocketWrapper handler = new ClientWebSocketWrapper( WebSocketClientHandshakerFactory.newHandshaker( getURI(), WebSocketVersion.V13, null, false, new DefaultHttpHeaders()), this); final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @SuppressWarnings("PMD.CommentRequired") @Override protected void initChannel(final SocketChannel channel) { final ChannelPipeline pipeline = channel.pipeline(); if (sslCtx != null) { pipeline.addFirst(sslCtx.newHandler(channel.alloc(), getURI().getHost(), getURI().getPort())); } pipeline.addLast( new HttpClientCodec(), new HttpObjectAggregator(OBJECT_AGGREGATOR_CODE), handler); } }); LOG.info("{} connecting to[ ]", this.getClass().getSimpleName() , getURI()); final Channel channel = bootstrap.connect(getURI().getHost(), getURI().getPort()).sync().channel(); handler.handshakeFuture().sync(); LOG.error("Something happened? {}", channel.metadata()); } catch (InterruptedException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); group.shutdownGracefully(); } }

Target:
protected final void connect() throws ConnectionException { final SslContext sslCtx = null; final InetSocketAddress remoteAddress = new InetSocketAddress(getURI().getHost(), getURI().getPort()); if (remoteAddress.isUnresolved()) { throw new ConnectionException("Remote address does not exist " + remoteAddress.getHostString()); } final EventLoopGroup group = new NioEventLoopGroup(); try { final ClientWebSocketWrapper handler = new ClientWebSocketWrapper( WebSocketClientHandshakerFactory.newHandshaker( getURI(), WebSocketVersion.V13, null, false, new DefaultHttpHeaders()), this); final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @SuppressWarnings("PMD.CommentRequired") @Override protected void initChannel(final SocketChannel channel) { final ChannelPipeline pipeline = channel.pipeline(); if (sslCtx != null) { pipeline.addFirst(sslCtx.newHandler(channel.alloc(), getURI().getHost(), getURI().getPort())); } pipeline.addLast( new HttpClientCodec(), new HttpObjectAggregator(OBJECT_AGGREGATOR_CODE), handler); } }); LOG.info("{} connecting to[ ]", this.getClass().getSimpleName() , getURI()); bootstrap.connect(getURI().getHost(), getURI().getPort()).sync().channel(); handler.handshakeFuture().sync(); } catch (InterruptedException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); group.shutdownGracefully(); } }
Source:
public void initViews() { EditText passwordEditText = (EditText) loginActivity.findViewById(R.id.edittext_password); passwordEditText.setInputType(InputType.TYPE_CLASS_NUMBER); passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); TextInputLayout passwordHint = (TextInputLayout) loginActivity.findViewById(R.id.password_hint); passwordHint.setHint(loginActivity.getResources().getText(R.string.login_password)); username = (EditText) loginActivity.findViewById(R.id.edittext_username); LinearLayout loginViewsContainer = (LinearLayout) loginActivity.findViewById(R.id.login_views_container); LayoutInflater inflater = LayoutInflater.from(loginActivity); Button forgotPassword = (Button) inflater.inflate(R.layout.forgot_password_button, null, false); loginViewsContainer.addView(forgotPassword); forgotPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onForgotPassword(); } }); IMainExecutor mainExecutor = new UIThreadExecutor(); IAsyncExecutor asyncExecutor = new AsyncExecutor(); ICredentialsRepository credentialsRepository = new CredentialsLocalDataSource(); GetUserLastInsertedUsernameUseCase getUserLastInsertedUsernameUseCase = new GetUserLastInsertedUsernameUseCase(mainExecutor, asyncExecutor, credentialsRepository); getUserLastInsertedUsernameUseCase.execute( new GetUserLastInsertedUsernameUseCase.Callback() { @Override public void onGetUsername(String username) { LoginActivityStrategy.this.username.setText(username); } }); }

Target:
public void initViews() { EditText passwordEditText = (EditText) loginActivity.findViewById(R.id.edittext_password); passwordEditText.setInputType(InputType.TYPE_CLASS_NUMBER); passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); TextInputLayout passwordHint = (TextInputLayout) loginActivity.findViewById(R.id.password_hint); passwordHint.setHint(loginActivity.getResources().getText(R.string.login_password)); username = (EditText) loginActivity.findViewById(R.id.edittext_username); LinearLayout loginViewsContainer = (LinearLayout) loginActivity.findViewById(R.id.login_views_container); LayoutInflater inflater = LayoutInflater.from(loginActivity); Button forgotPassword = (Button) inflater.inflate(R.layout.forgot_password_button, null, false); loginViewsContainer.addView(forgotPassword); forgotPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onForgotPassword(); } }); IMainExecutor mainExecutor = new UIThreadExecutor(); IAsyncExecutor asyncExecutor = new AsyncExecutor(); ICredentialsRepository credentialsRepository = new CredentialsLocalDataSource(); GetLastInsertedCredentialsUseCase getLastInsertedCredentialsUseCase = new GetLastInsertedCredentialsUseCase(mainExecutor, asyncExecutor, credentialsRepository); getLastInsertedCredentialsUseCase.execute( new GetLastInsertedCredentialsUseCase.Callback() { @Override public void onGetUsername(Credentials credentials) { if (credentials != null) { LoginActivityStrategy.this.username.setText(credentials.getUsername()); } } }); }
Source:
protected void doOperation() { List<AdminEmailAttributes> allEmails = adminEmailsLogic.getAllAdminEmails(); if (isPreview) { System.out.println("Checking Sanitization for admin emails..."); } int numberOfAffectedEmails = 0; for (AdminEmailAttributes email : allEmails) { if (isPreview) { if (previewSanitizedDataForAdminEmail(email)) { numberOfAffectedEmails++; } } else { fixSanitizedDataForEmail(email); } } if (isPreview) { System.out.println("There are/is " + numberOfAffectedEmails + " affected email(s)!"); } else { System.out.println("Sanitization fixing done!"); } }

Target:
protected void doOperation() { List<AdminEmailAttributes> allEmails = adminEmailsLogic.getAllAdminEmails(); int numberOfAffectedEmails = 0; int numberOfUpdatedEmails = 0; LoopHelper loopHelper = new LoopHelper(100, "admin emails processed."); println("Running data migration for sanitization on admin emails..."); println("Preview: " + isPreview); for (AdminEmailAttributes email : allEmails) { loopHelper.recordLoop(); boolean isEmailSanitized = DataMigrationForSanitizedDataHelper.isSanitizedHtml(email.getContentValue()); if (!isEmailSanitized) { continue; } numberOfAffectedEmails++; try { desanitizeAndUpdateEmail(email); numberOfUpdatedEmails++; } catch (InvalidParametersException | EntityDoesNotExistException e) { println("Problem sanitizing email id " + email.getEmailId()); println(e.getMessage()); } } println("Total number of emails: " + loopHelper.getCount()); println("Number of affected emails: " + numberOfAffectedEmails); println("Number of updated emails: " + numberOfUpdatedEmails); }
Source:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION_NAME, null); resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION, null); }

Target:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION_NAME, null); resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION, null); }
Source:
protected void testExecute() throws Exception { ______TS("Typical case"); CourseAttributes course = typicalBundle.courses.get("typicalCourse1"); FeedbackSessionAttributes session = typicalBundle.feedbackSessions.get("session1InCourse1"); String[] params = { Const.ParamsNames.COURSE_ID, course.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, session.getFeedbackSessionName(), }; PublishFeedbackSessionAction publishFeedbackSessionAction = getAction(params); JsonResult result = getJsonResult(publishFeedbackSessionAction); FeedbackSessionData feedbackSessionData = (FeedbackSessionData) result.getOutput(); assertEquals(feedbackSessionData.getFeedbackSessionName(), session.getFeedbackSessionName()); assertEquals(feedbackSessionData.getPublishStatus(), FeedbackSessionPublishStatus.PUBLISHED); ______TS("Failure case: Session is already published"); assertTrue(logic.getFeedbackSession(session.getFeedbackSessionName(), course.getId()).isPublished()); result = getJsonResult(getAction(params)); MessageOutput output = (MessageOutput) result.getOutput(); assertEquals(output.getMessage(), "Error publishing feedback session: Session has already been published."); assertEquals(result.getStatusCode(), HttpStatus.SC_BAD_REQUEST); }

Target:
protected void testExecute() throws Exception { ______TS("Typical case"); CourseAttributes course = typicalBundle.courses.get("typicalCourse1"); FeedbackSessionAttributes session = typicalBundle.feedbackSessions.get("session1InCourse1"); String[] params = { Const.ParamsNames.COURSE_ID, course.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, session.getFeedbackSessionName(), }; PublishFeedbackSessionAction publishFeedbackSessionAction = getAction(params); JsonResult result = getJsonResult(publishFeedbackSessionAction); FeedbackSessionData feedbackSessionData = (FeedbackSessionData) result.getOutput(); assertEquals(feedbackSessionData.getFeedbackSessionName(), session.getFeedbackSessionName()); assertEquals(FeedbackSessionPublishStatus.PUBLISHED, feedbackSessionData.getPublishStatus()); assertTrue(logic.getFeedbackSession(session.getFeedbackSessionName(), course.getId()).isPublished()); ______TS("Failure case: Session is already published"); assertTrue(logic.getFeedbackSession(session.getFeedbackSessionName(), course.getId()).isPublished()); result = getJsonResult(getAction(params)); MessageOutput output = (MessageOutput) result.getOutput(); assertEquals("Error publishing feedback session: Session has already been published.", output.getMessage()); assertEquals(HttpStatus.SC_BAD_REQUEST, result.getStatusCode()); }
Source:
public synchronized void cleanUp(Set<Long> activeTableIds) { if (activeTableIds.isEmpty()) { return; } long latestTableId = Collections.max(activeTableIds); for (Iterator<Map.Entry<Long, TableData>> tableDatas = tables.entrySet().iterator(); tableDatas.hasNext(); ) { Map.Entry<Long, TableData> tablePagesEntry = tableDatas.next(); Long tableId = tablePagesEntry.getKey(); if (tableId < latestTableId && !activeTableIds.contains(tableId)) { for (Page removedPage : tablePagesEntry.getValue().getPages()) { currentBytes -= removedPage.getRetainedSizeInBytes(); } tableDatas.remove(); } } }

Target:
public synchronized void cleanUp(Set<Long> activeTableIds) { if (activeTableIds.isEmpty()) { return; } long latestTableId = Collections.max(activeTableIds); for (Iterator<Map.Entry<Long, TableData>> tableDataIterator = tables.entrySet().iterator(); tableDataIterator.hasNext(); ) { Map.Entry<Long, TableData> tablePagesEntry = tableDataIterator.next(); Long tableId = tablePagesEntry.getKey(); if (tableId < latestTableId && !activeTableIds.contains(tableId)) { for (Page removedPage : tablePagesEntry.getValue().getPages()) { currentBytes -= removedPage.getRetainedSizeInBytes(); } tableDataIterator.remove(); } } }
Source:
RequestOptions toRequestOptions() { final RequestOptions requestOptions = new RequestOptions(); requestOptions.setConsistencyLevel(getConsistencyLevel()); requestOptions.setSessionToken(sessionToken); return requestOptions; }

Target:
RequestOptions toRequestOptions() { final RequestOptions requestOptions = new RequestOptions(); requestOptions.setIfMatchETag(getIfMatchETag()); requestOptions.setIfNoneMatchETag(getIfNoneMatchETag()); requestOptions.setContentResponseOnWriteEnabled(isContentResponseOnWriteEnabled()); return requestOptions; }
Source:
public ConsistencyCheckerTool(ClusterMap clusterMap, StoreKeyFactory storeKeyFactory, StoreConfig storeConfig, Set<StoreKey> filterSet, Throttler throttler, StoreToolsMetrics metrics, Time time, StoreKeyConverter storeKeyConverter) { StoreMetrics storeMetrics = new StoreMetrics("ConsistencyCheckerTool", clusterMap.getMetricRegistry()); indexProcessingHelper = new IndexProcessingHelper(storeKeyFactory, storeConfig, filterSet, throttler, storeMetrics, metrics, time, storeKeyConverter); }

Target:
public ConsistencyCheckerTool(ClusterMap clusterMap, StoreKeyFactory storeKeyFactory, StoreConfig storeConfig, Set<StoreKey> filterSet, Throttler throttler, StoreToolsMetrics metrics, Time time, StoreKeyConverter storeKeyConverter) { StoreMetrics storeMetrics = new StoreMetrics("ConsistencyCheckerTool", clusterMap.getMetricRegistry()); this.filterSet = filterSet; dumpIndexTool = new DumpIndexTool(storeKeyFactory, storeConfig, time, metrics, storeMetrics, throttler, storeKeyConverter); }
Source:
void flushStoredSessions() { if (flushingRequest.tryAcquire(1)) { try { List<File> storedFiles = sessionStore.findStoredFiles(); for (File storedFile : storedFiles) { Session payload = new Session(storedFile); DeliveryStatus deliveryStatus = deliverSessionPayload(payload); switch (deliveryStatus) { case DELIVERED: sessionStore.deleteStoredFiles(storedFiles); break; case UNDELIVERED: sessionStore.cancelQueuedFiles(storedFiles); logger.w("Leaving session payload for future delivery"); break; case FAILURE: logger.w("Deleting invalid session tracking payload"); sessionStore.deleteStoredFiles(storedFiles); break; default: break; } } } finally { flushingRequest.release(1); } } }

Target:
void flushStoredSessions() { if (flushingRequest.tryAcquire(1)) { try { List<File> storedFiles = sessionStore.findStoredFiles(); for (File storedFile : storedFiles) { flushStoredSession(storedFile); } } finally { flushingRequest.release(1); } } }
Source:
public void testNumberAdapter() throws Exception { NumberAdapter adapter = new NumberAdapter(); String value = adapter.marshal(4.65450971582E11); assertTrue(value.equals("4.65450971582E11")); }

Target:
public void testNumberAdapter() throws Exception { NumberAdapter adapter = new NumberAdapter(); assertEquals("4.65450971582E11", adapter.marshal(4.65450971582E11)); assertEquals(4.65450971582E11, adapter.unmarshal("4.65450971582E11")); assertEquals("45.0", adapter.marshal(45)); assertEquals(45.0, adapter.unmarshal("45")); assertEquals("2.147483647E9", adapter.marshal(Integer.MAX_VALUE)); assertEquals("NaN", adapter.marshal(Double.NaN)); assertEquals(Double.NaN, adapter.unmarshal("NaN")); assertEquals("Infinity", adapter.marshal(Double.POSITIVE_INFINITY)); assertEquals(Double.POSITIVE_INFINITY, adapter.unmarshal("Infinity")); assertEquals("-Infinity", adapter.marshal(Double.NEGATIVE_INFINITY)); assertEquals(Double.NEGATIVE_INFINITY, adapter.unmarshal("-Infinity")); assertEquals(Double.MAX_VALUE, adapter.unmarshal("1.7976931348623157E308D")); assertEquals("1.7976931348623157E308", adapter.marshal(Double.MAX_VALUE)); assertEquals("9.223372036854776E18", adapter.marshal(Long.MAX_VALUE)); assertEquals("-9.223372036854776E18", adapter.marshal(Long.MIN_VALUE)); }
Source:
public Handler getHandler(Config config) throws Exception { final String defaultTopic = config.getString("default_topic"); boolean propagate = false; try { propagate = config.getBoolean("propagate"); } catch (ConfigException.Missing ignored) if ("null".equals(defaultTopic)) { log.warn("default topic is \"null\"; messages will be discarded unless tagged with kt:"); } final Properties properties = new Properties(); for (Map.Entry<String, ConfigValue> kv : config.getConfig("producer_config").entrySet()) { properties.put(kv.getKey(), kv.getValue().unwrapped().toString()); } final String clientId = "plog_" + InetAddress.getLocalHost().getHostName() + "_" + KafkaProvider.clientId.getAndIncrement(); properties.put("client.id", clientId); log.info("Using producer with properties {}", properties); final ProducerConfig producerConfig = new ProducerConfig(properties); final Producer<byte[], byte[]> producer = new Producer<byte[], byte[]>(producerConfig); EncryptionConfig encryptionConfig = new EncryptionConfig(); try { Config encryption = config.getConfig("encryption"); encryptionConfig.encryptionKey = encryption.getString("key"); encryptionConfig.encryptionAlgorithm = encryption.getString("algorithm"); encryptionConfig.encryptionTransformation = encryption.getString("transformation"); encryptionConfig.encryptionProvider = encryption.getString("provider"); } catch (ConfigException.Missing ignored) { encryptionConfig = null; log.error("Read encryption config failed"); } return new KafkaHandler(clientId, propagate, defaultTopic, producer, encryptionConfig); }

Target:
public Handler getHandler(Config config) throws Exception { final String defaultTopic = config.getString("default_topic"); boolean propagate = false; try { propagate = config.getBoolean("propagate"); } catch (ConfigException.Missing ignored) if ("null".equals(defaultTopic)) { log.warn("default topic is \"null\"; messages will be discarded unless tagged with kt:"); } final Properties properties = new Properties(); for (Map.Entry<String, ConfigValue> kv : config.getConfig("producer_config").entrySet()) { properties.put(kv.getKey(), kv.getValue().unwrapped().toString()); } final String clientId = "plog_" + InetAddress.getLocalHost().getHostName() + "_" + KafkaProvider.clientId.getAndIncrement(); properties.put("client.id", clientId); log.info("Using producer with properties {}", properties); final ProducerConfig producerConfig = new ProducerConfig(properties); final Producer<byte[], byte[]> producer = new Producer<byte[], byte[]>(producerConfig); EncryptionConfig encryptionConfig = new EncryptionConfig(); try { Config encryption = config.getConfig("encryption"); encryptionConfig.encryptionKey = encryption.getString("key"); encryptionConfig.encryptionAlgorithm = encryption.getString("algorithm"); encryptionConfig.encryptionTransformation = encryption.getString("transformation"); encryptionConfig.encryptionProvider = encryption.getString("provider"); } catch (ConfigException.Missing ignored) { encryptionConfig = null; } return new KafkaHandler(clientId, propagate, defaultTopic, producer, encryptionConfig); }
Source:
private boolean isIllegalImport(String importText) { boolean result = false; if (regexp) { for (Pattern pattern : illegalPkgsRegexps) { if (pattern.matcher(importText).matches()) { result = true; } } for (Pattern pattern : illegalClassesRegexps) { if (pattern.matcher(importText).matches()) { result = true; } } } else { for (String element : illegalPkgs) { if (importText.startsWith(element + ".")) { result = true; } } for (String element : illegalClasses) { if (importText.equals(element)) { result = true; } } } return result; }

Target:
private boolean isIllegalImport(String importText) { final boolean result; if (regexp) { result = isIllegalImportByRegularExpressions(importText); } else { result = isIllegalImportByPackagesAndClassNames(importText); } return result; }
Source:
public void testCreateAnnouncementLocation() { URI baseURI = URI.create("<LINK_2>"); URI baseWithSlash = URI.create("<LINK_0>"); String nodeId = "ffff"; URI expected = URI.create("<LINK_0>v1/announcement/" + nodeId); assertEquals(expected, HttpDiscoveryAnnouncementClient.createAnnouncementLocation(baseURI, nodeId)); assertEquals(expected, HttpDiscoveryAnnouncementClient.createAnnouncementLocation(baseWithSlash, nodeId)); }

Target:
public void testCreateAnnouncementLocation() { String nodeId = "ffff"; URI expected = URI.create("<LINK_0>v1/announcement/" + nodeId); assertEquals(createAnnouncementLocation(URI.create("<LINK_2>"), nodeId), expected); assertEquals(createAnnouncementLocation(URI.create("<LINK_0>"), nodeId), expected); }
Source:
public void testInitialization() { assertNull(module.getStateSystem()); module.schedule(); assertEquals("Initialization succeeded", true, module.waitForInitialization()); assertNotNull(module.getStateSystem()); }

Target:
public void testInitialization() { assertNull(module.getStateSystem()); module.schedule(); assertTrue("Initialization succeeded", module.waitForInitialization()); assertNotNull(module.getStateSystem()); }
Source:
public void testStoreResults(@TempDir Path tempDir) { String queryId = "bb31ca4e-ed8f-4be0-a0f3-12099fb9263c"; FileResultStorageEngine engine = new FileResultStorageEngine(tempDir.toString()); AsyncQuery query = new AsyncQuery(); query.setId(queryId); engine.storeResults(query, Observable.fromArray(new String[]{"hi", "hello"})); File file = new File(tempDir.toString() + File.separator + queryId); assertTrue(file.exists()); }

Target:
public void testStoreResults(@TempDir Path tempDir) { String queryId = "store_results_success"; String validOutput = "hi\nhello"; String[] input = validOutput.split("\n"); storeResultsFile(tempDir.toString(), queryId, Observable.fromArray(input)); File file = new File(tempDir.toString() + File.separator + queryId); assertTrue(file.exists()); String finalResult = readResultsFile(tempDir.toString(), queryId); assertEquals(finalResult, validOutput); }
Source:
public void execute() { if (Config.isDevServer()) { log.info("Skipping backup in dev server."); return; } if (!Config.ENABLE_DATASTORE_BACKUP) { log.info("Skipping backup by system admin's choice."); return; } List<String> scopes = new ArrayList<>(); scopes.add("<LINK_2>"); String accessToken = AppIdentityServiceFactory.getAppIdentityService().getAccessToken(scopes).getAccessToken(); String appId = Config.getAppId(); HttpPost post = new HttpPost("<LINK_0>" + appId + ":export"); post.setHeader("Content-Type", "application/json"); post.setHeader("Authorization", "Bearer " + accessToken); Map<String, Object> body = new HashMap<>(); body.put("output_url_prefix", "gs://" + Config.GCS_BUCKETNAME + "/datastore-backups/" + Instant.now().toString()); StringEntity entity = new StringEntity(JsonUtils.toJson(body), Charset.forName("UTF-8")); post.setEntity(entity); try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse resp = client.execute(post); BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()))) { String output = br.lines().collect(Collectors.joining(System.lineSeparator())); log.info("Backup request successful:" + System.lineSeparator() + output); } catch (IOException e) { log.severe("Backup request failure: " + e.getMessage()); } }

Target:
public void execute() { if (Config.isDevServer()) { log.info("Skipping backup in dev server."); return; } if (!Config.ENABLE_DATASTORE_BACKUP) { log.info("Skipping backup by system admin's choice."); return; } List<String> scopes = new ArrayList<>(); scopes.add("<LINK_2>"); String accessToken = AppIdentityServiceFactory.getAppIdentityService().getAccessToken(scopes).getAccessToken(); String appId = Config.getAppId(); HttpPost post = new HttpPost("<LINK_0>" + appId + ":export"); post.setHeader("Content-Type", "application/json"); post.setHeader("Authorization", "Bearer " + accessToken); Map<String, Object> body = new HashMap<>(); String timestamp = Instant.now().toString(); body.put("output_url_prefix", "gs://" + Config.BACKUP_GCS_BUCKETNAME + "/datastore-backups/" + timestamp); StringEntity entity = new StringEntity(JsonUtils.toJson(body), Charset.forName("UTF-8")); post.setEntity(entity); try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse resp = client.execute(post); BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()))) { String output = br.lines().collect(Collectors.joining(System.lineSeparator())); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { log.info("Backup request successful:" + System.lineSeparator() + output); } else { log.severe("Backup request failure:" + System.lineSeparator() + output); } } catch (IOException e) { log.severe("Backup request failure: " + e.getMessage()); } }
Source:
public static Map<String, StudentResultSummary> getContribQnStudentResultSummary(FeedbackQuestionAttributes question, FeedbackSessionResultsBundle feedbackSessionResultsBundle) { Map<String, StudentResultSummary> contribQnStats = feedbackSessionResultsBundle.contributionQuestionStudentResultSummary.get(question.getId()); if (contribQnStats == null) { FeedbackContributionQuestionDetails fqcd = (FeedbackContributionQuestionDetails) question.getQuestionDetails(); contribQnStats = fqcd.getStudentResults(feedbackSessionResultsBundle, question); Map<String, StudentResultSummary> anonContribQnStats = new HashMap<>(); contribQnStats.forEach((key, studentResultSummary) -> anonContribQnStats.put( feedbackSessionResultsBundle.getAnonEmailFromStudentEmail(key), studentResultSummary)); for (Map.Entry<String, StudentResultSummary> entry : anonContribQnStats.entrySet()) { if (contribQnStats.get(entry.getKey()) == null) { contribQnStats.put(entry.getKey(), entry.getValue()); } } feedbackSessionResultsBundle.contributionQuestionStudentResultSummary.put(question.getId(), contribQnStats); } return contribQnStats; }

Target:
public static Map<String, StudentResultSummary> getContribQnStudentResultSummary(FeedbackQuestionAttributes question, FeedbackSessionResultsBundle feedbackSessionResultsBundle) { return feedbackSessionResultsBundle.contributionQuestionStudentResultSummary.computeIfAbsent( question.getId(), key -> { FeedbackContributionQuestionDetails fqcd = (FeedbackContributionQuestionDetails) question.getQuestionDetails(); Map<String, StudentResultSummary> contribQnStats = fqcd.getStudentResults(feedbackSessionResultsBundle, question); new HashMap<>(contribQnStats).forEach((contribQnStatsKey, value) -> contribQnStats.putIfAbsent( feedbackSessionResultsBundle.getAnonEmailFromStudentEmail(contribQnStatsKey), value)); return contribQnStats; } ); }
Source:
public RawIterator<Object[],ProcedureException> apply( Context ctx, Object[] input, ResourceTracker resourceTracker ) throws ProcedureException { try { int numberOfDeclaredArguments = signature.inputSignature().size(); if ( numberOfDeclaredArguments != input.length ) { throw new ProcedureException( Status.Procedure.ProcedureCallFailed, "Procedure `%s` takes %d arguments but %d was provided.", signature.name(), numberOfDeclaredArguments, input.length ); } for ( int i = 0; i < input.length; i++ ) { input[i] = signature.inputSignature().get( i ).map( input[i] ); } Object cls = constructor.invoke(); inject( ctx, cls ); Object rs = procedureMethod.invoke( cls, input ); if ( rs == null ) { return asRawIterator( emptyIterator() ); } else { return new MappingIterator( ((Stream<?>) rs).iterator(), ((Stream<?>) rs)::close, resourceTracker ); } } catch ( Throwable throwable ) { throw newProcedureException( throwable ); } }

Target:
public RawIterator<Object[],ProcedureException> apply( Context ctx, Object[] input, ResourceTracker resourceTracker ) throws ProcedureException { try { input = verifyInput( "Procedure", signature.name(), signature.inputSignature(), input ); Object cls = constructor.invoke(); inject( ctx, cls ); Object rs = procedureMethod.invoke( cls, input ); if ( rs == null ) { return asRawIterator( emptyIterator() ); } else { return new MappingIterator( ((Stream<?>) rs).iterator(), ((Stream<?>) rs)::close, resourceTracker ); } } catch ( Throwable throwable ) { throw newProcedureException( throwable ); } }
Source:
public ApiCaller(ServletContext context, PerunPrincipal perunPrincipal, PerunClient client) throws InternalErrorException { Perun perun = WebApplicationContextUtils.getWebApplicationContext(context).getBean("perun", Perun.class); PerunPrincipal rpcPrincipal = new PerunPrincipal(RPCPRINCIPAL, ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL); this.rpcSession = perun.getPerunSession(rpcPrincipal, new PerunClient()); this.tasksManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("tasksManager", TasksManager.class); this.cabinetManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("cabinetManager", CabinetManager.class); this.registrarManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("registrarManager", RegistrarManager.class); this.notificationManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("perunNotifNotificationManager", PerunNotifNotificationManager.class); this.vootManager = new VOOT(); this.scimManager = new SCIM(); this.session = perun.getPerunSession(perunPrincipal, client); }

Target:
public ApiCaller(ServletContext context, PerunPrincipal perunPrincipal, PerunClient client) throws InternalErrorException { Perun perun = WebApplicationContextUtils.getWebApplicationContext(context).getBean("perun", Perun.class); PerunPrincipal rpcPrincipal = new PerunPrincipal(RPCPRINCIPAL, ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL); this.rpcSession = perun.getPerunSession(rpcPrincipal, new PerunClient()); this.cabinetManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("cabinetManager", CabinetManager.class); this.registrarManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("registrarManager", RegistrarManager.class); this.notificationManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("perunNotifNotificationManager", PerunNotifNotificationManager.class); this.vootManager = new VOOT(); this.scimManager = new SCIM(); this.session = perun.getPerunSession(perunPrincipal, client); }