auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean rowsEqual(List<Object> expectedRow, List<Object> actualRow) { for (int i = 0; i < expectedRow.size(); ++i) { List<Object> expectedValues = expectedRow.get(i) instanceof MultiValue ? ((MultiValue) expectedRow.get(i)).getValues() : ImmutableList.of(expectedRow.get(i)); Object actualValue = actualRow.get(i); if (!valuesEqual(i, expectedValues, actualValue)) { return false; } } return true; }

Target:
private boolean rowsEqual(List<Object> expectedRow, List<Object> actualRow) { for (int i = 0; i < expectedRow.size(); ++i) { List<Object> acceptableValues = expectedRow.get(i) instanceof AcceptableValues ? ((AcceptableValues) expectedRow.get(i)).getValues() : singletonList(expectedRow.get(i)); Object actualValue = actualRow.get(i); if (!isAnyValueEqual(i, acceptableValues, actualValue)) { return false; } } return true; }
Source:
public void shouldReturnFactoryFromRepositoryWithDevfile() throws Exception { String githubUrl = "<LINK_0>"; FactoryDto computedFactory = generateDevfileFactory(); when(urlFactoryBuilder.createFactoryFromDevfile(any(RemoteFactoryUrl.class), any(), anyMap())) .thenReturn(Optional.of(computedFactory)); Map<String, String> params = new HashMap<>(); params.put(URL_PARAMETER_NAME, githubUrl); FactoryDto factory = githubFactoryParametersResolver.createFactory(params); assertNotNull(factory.getDevfile()); assertNull(factory.getWorkspace()); verify(urlFactoryBuilder) .createFactoryFromDevfile(factoryUrlArgumentCaptor.capture(), any(), anyMap()); verify(urlFactoryBuilder, never()).buildDefaultDevfile(eq("che")); assertEquals( factoryUrlArgumentCaptor.getValue().devfileFileLocation(), "<LINK_1>"); assertEquals(factoryUrlArgumentCaptor.getValue().getDevfileFilename(), "devfile.yaml"); }

Target:
public void shouldReturnFactoryFromRepositoryWithDevfile() throws Exception { String githubUrl = "<LINK_0>"; FactoryDto computedFactory = generateDevfileFactory(); when(urlFactoryBuilder.createFactoryFromDevfile(any(RemoteFactoryUrl.class), any(), anyMap())) .thenReturn(Optional.of(computedFactory)); Map<String, String> params = ImmutableMap.of(URL_PARAMETER_NAME, githubUrl); FactoryDto factory = githubFactoryParametersResolver.createFactory(params); assertNotNull(factory.getDevfile()); assertNull(factory.getWorkspace()); verify(urlFactoryBuilder) .createFactoryFromDevfile(factoryUrlArgumentCaptor.capture(), any(), anyMap()); verify(urlFactoryBuilder, never()).buildDefaultDevfile(eq("che")); assertEquals( factoryUrlArgumentCaptor.getValue().devfileFileLocation(), "<LINK_1>"); assertEquals(factoryUrlArgumentCaptor.getValue().getDevfileFilename(), "devfile.yaml"); }
Source:
public float getFloat() { if (floats[index] != null) { return floats[index]; } else { return NullHandling.ZERO_FLOAT; } }

Target:
public float getFloat() { if (floats[index] != null) { return floats[index]; } else if (NullHandling.replaceWithDefault()) { return NullHandling.ZERO_FLOAT; } else { throw new IllegalStateException("Should never be invoked when current value is null && SQL-compatible null handling is enabled!"); } }
Source:
public void removeItemWithoutTemplateTest() { NavTreeBuilder builder = new NavTreeBuilder(); LayoutTemplate lt = new LayoutTemplate("lt1"); final String ITEM = "item1"; final String ITEM_TO_REMOVE = "item2"; final String GROUP = "group"; builder.group(GROUP, GROUP, "", false); builder.item(ITEM, ITEM, "", false, NavWorkbenchCtx.perspective(lt.getName())); builder.item(ITEM_TO_REMOVE, ITEM_TO_REMOVE, "", false); builder.endGroup(); NavTree originalTree = builder.build(); assertNotNull(originalTree.getItemById(ITEM_TO_REMOVE)); List<LayoutTemplate> templates = new ArrayList<>(); templates.add(lt); NavTree runtimeTree = runtimeNavigationBuilder.buildRuntimeTree(originalTree, templates); assertEquals(1, runtimeTree.getRootItems().size()); NavGroup group = (NavGroup) runtimeTree.getItemById(GROUP); assertNotNull(group); assertEquals(1, group.getChildren().size()); assertNull(runtimeTree.getItemById(ITEM_TO_REMOVE)); assertNotNull(runtimeTree.getItemById(ITEM)); }

Target:
public void removeItemWithoutTemplateTest() { NavTreeBuilder builder = new NavTreeBuilder(); LayoutTemplate lt = new LayoutTemplate("lt1"); final String ITEM_TO_REMOVE = "item2"; builder.group(GROUP, GROUP, "", false); builder.item(ITEM, ITEM, "", false, NavWorkbenchCtx.perspective(lt.getName())); builder.item(ITEM_TO_REMOVE, ITEM_TO_REMOVE, "", false); builder.endGroup(); NavTree originalTree = builder.build(); assertNotNull(originalTree.getItemById(ITEM_TO_REMOVE)); List<LayoutTemplate> templates = new ArrayList<>(); templates.add(lt); NavTree runtimeTree = runtimeNavigationBuilder.buildRuntimeTree(originalTree, templates); assertEquals(1, runtimeTree.getRootItems().size()); NavGroup group = (NavGroup) runtimeTree.getItemById(GROUP); assertNotNull(group); assertEquals(1, group.getChildren().size()); assertNull(runtimeTree.getItemById(ITEM_TO_REMOVE)); assertNotNull(runtimeTree.getItemById(ITEM)); }
Source:
private void createRasterElevationSource() { ArrayList<String> filePaths = new ArrayList<>(); filePaths.add(Environment.getExternalStorageDirectory() + getString(R.string.raster_package_location)); try { RasterElevationSource rasterElevationSource = new RasterElevationSource(filePaths); rasterElevationSource.addLoadStatusChangedListener(loadStatusChangedEvent -> { if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.LOADED) { mSceneView.getScene().getBaseSurface().getElevationSources().add(rasterElevationSource); } else if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.FAILED_TO_LOAD) { logErrorToUser(getString(R.string.error_raster_elevation_source_load_failure_message, "")); } }); rasterElevationSource.loadAsync(); } catch (IllegalArgumentException e) { logErrorToUser(getString(R.string.error_raster_elevation_source_load_failure_message, e.getMessage())); } }

