auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void getAllCsvAttributeDescriptors() { Set<String> hiddenFields = new HashSet<>(); hiddenFields.add("attribute1"); Set<AttributeDescriptor> allAttributes = CsvTransformer.getAllCsvAttributeDescriptors(metacardList); assertThat(allAttributes, hasSize(5)); Set<String> allAttributeNames = allAttributes.stream().map(AttributeDescriptor::getName).collect(Collectors.toSet()); final Set<String> expectedAttributes = Sets.newHashSet("attribute2", "attribute3", "attribute4", "attribute5", "attribute6"); assertThat(allAttributeNames, is(expectedAttributes)); }

Target:
public void getAllCsvAttributeDescriptors() { Set<AttributeDescriptor> allAttributes = CsvTransformer.getAllCsvAttributeDescriptors(metacardList); assertThat(allAttributes, hasSize(6)); Set<String> allAttributeNames = allAttributes.stream().map(AttributeDescriptor::getName).collect(Collectors.toSet()); final Set<String> expectedAttributes = Sets.newHashSet( "attribute1", "attribute2", "attribute3", "attribute4", "attribute5", "attribute6"); assertThat(allAttributeNames, is(expectedAttributes)); }
Source:
public MemberSearchRequestBuilder filterBySet(String setId) { return addOption(OptionKey.SET, setId); }

Target:
public MemberSearchRequestBuilder filterBySet(String setId) { return filterBySets(ImmutableSet.of(setId)); }
Source:
public void targetMemberIsSetIfMemberOptionsIsUsed() { QueryCommand spyCommand = spy(command); DistributedMember member = mock(DistributedMember.class); String query = "select query"; String memberName = "member"; doReturn(member).when(spyCommand).getMember(memberName); doReturn(mock(DataCommandResult.class)).when(spyCommand).select(query, member); spyCommand.query(query, null, false, memberName); verify(spyCommand).select(query, member); }

Target:
public void targetMemberIsSetIfMemberOptionsIsUsed() { DistributedMember member = mock(DistributedMember.class); String query = "select query"; String memberName = "member"; doReturn(member).when(spyCommand).getMember(memberName); doReturn(mock(DataCommandResult.class)).when(spyCommand).select(query, member); spyCommand.query(query, null, false, memberName); verify(spyCommand).select(query, member); }
Source:
public GsonConverter(Gson gson, Charset charset) { this.gson = gson; this.charset = charset; this.mediaType = MediaType.parse("application/json; charset=" + charset.name()); }

Target:
public GsonConverter(Gson gson, Charset charset) { if (gson == null) throw new NullPointerException("gson == null"); if (charset == null) throw new NullPointerException("charset == null"); this.gson = gson; this.charset = charset; this.mediaType = MediaType.parse("application/json; charset=" + charset.name()); }
Source:
public static int verifyTally(String testLabels, EMap<String, LabelInfo> labels) { int state = 0, prevState; if (labels != null && labels.get(testLabels) != null) { for (Map.Entry<String, LabelInfo> entry : labels.entrySet()) { if (entry.getKey() != null && entry.getKey().compareTo(testLabels) == 0) { LabelInfo labelInfo = entry.getValue(); if (labelInfo.getAll() != null) { for (ApprovalInfo it : labelInfo.getAll()) { if (it.getValue() != null) { prevState = state; state = Utils.getStateValue(it.getValue(), state); if (testLabels.compareTo(CODE_REVIEW) == 0) { if (state <= -1) { if (state < prevState) { state = Math.min(state, prevState); } } else if (state >= 1) { if (state > prevState && !(prevState < 0)) { state = Math.max(state, prevState); } else if (prevState < state) { state = prevState; } } } } } } } } } return state; }

Target:
public static int verifyTally(String testLabels, EMap<String, LabelInfo> labels) { int state = 0, prevState; if (labels == null) { return state; } LabelInfo labelInfo = labels.get(testLabels); if (labelInfo == null) { return state; } if (labelInfo.getAll() != null) { for (ApprovalInfo it : labelInfo.getAll()) { if (it.getValue() != null) { prevState = state; state = Utils.getStateValue(it.getValue(), state); if (testLabels.compareTo(CODE_REVIEW) == 0) { if (state <= -1) { if (state < prevState) { state = Math.min(state, prevState); } } else if (state >= 1) { if (state > prevState && !(prevState < 0)) { state = Math.max(state, prevState); } else if (prevState < state) { state = prevState; } } } } } } return state; }
Source:
public Raster readRaster(int frameIndex, ImageReadParam param) throws IOException { readMetadata(); checkIndex(frameIndex); Raster raster; try (ImageInputStream iisOfFrame = iisOfFrame( frameIndex)) { if (decompressor != null) { decompressor.setInput(iisOfFrame); if (LOG.isDebugEnabled()) LOG.debug("Start decompressing frame #" + (frameIndex + 1)); raster = pmi.decompress() == pmi && decompressor.canReadRaster() ? decompressor.readRaster(0, decompressParam(param)) : decompressor.read(0, decompressParam(param)).getRaster(); if (LOG.isDebugEnabled()) LOG.debug("Finished decompressing frame #" + (frameIndex + 1)); } else { WritableRaster wr = Raster.createWritableRaster(createSampleModel(dataType, banded), null); DataBuffer buf = wr.getDataBuffer(); if (buf instanceof DataBufferByte) { byte[][] data = ((DataBufferByte) buf).getBankData(); for (byte[] bs : data) { System.out.printf("Filling buffer of size %s from %s with offset %s and remaining %s", bs.length, iisOfFrame.toString(), iisOfFrame.getStreamPosition(), iisOfFrame.length() - iisOfFrame.getStreamPosition()); iisOfFrame.readFully(bs); } if (this.metadata.getPixelDataVR() == VR.OW && bigEndian()) { ByteUtils.swapShorts(data); } } else { short[] data = ((DataBufferUShort) buf).getData(); iisOfFrame.readFully(data, 0, data.length); } raster = wr; } } return raster; }