Target:
private void createRasterElevationSource() { ArrayList<String> filePaths = new ArrayList<>(); filePaths.add(Environment.getExternalStorageDirectory() + getString(R.string.raster_package_location)); try { RasterElevationSource rasterElevationSource = new RasterElevationSource(filePaths); rasterElevationSource.addLoadStatusChangedListener(loadStatusChangedEvent -> { if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.LOADED) { mSceneView.getScene().getBaseSurface().getElevationSources().add(rasterElevationSource); } else if (loadStatusChangedEvent.getNewLoadStatus() == LoadStatus.FAILED_TO_LOAD) { logErrorToUser(getString(R.string.error_raster_elevation_source_load_failure_message, rasterElevationSource.getLoadError())); } }); rasterElevationSource.loadAsync(); } catch (IllegalArgumentException e) { logErrorToUser(getString(R.string.error_raster_elevation_source_load_failure_message, e.getMessage())); } }
Source:
public boolean isClientHealthy(RawClient client) { try { client.ping(); return !client.listBuckets().isEmpty(); } catch (IOException ioe) { return false; } }

Target:
public boolean isClientHealthy(RawClient client) { try { client.ping(); return true; } catch (IOException ioe) { return false; } }
Source:
void triggerWindowProcess(List<RowData> inputs, int i, int index) throws Exception { if (windowData.isEmpty()) { if (i >= lowerBoundary) { for (int j = (int) (i - lowerBoundary); j <= i; j++) { windowData.add(inputs.get(j)); } currentBatchCount += lowerBoundary; } else { for (int j = 0; j <= i; j++) { RowData rowData = inputs.get(j); windowData.add(rowData); currentBatchCount++; } Long previousTimestamp; List<RowData> previousData; int length; long remainingDataCount = lowerBoundary - i; ListIterator<Long> iter = sortedTimestamps.listIterator(index); while (remainingDataCount > 0 && iter.hasPrevious()) { previousTimestamp = iter.previous(); previousData = inputState.get(previousTimestamp); length = previousData.size(); ListIterator<RowData> previousDataIter = previousData.listIterator(length); while (previousDataIter.hasPrevious() && remainingDataCount > 0) { windowData.addFirst(previousDataIter.previous()); remainingDataCount--; currentBatchCount++; } } } } else { if (windowData.size() > lowerBoundary) { windowData.pop(); } windowData.add(inputs.get(i)); currentBatchCount += windowData.size(); } for (RowData rowData : windowData) { arrowSerializer.write(getFunctionInput(rowData)); } invokeCurrentBatch(); }

Target:
void triggerWindowProcess(List<RowData> inputs, int i, int index) throws Exception { if (windowData.isEmpty()) { if (i >= lowerBoundary) { for (int j = (int) (i - lowerBoundary); j <= i; j++) { windowData.add(inputs.get(j)); } currentBatchCount += lowerBoundary; } else { for (int j = 0; j <= i; j++) { RowData rowData = inputs.get(j); windowData.add(rowData); currentBatchCount++; } Long previousTimestamp; List<RowData> previousData; int length; long remainingDataCount = lowerBoundary - i; ListIterator<Long> iter = sortedTimestamps.listIterator(index); while (remainingDataCount > 0 && iter.hasPrevious()) { previousTimestamp = iter.previous(); previousData = inputState.get(previousTimestamp); length = previousData.size(); ListIterator<RowData> previousDataIter = previousData.listIterator(length); while (previousDataIter.hasPrevious() && remainingDataCount > 0) { windowData.addFirst(previousDataIter.previous()); remainingDataCount--; currentBatchCount++; } } while (iter.hasPrevious()) { previousTimestamp = iter.previous(); inputState.remove(previousTimestamp); } } } else { if (windowData.size() > lowerBoundary) { windowData.pop(); } windowData.add(inputs.get(i)); currentBatchCount += windowData.size(); } for (RowData rowData : windowData) { arrowSerializer.write(getFunctionInput(rowData)); } invokeCurrentBatch(); }
Source:
public Collection<CheckMessage> getIssues(String relativePath, JavaScriptCheck check) { File file = new File(relativePath); List<Issue> issues = new ArrayList<>(); try { JavaScriptCheckContext context = TestUtils.createContext(file); issues = check.scanFile(context); } catch (RecognitionException e) { if ("ParsingErrorCheck".equals(check.getClass().getSimpleName())) { issues .add(new LineIssue(null, e.getLine(), e.getMessage())); } } return getCheckMessages(issues); }

Target:
public Collection<CheckMessage> getIssues(String relativePath, JavaScriptCheck check) { File file = new File(relativePath); List<Issue> issues = new ArrayList<>(); try { JavaScriptCheckContext context = TestUtils.createContext(file); issues = check.scanFile(context); } catch (RecognitionException e) { if (check instanceof ParsingErrorCheck) { issues.add(new LineIssue(check, e.getLine(), e.getMessage())); } } return getCheckMessages(issues); }
Source:
public String getPortalUrlForDeployment(String projectId, String releaseVersion, String environmentId, String tenantId) throws IllegalArgumentException, IOException { String urlFilter = "?take=10" + "&projects=" + projectId + "&environments=" + environmentId; if (tenantId != null && !tenantId.isEmpty()) { urlFilter += "&tenants=" + tenantId; } AuthenticatedWebClient.WebResponse response = webClient.get("deployments" + urlFilter); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); for (Object obj : json.getJSONArray("Items")) { JSONObject jsonObj = (JSONObject)obj; for (Object change : jsonObj.getJSONArray("Changes")) { String version = ((JSONObject)change).getString("Version"); if(version.equals(releaseVersion)) { JSONObject links = jsonObj.getJSONObject("Links"); return links.getString("Web"); } } } return null; }

Target:
public String getPortalUrlForDeployment(String projectId, String releaseVersion, String environmentId, String tenantId) throws IllegalArgumentException, IOException { String urlFilter = "?take=25" + "&projects=" + projectId + "&environments=" + environmentId; if (tenantId != null && !tenantId.isEmpty()) { urlFilter += "&tenants=" + tenantId; } AuthenticatedWebClient.WebResponse response = webClient.get("deployments" + urlFilter); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); for (Object obj : json.getJSONArray("Items")) { JSONObject jsonObj = (JSONObject)obj; for (Object change : jsonObj.getJSONArray("Changes")) { String version = ((JSONObject)change).getString("Version"); if(version.equals(releaseVersion)) { JSONObject links = jsonObj.getJSONObject("Links"); return links.getString("Web"); } } } return null; }
Source:
public void testTrustExtensionsIsHonored() throws PathNotFoundException { final Configuration conf = new Configuration(); assertEquals(getSamFormat(conf, "misnamedBam.sam"), SAMFormat.SAM); conf.set(AnySAMInputFormat.TRUST_EXTS_PROPERTY, "false"); final SAMFormat result = getSamFormat(conf, "misnamedBam.sam"); assertEquals(result, SAMFormat.BAM); }

Target:
public void testTrustExtensionsIsHonored() throws PathNotFoundException { final Configuration conf = new Configuration(); assertEquals(SAMFormat.SAM, getSamFormat(conf, "misnamedBam.sam")); conf.set(AnySAMInputFormat.TRUST_EXTS_PROPERTY, "false"); final SAMFormat result = getSamFormat(conf, "misnamedBam.sam"); assertEquals(SAMFormat.BAM, result); }
Source:
public void buildAndOptimizeTopology(final Properties props) { maybePerformOptimizations(props); final PriorityQueue<StreamsGraphNode> graphNodePriorityQueue = new PriorityQueue<>(5, Comparator.comparing(StreamsGraphNode::buildPriority)); graphNodePriorityQueue.offer(root); while (!graphNodePriorityQueue.isEmpty()) { final StreamsGraphNode streamGraphNode = graphNodePriorityQueue.remove(); if (LOG.isDebugEnabled()) { LOG.debug("Adding nodes to topology child nodes {}", streamGraphNode, streamGraphNode.children()); } if (streamGraphNode.allParentsWrittenToTopology() && !streamGraphNode.hasWrittenToTopology()) { streamGraphNode.writeToTopology(internalTopologyBuilder); streamGraphNode.setHasWrittenToTopology(true); } for (final StreamsGraphNode graphNode : streamGraphNode.children()) { graphNodePriorityQueue.offer(graphNode); } } internalTopologyBuilder.validateCoPartition(); }

Target:
public void buildAndOptimizeTopology(final Properties props) { maybePerformOptimizations(props); final PriorityQueue<StreamsGraphNode> graphNodePriorityQueue = new PriorityQueue<>(5, Comparator.comparing(StreamsGraphNode::buildPriority)); graphNodePriorityQueue.offer(root); while (!graphNodePriorityQueue.isEmpty()) { final StreamsGraphNode streamGraphNode = graphNodePriorityQueue.remove(); if (LOG.isDebugEnabled()) { LOG.debug("Adding nodes to topology child nodes {}", streamGraphNode, streamGraphNode.children()); } if (streamGraphNode.allParentsWrittenToTopology() && !streamGraphNode.hasWrittenToTopology()) { streamGraphNode.writeToTopology(internalTopologyBuilder); streamGraphNode.setHasWrittenToTopology(true); } for (final StreamsGraphNode graphNode : streamGraphNode.children()) { graphNodePriorityQueue.offer(graphNode); } } internalTopologyBuilder.validateCopartition(); }
Source:
public Object getPayload(CorfuRuntime runtime) { Object value = payload.get(); if (value == null) { synchronized (this.payload) { value = this.payload.get(); if (value == null) { if (data == null) { this.payload.set(null); } else { ByteBuf copyBuf = Unpooled.wrappedBuffer(data); if (hasPayloadCodec()) { ByteBuf temp = ICorfuPayload.fromBuffer(data, ByteBuf.class); byte[] temp2 = new byte[temp.readableBytes()]; temp.readBytes(temp2); copyBuf = Unpooled.wrappedBuffer(getPayloadCodecType() .getInstance().decompress(ByteBuffer.wrap(temp2))); } final Object actualValue; try { actualValue = Serializers.CORFU.deserialize(copyBuf, runtime); } catch (Throwable throwable) { log.error("Exception caught at address {}, {}, {}", getGlobalAddress(), getStreams(), getType()); log.error("Raw data buffer {}", copyBuf.resetReaderIndex().toString(Charset.defaultCharset())); copyBuf.release(); data = null; throw throwable; } if (actualValue instanceof LogEntry) { ((LogEntry) actualValue).setGlobalAddress(getGlobalAddress()); ((LogEntry) actualValue).setRuntime(runtime); } value = actualValue == null ? this.payload : actualValue; this.payload.set(value); copyBuf.release(); lastKnownSize = data.length; data = null; } } } } return value; }

Target:
public Object getPayload(CorfuRuntime runtime) { Object value = payload.get(); if (value == null) { synchronized (this.payload) { value = this.payload.get(); if (value == null) { if (data == null) { this.payload.set(null); } else { ByteBuf serializedBuf = Unpooled.wrappedBuffer(data); if (hasPayloadCodec()) { ByteBuf compressedBuf = ICorfuPayload.fromBuffer(data, ByteBuf.class); byte[] compressedArrayBuf= new byte[compressedBuf.readableBytes()]; compressedBuf.readBytes(compressedArrayBuf); serializedBuf = Unpooled.wrappedBuffer(getPayloadCodecType() .getInstance().decompress(ByteBuffer.wrap(compressedArrayBuf))); } final Object actualValue; try { actualValue = Serializers.CORFU.deserialize(serializedBuf, runtime); if (actualValue instanceof LogEntry) { ((LogEntry) actualValue).setGlobalAddress(getGlobalAddress()); ((LogEntry) actualValue).setRuntime(runtime); } value = actualValue == null ? this.payload : actualValue; this.payload.set(value); lastKnownSize = data.length; } catch (Throwable throwable) { log.error("Exception caught at address {}, {}, {}", getGlobalAddress(), getStreams(), getType()); log.error("Raw data buffer {}", serializedBuf.resetReaderIndex().toString(Charset.defaultCharset())); throw throwable; } finally { serializedBuf.release(); data = null; } } } } } return value; }
Source:
private void setupKeyEvents() { inputField.textProperty().addListener((observable, oldValue, newValue) -> { handleUpdatedInput(newValue); }); this. inputField.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.DOWN) { e.consume(); state.selectNextBestMatchingMilestone(); refreshUI(state); } if (e.getCode() == KeyCode.UP) { e.consume(); state.selectPreviousBestMatchingMilestone(); refreshUI(state); } }); }