Target:
public Raster readRaster(int frameIndex, ImageReadParam param) throws IOException { readMetadata(); checkIndex(frameIndex); Raster raster; try (ImageInputStream iisOfFrame = iisOfFrame( frameIndex)) { if (decompressor != null) { decompressor.setInput(iisOfFrame); LOG.debug("Start decompressing frame # {}", (frameIndex + 1)); PhotometricInterpretation pmi = getAccessor().getPhotometricInterpretation(); raster = pmi.decompress() == pmi && decompressor.canReadRaster() ? decompressor.readRaster(0, decompressParam(param)) : decompressor.read(0, decompressParam(param)).getRaster(); if (LOG.isDebugEnabled()) LOG.debug("Finished decompressing frame #" + (frameIndex + 1)); } else { WritableRaster wr = Raster.createWritableRaster(createSampleModel(getAccessor().getDataType(), getAccessor().isBanded()), null); DataBuffer buf = wr.getDataBuffer(); if (buf instanceof DataBufferByte) { byte[][] data = ((DataBufferByte) buf).getBankData(); for (byte[] bs : data) { LOG.debug("Filling buffer of size from with offset and remaining {}", bs.length, iisOfFrame.toString(), iisOfFrame.getStreamPosition(), iisOfFrame.length() - iisOfFrame.getStreamPosition()); iisOfFrame.readFully(bs); } if (getAccessor().isSwapShortsRequired()) { ByteUtils.swapShorts(data); } } else { short[] data = ((DataBufferUShort) buf).getData(); iisOfFrame.readFully(data, 0, data.length); } raster = wr; } } return raster; }
Source:
void fillPolygonInPixels (int[] pointArray) { if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); checkGC(FILL); if (data.gdipGraphics != 0) { int mode = OS.GetPolyFillMode(handle) == OS.WINDING ? Gdip.FillModeWinding : Gdip.FillModeAlternate; Gdip.Graphics_TranslateTransform(data.gdipGraphics, data.gdipXOffset + 1, data.gdipYOffset, Gdip.MatrixOrderPrepend); Gdip.Graphics_FillPolygon(data.gdipGraphics, data.gdipBrush, pointArray, pointArray.length / 2, mode); Gdip.Graphics_TranslateTransform(data.gdipGraphics, -(data.gdipXOffset + 1), -data.gdipYOffset, Gdip.MatrixOrderPrepend); return; } if ((data.style & SWT.MIRRORED) != 0) { for (int i = 0; i < pointArray.length; i+=2) { pointArray[i]--; } } OS.Polygon(handle, pointArray, pointArray.length / 2); if ((data.style & SWT.MIRRORED) != 0) { for (int i = 0; i < pointArray.length; i+=2) { pointArray[i]++; } } }

Target:
void fillPolygonInPixels (int[] pointArray) { if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); checkGC(FILL); if (data.gdipGraphics != 0) { int mode = OS.GetPolyFillMode(handle) == OS.WINDING ? Gdip.FillModeWinding : Gdip.FillModeAlternate; float offsetCorrection = 0.5f; Gdip.Graphics_TranslateTransform(data.gdipGraphics, data.gdipXOffset + offsetCorrection, data.gdipYOffset + offsetCorrection, Gdip.MatrixOrderPrepend); Gdip.Graphics_FillPolygon(data.gdipGraphics, data.gdipBrush, pointArray, pointArray.length / 2, mode); Gdip.Graphics_TranslateTransform(data.gdipGraphics, -(data.gdipXOffset + offsetCorrection), -(data.gdipYOffset + offsetCorrection), Gdip.MatrixOrderPrepend); return; } if ((data.style & SWT.MIRRORED) != 0) { for (int i = 0; i < pointArray.length; i+=2) { pointArray[i]--; } } OS.Polygon(handle, pointArray, pointArray.length / 2); if ((data.style & SWT.MIRRORED) != 0) { for (int i = 0; i < pointArray.length; i+=2) { pointArray[i]++; } } }
Source:
public RangePublisherTest() { super(new TestEnvironment(25)); }

Target:
public RangePublisherTest() { super(new TestEnvironment()); }
Source:
public void process(Region region, EntityBuffer buffer) { if (region.getRegion().encompasses(0, 64, 24)) { Prefab chooseFactionNpc = Assets.getPrefab("LightAndShadow:MagicFool").get(); EntityStore entity = new EntityStore(chooseFactionNpc); entity.addComponent(new LocationComponent(new Vector3f(0, 61, 24))); buffer.enqueue(entity); Prefab beaconMark = Assets.getPrefab("BeaconMark").get(); EntityStore entityStore = new EntityStore(beaconMark); entityStore.addComponent(new LocationComponent(new Vector3f(0, 63, 24))); entityStore.addComponent(new NetworkComponent()); buffer.enqueue(entityStore); } }

Target:
public void process(Region region, EntityBuffer buffer) { if (region.getRegion().encompasses(0, 64, 24)) { Prefab chooseFactionNpc = Assets.getPrefab("LightAndShadow:MagicFool").get(); EntityStore entity = new EntityStore(chooseFactionNpc); entity.addComponent(new LocationComponent(new Vector3f(0, 61, 24))); buffer.enqueue(entity); Prefab beaconMark = Assets.getPrefab("BeaconMark").get(); EntityStore entityStore = new EntityStore(beaconMark); entityStore.addComponent(new LocationComponent(new Vector3f(0, 63, 24))); buffer.enqueue(entityStore); } }
Source:
public static void addServiceProvider (IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException { ASTNode node= problem.getCoveredNode(context.getASTRoot()); if (! (node instanceof Name) && ! (node.getParent() instanceof ProvidesDirective)) { return; } Name name= (Name) node; ProvidesDirective prov= (ProvidesDirective) name.getParent(); ITypeBinding targetBinding= name.resolveTypeBinding(); ITypeBinding serviceBinding= prov.getName().resolveTypeBinding(); if (targetBinding != null && serviceBinding != null) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), context.getASTRoot(), targetBinding); IJavaProject proj= context.getCompilationUnit().getJavaProject(); IType type= proj.findType(serviceBinding.getQualifiedName()); ITypeHierarchy th= type.newTypeHierarchy(null); IType[] subTypes= th.getAllSubtypes(type); List<IType> typeProposals= new ArrayList<> (Arrays.asList(type)); typeProposals.addAll(Arrays.asList(subTypes)); Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); for (IType t : typeProposals) { if (proj.findType(t.getFullyQualifiedName()) != null && Flags.isPublic(t.getFlags())) { proposals.add(new NewProviderMethodDeclaration( Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_add_provider_method_description, t.getElementName()), targetCU, context.getASTRoot(), targetBinding, IProposalRelevance.CREATE_METHOD, image, t.getElementName())); } } } }

Target:
public static void addServiceProvider (IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException { ASTNode node= problem.getCoveredNode(context.getASTRoot()); if (! (node instanceof Name) && ! (node.getParent() instanceof ProvidesDirective)) { return; } Name name= (Name) node; ProvidesDirective prov= (ProvidesDirective) name.getParent(); ITypeBinding targetBinding= name.resolveTypeBinding(); ITypeBinding serviceBinding= prov.getName().resolveTypeBinding(); if (targetBinding != null && serviceBinding != null) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), context.getASTRoot(), targetBinding); IJavaProject proj= context.getCompilationUnit().getJavaProject(); IType type= proj.findType(serviceBinding.getQualifiedName()); ITypeHierarchy th= type.newTypeHierarchy(proj, null); IType[] subTypes= th.getAllSubtypes(type); List<IType> typeProposals= new ArrayList<> (Arrays.asList(type)); typeProposals.addAll(Arrays.asList(subTypes)); Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); for (IType t : typeProposals) { proposals.add(new NewProviderMethodDeclaration( Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_add_provider_method_description, t.getElementName()), targetCU, context.getASTRoot(), targetBinding, IProposalRelevance.CREATE_METHOD, image, t)); } } }
Source:
public ExecTransformationProfile(ProfileCallback callback, ProfileContext context, TransformationService service) { this.service = service; this.callback = callback; Object paramFunction = context.getConfiguration().get(FUNCTION_PARAM); Object paramSource = context.getConfiguration().get(SOURCE_FORMAT_PARAM); logger.debug("Profile configured with '{}'='{}', '{}'={}", FUNCTION_PARAM, paramFunction, SOURCE_FORMAT_PARAM, paramSource); if (paramSource == null) { paramSource = "%s"; } if (paramFunction instanceof String && paramSource instanceof String) { function = (String) paramFunction; sourceFormat = (String) paramSource; } else { logger.warn("Parameter '{}' and '{}' have to be Strings. Profile will be inactive.", FUNCTION_PARAM, SOURCE_FORMAT_PARAM); function = null; sourceFormat = null; } }

Target:
public ExecTransformationProfile(ProfileCallback callback, ProfileContext context, TransformationService service) { this.service = service; this.callback = callback; Object paramFunction = context.getConfiguration().get(FUNCTION_PARAM); Object paramSource = context.getConfiguration().get(SOURCE_FORMAT_PARAM); logger.debug("Profile configured with '{}'='{}', '{}'={}", FUNCTION_PARAM, paramFunction, SOURCE_FORMAT_PARAM, paramSource); if (paramSource == null) { paramSource = "%s"; } if (paramFunction instanceof String && paramSource instanceof String) { function = (String) paramFunction; sourceFormat = (String) paramSource; } else { logger.error("Parameter '{}' and '{}' have to be Strings. Profile will be inactive.", FUNCTION_PARAM, SOURCE_FORMAT_PARAM); function = null; sourceFormat = null; } }
Source:
public void processDeviceChange(UUID idOfRequestingUser, UUID relatedUserAnonymizedId, DeviceChange change, UUID deviceAnonymizedId, Optional<String> oldName, Optional<String> newName) { User user = userService.getValidatedUserbyId(idOfRequestingUser); Buddy buddy = user.getBuddyByUserAnonymizedId(relatedUserAnonymizedId); switch (change) { case ADD: addDeviceToBuddy(buddy, deviceAnonymizedId, newName.get()); break; case RENAME: updateDeviceNameForToBuddy(buddy, deviceAnonymizedId, newName.get()); break; case DELETE: removeDeviceFromBuddy(buddy, deviceAnonymizedId); break; default: throw new IllegalArgumentException("Change " + change + " is unknown"); } }

Target:
public void processDeviceChange(UUID idOfRequestingUser, UUID relatedUserAnonymizedId, DeviceChange change, UUID deviceAnonymizedId, Optional<String> oldName, Optional<String> newName) { User user = userService.getValidatedUserById(idOfRequestingUser); Buddy buddy = user.getBuddyByUserAnonymizedId(relatedUserAnonymizedId); switch (change) { case ADD: addDeviceToBuddy(buddy, deviceAnonymizedId, newName.get()); break; case RENAME: updateDeviceNameForToBuddy(buddy, deviceAnonymizedId, newName.get()); break; case DELETE: removeDeviceFromBuddy(buddy, deviceAnonymizedId); break; default: throw new IllegalArgumentException("Change " + change + " is unknown"); } }
Source:
public static void main(String[] args) { DataGenerator generator = new DataGenerator(new Configuration()); if (args.length < 1) { System.err.println("Please specify a command (generate VERSION|cleanup)."); System.exit(1); } String command = args[0]; if (command.equalsIgnoreCase("generate")) { if (args.length < 2 || args.length > 3) { System.err.println("Usage: generate VERSION [-randomData]\n"); System.err.println("Options:"); System.err.println(" VERSION Use a specific parquet file version to generate data."); System.err.println(" - v1 for PARQUET_1_0 version."); System.err.println(" - v2 for PARQUET_2_0 version."); System.err.println(" -randomData This flag specifies if random data will be used to generate data."); System.err.println(" By default, only 1 random row is generated, and repeated across the file."); System.exit(1); } String parquetVersion = args[1]; if (args.length == 3 && args[2].equalsIgnoreCase("-randomData")) { generator.initializeRandomSampleData(RANDOM_SAMPLE_ROWS); } else { System.err.println("Unknown option: " + args[2]); System.exit(1); } generator.setWriterVersion(WriterVersion.fromString(parquetVersion)); generator.generateAll(); } else if (command.equalsIgnoreCase("cleanup")) { generator.cleanup(); } else { throw new IllegalArgumentException("invalid command " + command); } }