Target:
private void setupKeyEvents() { inputField.textProperty().addListener((observable, oldValue, newValue) -> { handleUpdatedInput(newValue); }); inputField.setOnKeyPressed(e -> { switch (e.getCode()) { case DOWN: state.selectNextBestMatchingMilestone(); refreshUI(state); e.consume(); break; case UP: state.selectPreviousBestMatchingMilestone(); refreshUI(state); e.consume(); break; default: break; } }); }
Source:
public boolean visit(FunctionInvocation node) { if ((searchKind & IIndexConstants.METHOD_PATTERN) == 0) { return true; } MethodPattern methodPattern = (MethodPattern) pattern; if (!methodPattern.findReferences) { return true; } String name, superName = null; if (node.getName() != null) { name = node.getName().getIdentifier(); } else if (node.getExpression().getNodeType() == ASTNode.FIELD_ACCESS) { FieldAccess fieldAccess = (FieldAccess) node.getExpression(); name = fieldAccess.getName().getIdentifier(); if (fieldAccess.getExpression() != null && fieldAccess.getExpression().getNodeType() == ASTNode.SIMPLE_NAME) { superName = ((SimpleName) fieldAccess.getExpression()).getIdentifier(); } } else { return true; } char[] nodeName = name.toCharArray(); char[] nodeSuper; if (superName != null) { nodeSuper = superName.toCharArray(); } else { nodeSuper = contextNames.isEmpty() ? new char[0] : contextNames.peek(); } char[] patternName = methodPattern.selector; char[] patternSuper = methodPattern.getDeclaringSimpleName(); if (patternSuper != null && !CharOperation.equals(nodeSuper, patternSuper, false)) { return true; } if (matchesName(patternName, nodeName)) { IJavaScriptElement enclosingElement = getEnclosingElement(node); MethodReferenceMatch match = new MethodReferenceMatch( enclosingElement, SearchMatch.A_ACCURATE, node.getStartPosition(), node.getLength(), false, false, false, participant, rootJSUnit.getResource()); matches.add(match); } return true; }

Target:
public boolean visit(FunctionInvocation node) { anonymousNameAvailable = false; if ((searchKind & IIndexConstants.METHOD_PATTERN) == 0) { return true; } MethodPattern methodPattern = (MethodPattern) pattern; if (!methodPattern.findReferences) { return true; } String name, superName = null; if (node.getName() != null) { name = node.getName().getIdentifier(); } else if (node.getExpression() != null && node.getExpression().getNodeType() == ASTNode.FIELD_ACCESS) { FieldAccess fieldAccess = (FieldAccess) node.getExpression(); name = fieldAccess.getName().getIdentifier(); if (fieldAccess.getExpression() != null && fieldAccess.getExpression().getNodeType() == ASTNode.SIMPLE_NAME) { superName = ((SimpleName) fieldAccess.getExpression()).getIdentifier(); } } else { return true; } char[] nodeName = name.toCharArray(); char[] nodeSuper; if (superName != null) { nodeSuper = superName.toCharArray(); } else { nodeSuper = contextNames.isEmpty() ? new char[0] : contextNames.peek(); } char[] patternName = methodPattern.selector; char[] patternSuper = methodPattern.getDeclaringSimpleName(); if (patternSuper != null && !CharOperation.equals(nodeSuper, patternSuper, false)) { return true; } if (matchesName(patternName, nodeName)) { IJavaScriptElement enclosingElement = getEnclosingElement(node); MethodReferenceMatch match = new MethodReferenceMatch( enclosingElement, SearchMatch.A_ACCURATE, node.getStartPosition(), node.getLength(), false, false, false, participant, rootJSUnit.getResource()); matches.add(match); } return true; }
Source:
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final String sid = webSession.get().getToken(); final String username = webSession.get().getCurrentUser().getUserName(); final String what = "sign out"; AuditEvent record = null; final long when = System.currentTimeMillis(); try { doLogout(req, rsp); } finally { record = new AuditEvent(sid, username, what, when, null, "{\"Success\":true}"); audit.dispatch(record); } }

Target:
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final String sid = webSession.get().getToken(); final String what = "sign out"; final long when = System.currentTimeMillis(); try { doLogout(req, rsp); } finally { audit.dispatch(new AuditEvent(sid, webSession.get().getCurrentUser(), what, when, null, "{\"Success\":true}")); } }
Source:
public static void main(String[] args) throws Exception { if (args.length < 2) { throw new IllegalArgumentException("The number of arguments is incorrect. Usage:\n" + " <configuration file (conf.xml) path> <job file (.analysis.xml) path> [properties file path]\n" + "Got: " + Arrays.toString(args)); } final SparkConf conf = new SparkConf().setAppName("DataCleaner-spark"); final JavaSparkContext sparkContext = new JavaSparkContext(conf); final String confXmlPath = args[0]; final String analysisJobXmlPath = args[1]; final String propertiesPath; if (args.length > 2) { propertiesPath = args[2]; } else { propertiesPath = null; } final SparkJobContext sparkJobContext = new SparkJobContext(confXmlPath, analysisJobXmlPath, propertiesPath, sparkContext); final SparkAnalysisRunner sparkAnalysisRunner = new SparkAnalysisRunner(sparkContext, sparkJobContext); try { final AnalysisResultFuture result = sparkAnalysisRunner.run(); result.await(); if (sparkJobContext.isResultEnabled()) { final Resource resultResource = ResultFilePathUtils.getResultResource(sparkContext, sparkJobContext); logger.info("DataCleaner result will be written to: {}", resultResource); saveResult(result, resultResource); } else { logger.info("DataCleaner result will not be written - disabled"); } } finally { sparkContext.stop(); } }