Target:
public static void main(String[] args) { DataGenerator generator = new DataGenerator(new Configuration()); if (args.length < 1) { System.err.println("Please specify a command (generate VERSION [-randomData]|cleanup)."); System.exit(1); } String command = args[0]; if (command.equalsIgnoreCase("generate")) { if (args.length < 2 || args.length > 3) { System.err.println("Usage: generate VERSION [-randomData]\n"); System.err.println("Options:"); System.err.println(" VERSION Use a specific parquet file version to generate data."); System.err.println(" - v1 for PARQUET_1_0 version."); System.err.println(" - v2 for PARQUET_2_0 version."); System.err.println(" -randomData This flag specifies if random data will be used to generate data."); System.err.println(" By default, only 1 random row is generated, and repeated across the file."); System.exit(1); } String parquetVersion = args[1]; if (args.length == 3) { if (args[2].equalsIgnoreCase("-randomData")) { generator.initializeRandomSampleData(RANDOM_SAMPLE_ROWS); } else { System.err.println("Unknown option: " + args[2]); System.exit(1); } } generator.setWriterVersion(WriterVersion.fromString(parquetVersion)); generator.generateAll(); } else if (command.equalsIgnoreCase("cleanup")) { generator.cleanup(); } else { throw new IllegalArgumentException("invalid command " + command); } }
Source:
private static List<ColumnReference> matchIndexExpression(RelationalOperator relOp, InListOperatorNode inNode, boolean isIn, boolean isProbe, ValueNode indexExprAst, Optimizable optTable) throws StandardException { CollectNodesVisitor cnv = new CollectNodesVisitor(ColumnReference.class); int tableNumber = optTable.getTableNumber(); if (isIn) { if (inNode.getLeftOperand().equals(indexExprAst)) { inNode.getLeftOperand().accept(cnv); if (isProbe) { assert relOp instanceof BinaryOperatorNode; BinaryOperatorNode binOp = (BinaryOperatorNode) relOp; binOp.setMatchIndexExpr(tableNumber, true); } } } else { if (relOp instanceof BinaryOperatorNode) { BinaryOperatorNode binOp = (BinaryOperatorNode) relOp; if (binOp.getLeftOperand().equals(indexExprAst)) { binOp.getLeftOperand().accept(cnv); binOp.setMatchIndexExpr(tableNumber, true); } else if (binOp.getRightOperand().equals(indexExprAst)) { binOp.getRightOperand().accept(cnv); binOp.setMatchIndexExpr(tableNumber, false); } } else if (relOp instanceof IsNullNode) { IsNullNode isNull = (IsNullNode) relOp; if (isNull.getOperand().equals(indexExprAst)) { isNull.getOperand().accept(cnv); } } } return cnv.getList(); }

Target:
private static boolean matchIndexExpression(RelationalOperator relOp, InListOperatorNode inNode, boolean isIn, boolean isProbe, ValueNode indexExprAst, Optimizable optTable) { boolean match = false; int tableNumber = optTable.getTableNumber(); if (isIn) { if (inNode.getLeftOperand().semanticallyEquals(indexExprAst)) { match = true; if (isProbe) { assert relOp instanceof BinaryOperatorNode; BinaryOperatorNode binOp = (BinaryOperatorNode) relOp; binOp.setMatchIndexExpr(tableNumber, true); } } } else { if (relOp instanceof BinaryOperatorNode) { BinaryOperatorNode binOp = (BinaryOperatorNode) relOp; if (binOp.getLeftOperand().semanticallyEquals(indexExprAst)) { match = true; binOp.setMatchIndexExpr(tableNumber, true); } else if (binOp.getRightOperand().semanticallyEquals(indexExprAst)) { match = true; binOp.setMatchIndexExpr(tableNumber, false); } } else if (relOp instanceof IsNullNode) { IsNullNode isNull = (IsNullNode) relOp; if (isNull.getOperand().semanticallyEquals(indexExprAst)) { match = true; } } } return match; }
Source:
public void testCompositeBlobGetSuccess() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize * 6 + 11, null); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); BlobInfo blobInfo = router.getBlobInfo(blobId).get(); Assert.assertTrue("Blob properties should match", RouterTestHelpers.haveEquivalentFields(putBlobProperties, blobInfo.getBlobProperties())); Assert.assertArrayEquals("User metadata should match", putUserMetadata, blobInfo.getUserMetadata()); getBlobAndCompareContent(blobId); router.close(); }

Target:
public void testCompositeBlobGetSuccess() throws Exception { testGetSuccess(chunkSize * 6 + 11, null); }
Source:
public void initialize(String blobProviderId, Map<String, String> properties) throws IOException { super.initialize(blobProviderId, properties); this.properties = properties; if (StringUtils.isNotBlank(properties.get(SERVER_PROPERTY)) || StringUtils.isNotBlank(properties.get(DBNAME_PROPERTY))) { throw new NuxeoException("Unable to initialize GridFS Binary Manager, properties " + SERVER_PROPERTY + " and " + DBNAME_PROPERTY + " has been removed. Please configure a connection!"); } String bucket = properties.get(BUCKET_PROPERTY); if (StringUtils.isBlank(bucket)) { bucket = blobProviderId + ".fs"; } MongoDBConnectionService mongoService = Framework.getService(MongoDBConnectionService.class); MongoDatabase database = mongoService.getDatabase("blobProvider/" + blobProviderId); gridFSBucket = GridFSBuckets.create(database, bucket); filesColl = database.getCollection(bucket + ".files"); garbageCollector = new GridFSBinaryGarbageCollector(bucket); }