Target:
public static void main(String[] args) throws Exception { if (args.length < 2) { throw new IllegalArgumentException("The number of arguments is incorrect. Usage:\n" + " <configuration file (conf.xml) path> <job file (.analysis.xml) path> [properties file path]\n" + "Got: " + Arrays.toString(args)); } final SparkConf conf = new SparkConf().setAppName("DataCleaner-spark"); final JavaSparkContext sparkContext = new JavaSparkContext(conf); final URI confXmlPath = URI.create(args[0]); final URI analysisJobXmlPath = URI.create(args[1]); final URI propertiesPath; if (args.length > 2) { propertiesPath = URI.create(args[2]); } else { propertiesPath = null; } final SparkJobContext sparkJobContext = new SparkJobContext(confXmlPath, analysisJobXmlPath, propertiesPath, sparkContext); final SparkAnalysisRunner sparkAnalysisRunner = new SparkAnalysisRunner(sparkContext, sparkJobContext); try { final AnalysisResultFuture result = sparkAnalysisRunner.run(); result.await(); if (sparkJobContext.isResultEnabled()) { final Resource resultResource = ResultFilePathUtils.getResultResource(sparkContext, sparkJobContext); logger.info("DataCleaner result will be written to: {}", resultResource); saveResult(result, resultResource); } else { logger.info("DataCleaner result will not be written - disabled"); } } finally { sparkContext.stop(); } }
Source:
private void ensureList() { if (mList != null) { return; } View root = getView(); if (root == null) { throw new IllegalStateException("Content view not yet created"); } View rawList = root.findViewById(android.R.id.list); if (mEmptyView == null) { throw new RuntimeException( "Your content must have a View whose id attribute is 'R.id.empty'"); } if (mProgressContainer == null) { throw new RuntimeException( "Your content must have a View whose id attribute is 'R.id.loading'"); } mProgressContainer.setVisibility(View.GONE); if (rawList == null) { throw new RuntimeException( "Your content must have a ListView whose id attribute is 'R.id.list'"); } if (!(rawList instanceof AdapterView)) { throw new RuntimeException( "Content has view with id attribute 'R.id.list' that is not a AbsListView class"); } mList = (AbsListView) rawList; mListShown = true; mList.setOnItemClickListener(mOnClickListener); mList.setOnScrollListener(mOnScrollListener); if (mAdapter != null) { ListAdapter adapter = mAdapter; mAdapter = null; setListAdapter(adapter); } else { if (mProgressContainer != null) { setListShown(false, false); } } mHandler.post(mRequestFocus); }

Target:
private void ensureList() { if (mList != null) { return; } View root = getView(); if (root == null) { throw new IllegalStateException("Content view not yet created"); } View rawList = root.findViewById(android.R.id.list); if (mEmptyView == null) { throw new RuntimeException( "Your content must have a View whose id attribute is 'R.id.empty'"); } if (mProgressContainer == null) { throw new RuntimeException( "Your content must have a View whose id attribute is 'R.id.loading'"); } mProgressContainer.setVisibility(View.GONE); if (rawList == null) { throw new RuntimeException( "Your content must have a ListView whose id attribute is 'R.id.list'"); } if (!(rawList instanceof AbsListView)) { throw new RuntimeException( "Content has view with id attribute 'R.id.list' that is not a AbsListView class"); } mList = (AbsListView) rawList; mListShown = true; mList.setOnItemClickListener(mOnClickListener); mList.setOnScrollListener(mOnScrollListener); if (mAdapter != null) { ListAdapter adapter = mAdapter; mAdapter = null; setListAdapter(adapter); } else { if (mProgressContainer != null) { setListShown(false, false); } } mHandler.post(mRequestFocus); }
Source:
private String extractStudentRegistrationKey(StudentAttributes student) { String joinLink = Config.getAppUrl(student.getRegistrationUrl()).toAbsoluteString(); int startIndex = joinLink.indexOf("key=") + "key=".length(); return joinLink.substring(startIndex); }

Target:
private String extractStudentRegistrationKey(StudentAttributes student) { String joinLink = Config.getAppUrl(student.getRegistrationUrl()).toAbsoluteString(); String keyParam = Const.ParamsNames.REGKEY + "="; int startIndex = joinLink.indexOf(keyParam) + keyParam.length(); return joinLink.substring(startIndex); }
Source:
private Component getComponentWithHistory(ValueResult valueResult, boolean phaseIsEnded, boolean inBanner) { if (getPermission() == PrivacyGroupPermissionEnum.NONE) { return null; } this.phaseIsEnded = phaseIsEnded; final boolean enabled = userCanPerformChangeType(ValueEventChangeType.EDIT); Component component = inBanner ? getComponentInBanner(valueResult) : getComponent(valueResult, enabled); if(getAmendable() && component instanceof Field) { final Field<?> field = (Field<?>)component; field.setFieldLabel(field.getFieldLabel() + "&nbsp;" + IconImageBundle.ICONS.DNABrownGreen().getHTML()); } if (isHistorable() && !(this instanceof BudgetElementDTO)) { if(inBanner || !(component instanceof Field)) { createHistoryMenu(component); } else { final HistoryWrapper wrapper = new HistoryWrapper((Field<?>)component); wrapper.getHistoryButton().addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { loadAndShowHistory(wrapper.getHistoryButton()); } }); if (ElementTypeEnum.CONTACT_LIST == this.getElementType() && Profiler.INSTANCE.getApplicationStateManager().getLastState() == ApplicationState.OFFLINE) { wrapper.getHistoryButton().setVisible(false); } component = wrapper; } } return component; }

Target:
private Component getComponentWithHistory(ValueResult valueResult, boolean phaseIsEnded, boolean inBanner) { if (getPermission() == PrivacyGroupPermissionEnum.NONE) { return null; } this.phaseIsEnded = phaseIsEnded; final boolean enabled = userCanPerformChangeType(ValueEventChangeType.EDIT); Component component = inBanner ? getComponentInBanner(valueResult) : getComponent(valueResult, enabled); if(getAmendable() && component instanceof Field) { final Field<?> field = (Field<?>)component; field.setFieldLabel(field.getFieldLabel() + "&nbsp;" + IconImageBundle.ICONS.DNABrownGreen().getHTML()); } if (isHistorable() && !(this instanceof BudgetElementDTO)) { if(inBanner || !(component instanceof Field)) { createHistoryMenu(component); } else { final HistoryWrapper wrapper = new HistoryWrapper((Field<?>)component); wrapper.getHistoryButton().addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { loadAndShowHistory(wrapper.getHistoryButton()); } }); if (ElementTypeEnum.CONTACT_LIST == this.getElementType() && Profiler.INSTANCE.isOfflineMode()) { wrapper.getHistoryButton().setVisible(false); } component = wrapper; } } return component; }
Source:
public static Map<String, String> getKiePMMLScorecardModelSourcesMap(final DataDictionary dataDictionary, final Scorecard model, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap, final String packageName) { logger.trace("getKiePMMLScorecardModelSourcesMap {}", dataDictionary, model, packageName); CompilationUnit cloneCU = getKiePMMLModelCompilationUnit(dataDictionary, model, fieldTypeMap, packageName, KIE_PMML_SCORECARD_MODEL_TEMPLATE_JAVA, KIE_PMML_SCORECARD_MODEL_TEMPLATE); String className = getSanitizedClassName(model.getModelName()); ClassOrInterfaceDeclaration modelTemplate = cloneCU.getClassByName(className) .orElseThrow(() -> new KiePMMLException(MAIN_CLASS_NOT_FOUND)); final ConstructorDeclaration constructorDeclaration = modelTemplate.getDefaultConstructor().orElseThrow(() -> new KiePMMLInternalException(String.format("Missing default constructor in ClassOrInterfaceDeclaration %s ", modelTemplate.getName()))); setSuperInvocation(model, constructorDeclaration, modelTemplate.getName()); Map<String, String> toReturn = new HashMap<>(); String fullClassName = packageName + "." + className; toReturn.put(fullClassName, cloneCU.toString()); return toReturn; }

Target:
public static Map<String, String> getKiePMMLScorecardModelSourcesMap(final DataDictionary dataDictionary, final Scorecard model, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap, final String packageName) { logger.trace("getKiePMMLScorecardModelSourcesMap {}", dataDictionary, model, packageName); CompilationUnit cloneCU = getKiePMMLModelCompilationUnit(dataDictionary, model, fieldTypeMap, packageName, KIE_PMML_SCORECARD_MODEL_TEMPLATE_JAVA, KIE_PMML_SCORECARD_MODEL_TEMPLATE); String className = getSanitizedClassName(model.getModelName()); ClassOrInterfaceDeclaration modelTemplate = cloneCU.getClassByName(className) .orElseThrow(() -> new KiePMMLException(MAIN_CLASS_NOT_FOUND + ": " + className)); final ConstructorDeclaration constructorDeclaration = modelTemplate.getDefaultConstructor().orElseThrow(() -> new KiePMMLInternalException(String.format("Missing default constructor in ClassOrInterfaceDeclaration %s ", modelTemplate.getName()))); setSuperInvocation(model, constructorDeclaration, modelTemplate.getName()); Map<String, String> toReturn = new HashMap<>(); String fullClassName = packageName + "." + className; toReturn.put(fullClassName, cloneCU.toString()); return toReturn; }
Source:
public static PMMLConstants byName(String name) { return Arrays.stream(PMMLConstants.values()).filter(value -> Objects.equals(name, value.name)).findFirst().orElseThrow(() -> new RuntimeException("Failed to find PMMLConstants with name: " + name)); }

Target:
public static PMMLConstants byName(String name) { return Arrays.stream(PMMLConstants.values()) .filter(getFilterPredicate(name)) .findFirst() .orElseThrow(getRuntimeExceptionSupplier(name)); }
Source:
private synchronized void asyncAuth(int cmd, Buffer buffer, boolean authed) { try { if (authed) { handleAuthenticationSuccess(cmd, buffer); } else { handleAuthenticationFailure(cmd, buffer); } } catch (Exception e) { log.warn("Error performing async authentication: {}", e.getMessage(), e); } }

Target:
protected synchronized void asyncAuth(int cmd, Buffer buffer, boolean authed) { try { if (authed) { handleAuthenticationSuccess(cmd, buffer); } else { handleAuthenticationFailure(cmd, buffer); } } catch (Exception e) { log.warn("Error performing async authentication: {}", e.getMessage(), e); } }
Source:
public Cluster get() { Clusters clusters = parent.list(); for (Cluster cluster : clusters.getClusters()) { if (cluster.getId().equals(guid.toString())) { return cluster; } } return notFound(); }

Target:
public Cluster get() { Cluster cluster = parent.getClusterById(id); if (cluster == null) { return notFound(); } return cluster; }
Source:
public void before() { Whitebox.setInternalState(lawJournalEntry, "id", 114); lawJournalEntry.setYear(2011); lawJournalEntry.setEntry(11); lawJournalEntry.setEntry(1); lawJournalEntry.setTitle("Title title"); when(lawJournalEntryRepository.findOneByYearAndEntry(Mockito.eq(lawJournalEntry.getYear()), Mockito.eq(lawJournalEntry.getEntry()))).thenReturn(lawJournalEntry); lawJournalEntryCreator.setLawJournalEntryRepository(lawJournalEntryRepository); }

Target:
public void before() { Whitebox.setInternalState(lawJournalEntry, "id", 114); lawJournalEntry.setYear(2011); lawJournalEntry.setJournalNo(11); lawJournalEntry.setEntry(1); lawJournalEntry.setTitle("Title title"); when(lawJournalEntryRepository.findOneByYearAndEntry(Mockito.eq(lawJournalEntry.getYear()), Mockito.eq(lawJournalEntry.getEntry()))).thenReturn(lawJournalEntry); lawJournalEntryCreator.setLawJournalEntryRepository(lawJournalEntryRepository); }
Source:
public KeyboardShortcutsApi produce() { if (WindowRef.isEnvelopeAvailable()) { return new KeyboardShortcutsService(); } DomGlobal.console.info("[KeyboardShortcutsServiceProducer] Envelope API is not available. Producing NoOpKeyboardShortcutsService"); return new NoOpKeyboardShortcutsService(); }

Target:
public KeyboardShortcutsApi produce() { if (WindowRef.isEnvelopeAvailable()) { return new KeyboardShortcutsService(); } DomGlobal.console.debug("[KeyboardShortcutsServiceProducer] Envelope API is not available. Producing NoOpKeyboardShortcutsService"); return new NoOpKeyboardShortcutsService(); }
Source:
OnkyoConnection getConnection() { if (connection == null) { if (serialPortName!=null) connection = new OnkyoConnection(serialPortName); else connection = new OnkyoConnection(host, port); } return connection; }

Target:
OnkyoConnection getConnection() { if (connection == null) { if (serialPortName != null) { connection = new OnkyoConnection(serialPortName); } else { connection = new OnkyoConnection(host, port); } } return connection; }
Source:
public long length() throws IOException { String response = executeCommand("SIZE\r\n"); long currAvailSize = Long.parseLong(response.substring(0, response.indexOf(' '))); currTotalSize = Long.parseLong(response.substring(response.indexOf(' ') + 1)); maxRemoteSize = Math.max(maxRemoteSize, currAvailSize); if (currAvailSize != currTotalSize) { activeFile = true; } return maxRemoteSize; }

Target:
public long length() throws IOException { if (maxRemoteSize == 0 || activeFile) { return reallyGetLength(); } return maxRemoteSize; }
Source:
public Map<Field, List<GraphQLDirective>> getImmediateDirectivesByField() { computeValuesLazily(); return new LinkedHashMap<>(fieldDirectivesMap); }