Target:
public void initialize(String blobProviderId, Map<String, String> properties) throws IOException { super.initialize(blobProviderId, properties); this.properties = properties; if (StringUtils.isNotBlank(properties.get(SERVER_PROPERTY)) || StringUtils.isNotBlank(properties.get(DBNAME_PROPERTY))) { throw new NuxeoException("Unable to initialize GridFS Binary Manager, properties " + SERVER_PROPERTY + " and " + DBNAME_PROPERTY + " has been removed. Please configure a connection!"); } String bucket = properties.get(BUCKET_PROPERTY); if (StringUtils.isBlank(bucket)) { bucket = blobProviderId + ".fs"; } MongoDBConnectionService mongoService = Framework.getService(MongoDBConnectionService.class); MongoDatabase database = mongoService.getDatabase(BLOB_PROVIDER_CONNECTION_PREFIX + blobProviderId); gridFSBucket = GridFSBuckets.create(database, bucket); filesColl = database.getCollection(bucket + ".files"); garbageCollector = new GridFSBinaryGarbageCollector(bucket); }
Source:
protected void runApplication(String[] args) throws Exception { LOG.info("Running 'run-application' command."); final Options commandOptions = CliFrontendParser.getRunCommandOptions(); final CommandLine commandLine = getCommandLine(commandOptions, args, true); if (commandLine.hasOption(HELP_OPTION.getOpt())) { CliFrontendParser.printHelpForRun(customCommandLines); return; } final CustomCommandLine activeCommandLine = validateAndGetActiveCommandLine(checkNotNull(commandLine)); ProgramOptions programOptions; if (ProgramOptionsUtils.isPythonEntryPoint(commandLine)) { programOptions = ProgramOptionsUtils.createPythonApplicationProgramOptions(commandLine); } else { programOptions = new ProgramOptions(commandLine); } final ApplicationDeployer deployer = new ApplicationClusterDeployer(clusterClientServiceLoader); programOptions.validate(); final URI uri = PackagedProgramUtils.resolveURI(programOptions.getJarFilePath()); final Configuration effectiveConfiguration = getEffectiveConfiguration( activeCommandLine, commandLine, programOptions, Collections.singletonList(uri.toString())); final ApplicationConfiguration applicationConfiguration = new ApplicationConfiguration(programOptions.getProgramArgs(), programOptions.getEntryPointClassName()); deployer.run(effectiveConfiguration, applicationConfiguration); }

Target:
protected void runApplication(String[] args) throws Exception { LOG.info("Running 'run-application' command."); final Options commandOptions = CliFrontendParser.getRunCommandOptions(); final CommandLine commandLine = getCommandLine(commandOptions, args, true); if (commandLine.hasOption(HELP_OPTION.getOpt())) { CliFrontendParser.printHelpForRun(customCommandLines); return; } final CustomCommandLine activeCommandLine = validateAndGetActiveCommandLine(checkNotNull(commandLine)); final ApplicationDeployer deployer = new ApplicationClusterDeployer(clusterClientServiceLoader); final ProgramOptions programOptions; final Configuration effectiveConfiguration; if (ProgramOptionsUtils.isPythonEntryPoint(commandLine)) { programOptions = ProgramOptionsUtils.createPythonProgramOptions(commandLine); effectiveConfiguration = getEffectiveConfiguration( activeCommandLine, commandLine, programOptions, Collections.emptyList()); } else { programOptions = new ProgramOptions(commandLine); programOptions.validate(); final URI uri = PackagedProgramUtils.resolveURI(programOptions.getJarFilePath()); effectiveConfiguration = getEffectiveConfiguration( activeCommandLine, commandLine, programOptions, Collections.singletonList(uri.toString())); } final ApplicationConfiguration applicationConfiguration = new ApplicationConfiguration(programOptions.getProgramArgs(), programOptions.getEntryPointClassName()); deployer.run(effectiveConfiguration, applicationConfiguration); }
Source:
private void writeVoidPromise(ChannelHandlerContext ctx, CodecOutputList out) { final ChannelPromise voidPromise = ctx.voidPromise(); for (int i = 0; i < out.size(); i++) { ctx.write(out.getUnsafe(i), voidPromise); } }

Target:
private static void writeVoidPromise(ChannelHandlerContext ctx, CodecOutputList out) { final ChannelPromise voidPromise = ctx.voidPromise(); for (int i = 0; i < out.size(); i++) { ctx.write(out.getUnsafe(i), voidPromise); } }
Source:
public String getColumnText(Object element, XViewerColumn column, int columnIndex) { try { if (element instanceof Artifact) { Collection<IUserGroupArtifactToken> userGroups = UserGroupService.getUserGrps(); if (userGroups.isEmpty()) { return ""; } String strUserGroupsOut = ""; for (IUserGroupArtifactToken usr : userGroups) { strUserGroupsOut += usr.getName().substring(usr.getName().indexOf("[")) + ", "; } return strUserGroupsOut.substring(0, strUserGroupsOut.length() - 2); } else { return ""; } } catch (OseeCoreException ex) { return LogUtil.getCellExceptionString(ex); } }

Target:
public String getColumnText(Object element, XViewerColumn column, int columnIndex) { try { if (element instanceof User) { Collection<Artifact> userGroups = ((User) element).getRelatedArtifacts(CoreRelationTypes.Users_Artifact); if (userGroups.isEmpty()) { return ""; } String strUserGroupsOut = ""; for (Artifact usr : userGroups) { strUserGroupsOut += usr.toStringWithId() + ", "; } return strUserGroupsOut.substring(0, strUserGroupsOut.length() - 2); } else { return ""; } } catch (OseeCoreException ex) { return LogUtil.getCellExceptionString(ex); } }
Source:
private void showMenu() { if (mNavigationView != null) { final int accountCount = AccountManager.get(this) .getAccountsByType(MainApp.getAccountType()).length; if (mIsAccountChooserActive) { mAccountChooserToggle.setImageResource(R.drawable.ic_up); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, true); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_standard, false); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_settings_etc, false); if(mDrawerCloud != null && accountCount > 4) mDrawerCloud.setVisibility(View.GONE); } else { mAccountChooserToggle.setImageResource(R.drawable.ic_down); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, false); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_standard, true); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_settings_etc, true); if(mDrawerCloud != null) mDrawerCloud.setVisibility(View.VISIBLE); } } }

Target:
private void showMenu() { if (mNavigationView != null) { final int accountCount = AccountManager.get(this) .getAccountsByType(MainApp.getAccountType()).length; if (mIsAccountChooserActive) { mAccountChooserToggle.setImageResource(R.drawable.ic_up); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, true); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_standard, false); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_settings_etc, false); if(mDrawerCloud != null && accountCount > USER_ITEMS_ALLOWD_BEFORE_REMOVING_CLOUD) mDrawerCloud.setVisibility(View.GONE); } else { mAccountChooserToggle.setImageResource(R.drawable.ic_down); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, false); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_standard, true); mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_settings_etc, true); if(mDrawerCloud != null) mDrawerCloud.setVisibility(View.VISIBLE); } } }
Source:
public void should_not_explode_if_bad_json_response() throws Exception { eslintBridgeServer = createEslintBridgeServer("badResponse.js"); eslintBridgeServer.deploy(); eslintBridgeServer.startServerLazily(context); DefaultInputFile inputFile = TestInputFileBuilder.create("foo", "foo.js") .setContents("alert('Fly, you fools!')") .build(); EslintBridgeServer.AnalysisRequest request = new EslintBridgeServer.AnalysisRequest(inputFile, new EslintBridgeServer.Rule[0]); eslintBridgeServer.call(request); assertThat(logTester.logs(LoggerLevel.ERROR).get(0)).startsWith("Failed to parse: \n" + "-----\n" + "Invalid response\n" + "-----\n"); assertThat(context.allIssues()).isEmpty(); }