Target:
public Map<Field, List<GraphQLDirective>> getImmediateDirectivesByField() { computeValuesLazily(); return fieldDirectivesByField; }
Source:
public static InspectorModulesProvider defaultInspectorModulesProvider(final Context context) { return new InspectorModulesProvider() { @Override public Iterable<ChromeDevtoolsDomain> get() { ArrayList<ChromeDevtoolsDomain> modules = new ArrayList<ChromeDevtoolsDomain>(); modules.add(new Console()); modules.add(new CSS()); modules.add(new Debugger()); modules.add(new DOM(new DOMProvider.Factory() { @Override public DOMProvider create() { return new AndroidDOMProvider((Application)context.getApplicationContext()); } })); modules.add(new DOMStorage()); modules.add(new HeapProfiler()); modules.add(new Inspector()); modules.add(new Network(context)); modules.add(new Page(context)); modules.add(new Profiler()); modules.add(new Runtime()); modules.add(new Worker()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { modules.add(new Database(context)); } return modules; } }; }

Target:
public static InspectorModulesProvider defaultInspectorModulesProvider(final Context context) { return new InspectorModulesProvider() { @Override public Iterable<ChromeDevtoolsDomain> get() { ArrayList<ChromeDevtoolsDomain> modules = new ArrayList<ChromeDevtoolsDomain>(); modules.add(new Console()); modules.add(new CSS()); modules.add(new Debugger()); modules.add(new DOM(new AndroidDOMProviderFactory((Application)context.getApplicationContext()))); modules.add(new DOMStorage()); modules.add(new HeapProfiler()); modules.add(new Inspector()); modules.add(new Network(context)); modules.add(new Page(context)); modules.add(new Profiler()); modules.add(new Runtime()); modules.add(new Worker()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { modules.add(new Database(context)); } return modules; } }; }
Source:
public void testDeleteIdempotency() throws Exception { org.junit.Assume.assumeTrue(DEFAULT_DELETE_CONSIDERED_IDEMPOTENT); AbfsConfiguration abfsConfig = getConfiguration(); abfsConfig.setMaxIoRetries(reducedRetryCount); abfsConfig.setMaxBackoffIntervalMilliseconds(reducedMaxBackoffIntervalMs); final AzureBlobFileSystem fs = getFileSystem(); AbfsClient abfsClient = fs.getAbfsStore().getClient(); AbfsPerfTracker tracker = new AbfsPerfTracker("test", this.getAccountName(), abfsConfig); AbfsClient testClient = new AbfsClient( abfsClient.getBaseUrl(), new SharedKeyCredentials(abfsConfig.getAccountName().substring(0, abfsConfig.getAccountName().indexOf(DOT)), abfsConfig.getStorageAccountKey()), abfsConfig, new ExponentialRetryPolicy(reducedRetryCount), abfsConfig.getTokenProvider(), tracker); AbfsRestOperation op = mock(AbfsRestOperation.class); when(op.getRetryCount()).thenReturn(reducedRetryCount); AbfsHttpOperation http404Op = mock(AbfsHttpOperation.class); when(http404Op.getStatusCode()).thenReturn(HTTP_NOT_FOUND); when(op.getResult()).thenReturn(http404Op); assertTrue( "Delete is considered idempotent by default and should return success.", (testClient.deleteIdempotencyCheckOp(op) .getResult() .getStatusCode() == HTTP_OK)); }

Target:
public void testDeleteIdempotency() throws Exception { Assume.assumeTrue(DEFAULT_DELETE_CONSIDERED_IDEMPOTENT); AbfsConfiguration abfsConfig = TestAbfsConfigurationFieldsValidation.updateRetryConfigs( getConfiguration(), REDUCED_RETRY_COUNT, REDUCED_MAX_BACKOFF_INTERVALS_MS); final AzureBlobFileSystem fs = getFileSystem(); AbfsClient abfsClient = fs.getAbfsStore().getClient(); AbfsClient testClient = TestAbfsClient.createTestClientFromCurrentContext( abfsClient, abfsConfig); AbfsRestOperation op = mock(AbfsRestOperation.class); when(op.isARetriedRequest()).thenReturn(true); AbfsHttpOperation http404Op = mock(AbfsHttpOperation.class); when(http404Op.getStatusCode()).thenReturn(HTTP_NOT_FOUND); when(op.getResult()).thenReturn(http404Op); Assertions.assertThat(testClient.deleteIdempotencyCheckOp(op) .getResult() .getStatusCode()) .describedAs( "Delete is considered idempotent by default and should return success.") .isEqualTo(HTTP_OK); }
Source:
public SnapshotStatus[] getSnapshotListing(Path snapshotRoot) throws IOException { return dfs.getSnapshotListing(getPathName(snapshotRoot)); }

Target:
public SnapshotStatus[] getSnapshotListing(Path snapshotRoot) throws IOException { Path absF = fixRelativePart(snapshotRoot); statistics.incrementReadOps(1); storageStatistics .incrementOpCounter(OpType.GET_SNAPSHOT_LIST); return dfs.getSnapshotListing(getPathName(absF)); }
Source:
protected boolean shouldProcessSAELineToPDP(ConcurStandardAccountingExtractDetailLine line) { boolean isCashLine = StringUtils.equalsIgnoreCase(line.getPaymentCode(), ConcurConstants.PAYMENT_CODE_CASH); boolean isPersonalExpeseChargedToCorporateCard = getConcurBatchUtilityService().lineRepresentsPersonalExpenseChargedToCorporateCard(line); boolean isCreditLine = StringUtils.equalsIgnoreCase(line.getJounalDebitCredit(), ConcurConstants.CREDIT); return isCashLine || (isPersonalExpeseChargedToCorporateCard && isCreditLine); }

Target:
protected boolean shouldProcessSAELineToPDP(ConcurStandardAccountingExtractDetailLine line) { boolean isCashLine = StringUtils.equalsIgnoreCase(line.getPaymentCode(), ConcurConstants.PAYMENT_CODE_CASH); boolean isPersonalExpenseChargedToCorporateCard = getConcurBatchUtilityService().lineRepresentsPersonalExpenseChargedToCorporateCard(line); boolean isCreditLine = StringUtils.equalsIgnoreCase(line.getJounalDebitCredit(), ConcurConstants.CREDIT); return isCashLine || (isPersonalExpenseChargedToCorporateCard && isCreditLine); }
Source:
public void testDisabledOutputPaging() throws Exception { setupConsole(false); consoleWriter.println("/:read-resource"); Assert.assertFalse(consoleWriter.checkError()); String window = queue.poll(15, TimeUnit.SECONDS); Assert.assertNotNull(window); checkWithRegex(window, promptPattern); Assert.assertTrue(Pattern.compile("^\\{.*^\\}", Pattern.MULTILINE | Pattern.DOTALL) .matcher(window).find()); }

Target:
private void testDisabledOutputPaging() throws Exception { consoleWriter.println("/subsystem=elytron:read-resource-description(recursive=true)"); Assert.assertFalse(consoleWriter.checkError()); String window = queue.poll(10, TimeUnit.SECONDS); Assert.assertNotNull(window); checkWithRegex(window, promptPattern); Assert.assertTrue(Pattern.compile("^\\{.*^\\}", Pattern.MULTILINE | Pattern.DOTALL) .matcher(window).find()); }
Source:
public void move() { spriteBase.move(); Double newX = spriteBase.getX() + spriteBase.getDx(); Double newY = spriteBase.getY() + spriteBase.getDy(); if (!newX.equals(spriteBase.getX()) || !newY.equals(spriteBase.getY())) { Logger.log(String.format("Monster moved from (%f, %f) to (%f, %f)", spriteBase.getX(), spriteBase.getY(), newX, newY)); } this.setChanged(); this.notifyObservers(); }

Target:
public void move() { spriteBase.move(); Double newX = spriteBase.getX() + spriteBase.getDx(); Double newY = spriteBase.getY() + spriteBase.getDy(); if (!newX.equals(spriteBase.getX()) || !newY.equals(spriteBase.getY())) { Logger.log(String.format("Monster moved from (%f, %f) to (%f, %f)", spriteBase.getX(), spriteBase.getY(), newX, newY)); } }
Source:
private TableMetadataPersistence.SweepStrategy getStrategyFromKvs(TableReference tableRef) { return TableMetadata.BYTES_HYDRATOR.hydrateFromBytes(kvs.getMetadataForTable(tableRef)).getSweepStrategy(); }

Target:
private TableMetadataPersistence.SweepStrategy getStrategyFromKvs(TableReference tableRef) { try { return TableMetadata.BYTES_HYDRATOR.hydrateFromBytes(kvs.getMetadataForTable(tableRef)).getSweepStrategy(); } catch (Throwable th) { log.warn("Failed to obtain sweep strategy for table {}. Assuming sweep strategy is CONSERVATIVE.", UnsafeArg.of("tableRef", tableRef), th); return TableMetadataPersistence.SweepStrategy.CONSERVATIVE; } }
Source:
public void test_cost() { TestPythonCheck check = new TestPythonCheck (){ @Override public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, ctx -> { PyFunctionDefTree pyFunctionDefTree = (PyFunctionDefTree) ctx.syntaxNode(); PyNameTree name = pyFunctionDefTree.name(); ctx.addIssue(name.astNode().getToken(), MESSAGE).withCost(42); }); } }; List<PreciseIssue> issues = scanFileForIssues(FILE, check); PreciseIssue firstIssue = issues.get(0); assertThat(firstIssue.cost()).isEqualTo(42); }