Target:
public void should_not_explode_if_bad_json_response() throws Exception { eslintBridgeServer = createEslintBridgeServer("badResponse.js"); eslintBridgeServer.deploy(); eslintBridgeServer.startServerLazily(context); DefaultInputFile inputFile = TestInputFileBuilder.create("foo", "foo.js") .setContents("alert('Fly, you fools!')") .build(); AnalysisRequest request = new AnalysisRequest(inputFile, new Rule[0]); EslintBridgeServer.AnalysisResponse response = eslintBridgeServer.analyzeJavaScript(request); assertThat(response.issues).isEmpty(); assertThat(logTester.logs(LoggerLevel.ERROR).get(0)).startsWith("Failed to parse: \n" + "-----\n" + "Invalid response\n" + "-----\n"); assertThat(context.allIssues()).isEmpty(); }
Source:
public Element caseAssociation(Association association) { if (isReconnectable(association)) { if (RECONNECT_SOURCE == reconnectKind) { if (association.getMemberEnds().size() > 2) { final String sourceObject = edgeToReconnect.getSourceNode().toString(); final List<Property> members = association.getMemberEnds(); for (final Property member : members) { final String typeName = member.getType().getName(); if (sourceObject.contains(typeName)) { member.setType((Type)newPointedElement); } } } else { final Property source = AssociationServices.INSTANCE.getSource(association); source.setType((Type)newPointedElement); } } else { final Property target = AssociationServices.INSTANCE.getTarget(association); target.setType((Type)newPointedElement); } } return association; }

Target:
public Element caseAssociation(Association association) { if (isReconnectable(association)) { if (RECONNECT_SOURCE == reconnectKind) { if (association.getMemberEnds().size() > 2) { final Property end = AssociationServices.INSTANCE.getSourceEndAssociation(association, edgeToReconnect); end.setType((Type)newPointedElement); } else { final Property source = AssociationServices.INSTANCE.getSource(association); source.setType((Type)newPointedElement); } } else { final Property target = AssociationServices.INSTANCE.getTarget(association); target.setType((Type)newPointedElement); } } return association; }
Source:
public ArrayList<Integer> sample_value_use_binomial() { BinomialDistribution binom = null; int cur = 0; double cdf = 0; ArrayList<Integer> result = new ArrayList<Integer>(k); for (int i = 0; i < k - 1; i++) { if (n == cur) { result.add(0); continue; } binom = new BinomialDistribution(n - cur, p[i] / (1.0 - cdf)); int x = binom.sample(); cur += x; cdf += p[i]; result.add(x); } result.add(n - cur); return result; }

Target:
private ArrayList<Integer> sample_value_use_binomial() { BinomialDistribution binom = null; int cur = 0; double cdf = 0; ArrayList<Integer> result = new ArrayList<Integer>(k); for (int i = 0; i < k - 1; i++) { if (n == cur) { result.add(0); continue; } binom = new BinomialDistribution(n - cur, p[i] / (1.0 - cdf)); int x = binom.sample(); cur += x; cdf += p[i]; result.add(x); } result.add(n - cur); return result; }
Source:
protected JdbcConnectionOptions(String url, String driverName, String username, String password, int connectionCheckTimeoutSeconds) { this.url = Preconditions.checkNotNull(url, "jdbc url is empty"); this.driverName = Preconditions.checkNotNull(driverName, "driver name is empty"); this.username = username; this.password = password; this.connectionCheckTimeoutSeconds = connectionCheckTimeoutSeconds; }

Target:
protected JdbcConnectionOptions(String url, String driverName, String username, String password, int connectionCheckTimeoutSeconds) { Preconditions.checkArgument(connectionCheckTimeoutSeconds > 0); this.url = Preconditions.checkNotNull(url, "jdbc url is empty"); this.driverName = Preconditions.checkNotNull(driverName, "driver name is empty"); this.username = username; this.password = password; this.connectionCheckTimeoutSeconds = connectionCheckTimeoutSeconds; }
Source:
public void execute(IProgressMonitor monitor) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { List<IResource> allFiles = new ArrayList<IResource>(); for (IResource res : files) { allFiles.addAll(getAllMembers(res)); } for (IResource res : allFiles) { Repository repo = getRepository(res); if (repo == null) { IStatus status = Activator.error( CoreText.DiscardChangesOperation_repoNotFound, null); throw new CoreException(status); } discardChange(res, repo, monitor); } } }; ResourcesPlugin.getWorkspace().run(action, monitor); }

Target:
public void execute(IProgressMonitor monitor) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { discardChanges(monitor); } }; ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); }
Source:
private static AccountDiffPreference initAccountDiffPreferences( AccountDiffPreference a, DiffPreferencesInfo i, Account.Id id) { if (a == null) { a = AccountDiffPreference.createDefault(id); } int context = i.context == null ? DiffPreferencesInfo.DEFAULT_CONTEXT : i.context; a.setContext((short)context); a.setExpandAllComments(b(i.expandAllComments)); a.setHideLineNumbers(b(i.hideLineNumbers)); a.setHideTopMenu(b(i.hideTopMenu)); a.setIgnoreWhitespace(Whitespace.forCode( PatchListKey.WHITESPACE_TYPES.get(i.ignoreWhitespace))); a.setIntralineDifference(b(i.intralineDifference)); a.setLineLength(i.lineLength == null ? 100 : i.lineLength); a.setManualReview(i.manualReview); a.setRenderEntireFile(b(i.renderEntireFile)); a.setRetainHeader(b(i.retainHeader)); a.setShowLineEndings(b(i.showLineEndings)); a.setShowTabs(b(i.showTabs)); a.setShowWhitespaceErrors(b(i.showWhitespaceErrors)); a.setSkipDeleted(b(i.skipDeleted)); a.setSkipUncommented(b(i.skipUncommented)); a.setSyntaxHighlighting(b(i.syntaxHighlighting)); a.setTabSize(i.tabSize == null ? 8 : i.tabSize); a.setTheme(i.theme); a.setHideEmptyPane(b(i.hideEmptyPane)); a.setAutoHideDiffTableHeader(b(i.autoHideDiffTableHeader)); return a; }

Target:
private static AccountDiffPreference initAccountDiffPreferences( AccountDiffPreference a, DiffPreferencesInfo i, Account.Id id) { if (a == null) { a = AccountDiffPreference.createDefault(id); } int context = i.context == null ? DiffPreferencesInfo.DEFAULT_CONTEXT : i.context; a.setContext((short)context); a.setExpandAllComments(b(i.expandAllComments)); a.setHideLineNumbers(b(i.hideLineNumbers)); a.setHideTopMenu(b(i.hideTopMenu)); a.setIgnoreWhitespace(Whitespace.forCode( PatchListKey.WHITESPACE_TYPES.get(i.ignoreWhitespace))); a.setIntralineDifference(b(i.intralineDifference)); a.setLineLength(i.lineLength == null ? DiffPreferencesInfo.DEFAULT_LINE_LENGTH : i.lineLength); a.setManualReview(i.manualReview); a.setRenderEntireFile(b(i.renderEntireFile)); a.setRetainHeader(b(i.retainHeader)); a.setShowLineEndings(b(i.showLineEndings)); a.setShowTabs(b(i.showTabs)); a.setShowWhitespaceErrors(b(i.showWhitespaceErrors)); a.setSkipDeleted(b(i.skipDeleted)); a.setSkipUncommented(b(i.skipUncommented)); a.setSyntaxHighlighting(b(i.syntaxHighlighting)); a.setTabSize(i.tabSize == null ? DiffPreferencesInfo.DEFAULT_TAB_SIZE : i.tabSize); a.setTheme(i.theme); a.setHideEmptyPane(b(i.hideEmptyPane)); a.setAutoHideDiffTableHeader(b(i.autoHideDiffTableHeader)); return a; }
Source:
public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<? extends T> attributeType) { if ( renderers==null ) { return null; } return renderers.get(attributeType); }

Target:
public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<? extends T> attributeType) { if ( renderers==null ) { return null; } return (AttributeRenderer<? super T>) renderers.get(attributeType); }
Source:
public String getCacheName(boolean useFullDepName) { if (useFullDepName) { if (!StringUtils.isEmpty(group)) { return group + "--" + name + "--" + String.valueOf(version) + "." + packaging; } else { return name + "." + depFile.getName(); } } else { return depFile.getName(); } }

Target:
public String getCacheName(boolean useFullDepName) { if (useFullDepName) { if (!StringUtils.isEmpty(group)) { return group + CACHE_DELIMITER + name + CACHE_DELIMITER + String.valueOf(version) + "." + packaging; } else { return name + "." + depFile.getName(); } } else { return depFile.getName(); } }
Source:
public CRAMFileReader(File file, InputStream is, ReferenceSource referenceSource) { this.file = file; this.is = is; this.referenceSource = referenceSource; counter++; if (counter % 1000 == 0) System.err.println("open cram files: " + counter); if (file == null) getIterator(); }