Target:
public void test_cost() { TestPythonCheck check = new TestPythonCheck (){ @Override public void visitFunctionDef(PyFunctionDefTree pyFunctionDefTree) { super.visitFunctionDef(pyFunctionDefTree); PyNameTree name = pyFunctionDefTree.name(); addIssue(name.astNode().getToken(), MESSAGE).withCost(42); } }; List<PreciseIssue> issues = scanFileForIssues(FILE, check); PreciseIssue firstIssue = issues.get(0); assertThat(firstIssue.cost()).isEqualTo(42); }
Source:
private void reset() { allHistograms.forEach(AbstractHistogram::reset); }

Target:
private void reset() { allHistograms.forEach(Histogram::reset); }
Source:
public static Boolean checkIfUserOwns(final Tool tool,final HttpClient client, final ObjectMapper objectMapper, final TokenDAO tokenDAO, final long userId) { List<Token> tokens = tokenDAO.findByUserId(userId); Token quayToken = extractToken(tokens, TokenType.QUAY_IO.toString()); if (tool.getRegistry() == Registry.QUAY_IO && quayToken == null) { LOG.info("WARNING: QUAY.IO token not found!"); throw new CustomWebApplicationException("A valid Quay.io token is required to add this tool.", HttpStatus.SC_BAD_REQUEST); } QuayImageRegistry factory = new QuayImageRegistry(client, objectMapper, quayToken); String quayUsername = quayToken.getUsername(); Map<String,Object> map = factory.getQuayInfo(tool); if (map != null){ String namespace = map.get("namespace").toString(); boolean isOrg = (Boolean)map.get("is_organization"); if (isOrg) { List<String> namespaces = factory.getNamespaces(); for(String nm : namespaces) { if (nm.equals(namespace)) { return true; } return false; } } else { return (namespace.equals(quayUsername) && !isOrg); } } return false; }

Target:
public static boolean checkIfUserOwns(final Tool tool,final HttpClient client, final ObjectMapper objectMapper, final TokenDAO tokenDAO, final long userId) { List<Token> tokens = tokenDAO.findByUserId(userId); Token quayToken = extractToken(tokens, TokenType.QUAY_IO.toString()); if (tool.getRegistry() == Registry.QUAY_IO && quayToken == null) { LOG.info("WARNING: QUAY.IO token not found!"); throw new CustomWebApplicationException("A valid Quay.io token is required to add this tool.", HttpStatus.SC_BAD_REQUEST); } QuayImageRegistry factory = new QuayImageRegistry(client, objectMapper, quayToken); String quayUsername = quayToken.getUsername(); Map<String,Object> map = factory.getQuayInfo(tool); if (map != null){ String namespace = map.get("namespace").toString(); boolean isOrg = (Boolean)map.get("is_organization"); if (isOrg) { List<String> namespaces = factory.getNamespaces(); for(String nm : namespaces) { if (nm.equals(namespace)) { return true; } return false; } } else { return (namespace.equals(quayUsername)); } } return false; }
Source:
public RoomModel voteSong(@PathParam("id") final int roomId, @PathParam("vote") final String vote) throws InvalidVoteException { final RoomInstance roomInstance = this.backend.getRoomInstance(roomId); if ("like".equals(vote) || "dislike".equals(vote)) { roomInstance.addVote(currentUserProvider.get(), Vote.valueOf(vote.toUpperCase())); } else { throw new InvalidVoteException(); } return transform(roomInstance); }

Target:
public RoomModel voteSong(@PathParam("id") final int roomId, @PathParam("vote") final String vote) { final RoomInstance roomInstance = this.backend.getRoomInstance(roomId); Vote voteValue = Vote.valueOf(vote.toUpperCase()); roomInstance.addVote(currentUserProvider.get(), voteValue); return transform(roomInstance); }