Target:
public CRAMFileReader(File file, InputStream is, ReferenceSource referenceSource) { if (file == null && is == null) throw new NullPointerException( "Either file or input stream is required."); this.file = file; this.is = is; this.referenceSource = referenceSource; getIterator(); }
Source:
public void pushExportBuffer( final long startSequenceNumber, final long committedSequenceNumber, final int tupleCount, final long uniqueId, final long genId, final ByteBuffer buffer) { try { m_bufferPushPermits.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (m_closed) { exportLog.error("Closed: ignoring export buffer with " + tupleCount + " rows"); return; } try { m_es.execute((new Runnable() { @Override public void run() { try { if (!m_closed) { pushExportBufferImpl(startSequenceNumber, committedSequenceNumber, tupleCount, uniqueId, genId, buffer, m_readyForPolling); } else { exportLog.error("Closed: ignoring export buffer with " + tupleCount + " rows"); } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error pushing export buffer", true, t); } finally { m_bufferPushPermits.release(); } } })); } catch (RejectedExecutionException rej) { m_bufferPushPermits.release(); exportLog.info("Export buffer rejected by data source executor: ", rej); } }

Target:
public void pushExportBuffer( final long startSequenceNumber, final long committedSequenceNumber, final int tupleCount, final long uniqueId, final long genId, final ByteBuffer buffer) { try { m_bufferPushPermits.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (m_closed) { exportLogLimited.log("Closed: ignoring export buffer with " + tupleCount + " rows", EstTime.currentTimeMillis()); return; } try { m_es.execute((new Runnable() { @Override public void run() { try { if (!m_closed) { pushExportBufferImpl(startSequenceNumber, committedSequenceNumber, tupleCount, uniqueId, genId, buffer, m_readyForPolling); } else { exportLogLimited.log("Closed: ignoring export buffer with " + tupleCount + " rows", EstTime.currentTimeMillis()); } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error pushing export buffer", true, t); } finally { m_bufferPushPermits.release(); } } })); } catch (RejectedExecutionException rej) { m_bufferPushPermits.release(); exportLog.info("Export buffer rejected by data source executor: ", rej); } }
Source:
public boolean hasActiveEntitlementPools(Owner o, Date date) { if (o == null) { return false; } if (date == null) { date = new Date(); } Criteria crit = createSecureCriteria(); crit.add(Restrictions.eq("activeSubscription", Boolean.TRUE)); crit.add(Restrictions.eq("owner", o)); crit.add(Restrictions.le("startDate", date)); crit.add(Restrictions.ge("endDate", date)); crit.setProjection(Projections.rowCount()); long count = (Long) crit.list().get(0); return count > 0; }

Target:
public boolean hasActiveEntitlementPools(Owner o, Date date) { if (o == null) { return false; } if (date == null) { date = new Date(); } Criteria crit = createSecureCriteria(); crit.add(Restrictions.eq("activeSubscription", Boolean.TRUE)); crit.add(Restrictions.eq("owner", o)); crit.add(Restrictions.le("startDate", date)); crit.add(Restrictions.ge("endDate", date)); crit.setProjection(Projections.rowCount()); long count = (Long) crit.uniqueResult(); return count > 0; }
Source:
public void partActivated(IWorkbenchPart part) { if (part == AbstractTimeGraphView.this) { synchronized (FIND_ACTION) { if (fFindActionHandler == null) { fFindActionHandler = new ActionHandler(FIND_ACTION); } final Object service = PlatformUI.getWorkbench().getService(IHandlerService.class); ((IHandlerService) service).deactivateHandler(fFindHandlerActivation); fFindHandlerActivation = ((IHandlerService) service).activateHandler(ActionFactory.FIND.getCommandId(), fFindActionHandler); } } FIND_ACTION.partActivated(part); }

Target:
public void partActivated(IWorkbenchPart part) { if (part == AbstractTimeGraphView.this) { synchronized (FIND_ACTION) { if (fFindActionHandler == null) { fFindActionHandler = new ActionHandler(FIND_ACTION); } if (fFindHandlerActivation == null) { final Object service = PlatformUI.getWorkbench().getService(IHandlerService.class); fFindHandlerActivation = ((IHandlerService) service).activateHandler(ActionFactory.FIND.getCommandId(), fFindActionHandler); } } } FIND_ACTION.partActivated(part); }
Source:
public void openTaskSelectionScreen(OpenUpgradeScreenEvent event, EntityRef player) { this.upgradeScreenLayer = nuiManager.createScreen("buildingUpgradeScreen"); nuiManager.pushScreen(this.upgradeScreenLayer); }

Target:
public void openTaskSelectionScreen(OpenUpgradeScreenEvent event, EntityRef player) { this.upgradeScreenLayer = nuiManager.createScreen(Constants.BUILDING_UPGRADE_SCREEN_URI); nuiManager.pushScreen(this.upgradeScreenLayer); }
Source:
public void testGetCoursesForInstructor() throws Exception { restoreTypicalDataInDatastore(); ______TS("success: instructor with present courses"); String instructorId = getTypicalDataBundle().accounts.get("instructor3").googleId; List<CourseAttributes> courses = coursesLogic.getCoursesForInstructor(instructorId); assertEquals(2, courses.size()); ______TS("fail: instructor without any courses"); instructorId = getTypicalDataBundle().accounts.get("instructorWithoutCourses").googleId; courses = coursesLogic.getCoursesForInstructor(instructorId); assertEquals(0, courses.size()); }

Target:
public void testGetCoursesForInstructor() throws Exception { restoreTypicalDataInDatastore(); ______TS("success: instructor with present courses"); String instructorId = getTypicalDataBundle().accounts.get("instructor3").googleId; List<CourseAttributes> courses = coursesLogic.getCoursesForInstructor(instructorId); assertEquals(2, courses.size()); ______TS("boundary: instructor without any courses"); instructorId = getTypicalDataBundle().accounts.get("instructorWithoutCourses").googleId; courses = coursesLogic.getCoursesForInstructor(instructorId); assertEquals(0, courses.size()); }
Source:
protected UnifyResult apply(UnifyRuleCall call) { final MutableSort query = (MutableSort) call.query; final MutableSort target = (MutableSort) call.target; final MutableProject queryProject = (MutableProject) query.getInput(); final MutableProject targetProject = (MutableProject) target.getInput(); if (!queryProject.getInput().equals(targetProject.getInput())) { return null; } if (query.fetch != null || query.offset != null || target.fetch != null || target.offset != null) { return null; } Mappings.TargetMapping queryProjectMapping = queryProject.getMapping(); Mappings.TargetMapping targetProjectMapping = targetProject.getMapping(); if (queryProjectMapping == null || targetProjectMapping == null) { return null; } final int queryFieldCount = query.rowType.getFieldCount(); final int targetFieldCount = target.rowType.getFieldCount(); Mappings.TargetMapping mapping = Mappings.create( MappingType.FUNCTION, queryFieldCount, targetFieldCount); List<Integer> posList = new ArrayList<>(); for (int ordinal = 0; ordinal < queryFieldCount; ordinal++) { int inputOrdinal = queryProjectMapping.getSourceOpt(ordinal); assert inputOrdinal >= 0; int targetOrdinal = targetProjectMapping.getTargetOpt(inputOrdinal); if (targetOrdinal < 0) { return null; } mapping.set(ordinal, targetOrdinal); posList.add(targetOrdinal); } RelCollation collation = RelCollations.permute(query.collation, mapping); if (!target.collation.satisfies(collation)) { return null; } MutableRel result = MutableRels.createProject(target, posList); return call.result(result); }

Target:
protected UnifyResult apply(UnifyRuleCall call) { final MutableSort query = (MutableSort) call.query; final MutableSort target = (MutableSort) call.target; final MutableProject queryProject = (MutableProject) query.getInput(); final MutableProject targetProject = (MutableProject) target.getInput(); if (!queryProject.getInput().equals(targetProject.getInput())) { return null; } if (!Objects.equals(query.fetch, target.fetch) || !Objects.equals(query.offset, target.offset)) { return null; } Mappings.TargetMapping queryProjectMapping = queryProject.getMapping(); Mappings.TargetMapping targetProjectMapping = targetProject.getMapping(); if (queryProjectMapping == null || targetProjectMapping == null) { return null; } final int queryFieldCount = query.rowType.getFieldCount(); final int targetFieldCount = target.rowType.getFieldCount(); Mappings.TargetMapping mapping = Mappings.create( MappingType.FUNCTION, queryFieldCount, targetFieldCount); List<Integer> posList = new ArrayList<>(); for (int ordinal = 0; ordinal < queryFieldCount; ordinal++) { int inputOrdinal = queryProjectMapping.getSourceOpt(ordinal); assert inputOrdinal >= 0; int targetOrdinal = targetProjectMapping.getTargetOpt(inputOrdinal); if (targetOrdinal < 0) { return null; } mapping.set(ordinal, targetOrdinal); posList.add(targetOrdinal); } RelCollation collation = RelCollations.permute(query.collation, mapping); if (!target.collation.satisfies(collation)) { return null; } MutableRel result = MutableRels.createProject(target, posList); return call.result(result); }