Performs a single-input/single-output dither operation, applying basic
Floyd-Steinberg error-diffusion to the image.

@param pSource
@param pDest

@return the destination raster, or a new raster, if {@code pDest} was
{@code null}.
967352
public final WritableRaster filter(final Raster pSource, WritableRaster pDest) {
        return filter(pSource, pDest, getICM(pSource));
    }
1024091
private void readImageResources(final boolean pParseData) throws IOException {
        readHeader();

        if (pParseData && metadata.imageResources == null || metadata.layerAndMaskInfoStart == 0) {
            imageInput.seek(metadata.imageResourcesStart);

            long imageResourcesLength = imageInput.readUnsignedInt();

            if (pParseData && metadata.imageResources == null && imageResourcesLength > 0) {
                long expectedEnd = imageInput.getStreamPosition() + imageResourcesLength;
                metadata.imageResources = new ArrayList<>();

                while (imageInput.getStreamPosition() < expectedEnd) {
                    PSDImageResource resource = PSDImageResource.read(imageInput);
                    metadata.imageResources.add(resource);
                }

                if (DEBUG) {
                    System.out.println("imageResources: " + metadata.imageResources);
                }

                if (imageInput.getStreamPosition() != expectedEnd) {
                    throw new IIOException("Corrupt PSD document"); // ..or maybe just a bug in the reader.. ;-)
                }
            }

            // TODO: We should now be able to flush input
//                imageInput.flushBefore(metadata.imageResourcesStart + imageResourcesLength + 4);

            metadata.layerAndMaskInfoStart = metadata.imageResourcesStart + imageResourcesLength + 4; // + 4 for the length field itself
        }
    }
1090105
public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }
252511
protected CoverageDataSourcePixel getYSourceMinAndMax(float source) {

		int floor = (int) Math.floor(source);
		float valueLocation = getYEncodedLocation(floor,
				griddedCoverage.getGridCellEncodingType());

		CoverageDataSourcePixel pixel = getSourceMinAndMax(source, floor,
				valueLocation);
		return pixel;
	}
549794
public static BufferedImage renderBinary(GrayU8 binaryImage, boolean invert, BufferedImage out) {

		if( out == null || ( out.getWidth() != binaryImage.width || out.getHeight() != binaryImage.height) ) {
			out = new BufferedImage(binaryImage.getWidth(),binaryImage.getHeight(),BufferedImage.TYPE_BYTE_GRAY);
		}

		try {
			WritableRaster raster = out.getRaster();
			DataBuffer buffer = raster.getDataBuffer();
			if( buffer.getDataType() == DataBuffer.TYPE_BYTE ) {
				renderBinary(binaryImage, invert, (DataBufferByte)buffer, raster);
			} else if( buffer.getDataType() == DataBuffer.TYPE_INT ) {
				renderBinary(binaryImage, invert, (DataBufferInt)buffer, raster);
			} else {
				_renderBinary(binaryImage, invert,  out);
			}
		} catch( SecurityException e ) {
			_renderBinary(binaryImage, invert, out);
		}
		// hack so that it knows the buffer has been modified
		out.setRGB(0,0,out.getRGB(0,0));
		return out;
	}
87637
public static float sipToPixel(Resources resources, float sip) {
        float density = resources.getDisplayMetrics().scaledDensity;
        return sip * density;
    }
169853
private static <IN, K> org.apache.flink.api.common.operators.SingleInputOperator<?, IN, ?> translateSelectorFunctionDistinct(
			SelectorFunctionKeys<IN, ?> rawKeys,
			ReduceFunction<IN> function,
			TypeInformation<IN> outputType,
			String name,
			Operator<IN> input,
			int parallelism,
			CombineHint hint) {
		@SuppressWarnings("unchecked")
		final SelectorFunctionKeys<IN, K> keys = (SelectorFunctionKeys<IN, K>) rawKeys;

		TypeInformation<Tuple2<K, IN>> typeInfoWithKey = KeyFunctions.createTypeWithKey(keys);
		Operator<Tuple2<K, IN>> keyedInput = KeyFunctions.appendKeyExtractor(input, keys);

		PlanUnwrappingReduceOperator<IN, K> reducer =
				new PlanUnwrappingReduceOperator<>(function, keys, name, outputType, typeInfoWithKey);
		reducer.setInput(keyedInput);
		reducer.setCombineHint(hint);
		reducer.setParallelism(parallelism);

		return KeyFunctions.appendKeyRemover(reducer, keys);
	}
1268387
def raster2shp(rasterfile, vectorshp, layername=None, fieldname=None,
                   band_num=1, mask='default'):
        """"""
        FileClass.remove_files(vectorshp)
        FileClass.check_file_exists(rasterfile)
        # this allows GDAL to throw Python Exceptions
        gdal.UseExceptions()
        src_ds = gdal.Open(rasterfile)
        if src_ds is None:
            print('Unable to open %s' % rasterfile)
            sys.exit(1)
        try:
            srcband = src_ds.GetRasterBand(band_num)
        except RuntimeError as e:
            # for example, try GetRasterBand(10)
            print('Band ( %i ) not found, %s' % (band_num, e))
            sys.exit(1)
        if mask == 'default':
            maskband = srcband.GetMaskBand()
        elif mask is None or mask.upper() == 'NONE':
            maskband = None
        else:
            mask_ds = gdal.Open(mask)
            maskband = mask_ds.GetRasterBand(1)
        #  create output datasource
        if layername is None:
            layername = FileClass.get_core_name_without_suffix(rasterfile)
        drv = ogr_GetDriverByName(str('ESRI Shapefile'))
        dst_ds = drv.CreateDataSource(vectorshp)
        srs = None
        if src_ds.GetProjection() != '':
            srs = osr_SpatialReference()
            srs.ImportFromWkt(src_ds.GetProjection())
        dst_layer = dst_ds.CreateLayer(str(layername), srs=srs)
        if fieldname is None:
            fieldname = layername.upper()
        fd = ogr_FieldDefn(str(fieldname), OFTInteger)
        dst_layer.CreateField(fd)
        dst_field = 0
        result = gdal.Polygonize(srcband, maskband, dst_layer, dst_field,
                                 ['8CONNECTED=8'], callback=None)
        return result
420808
public static <T extends ImageGray<T>>
	void scaleDown2(T input , T output ) {
		if( input instanceof GrayF32) {
			ImplPyramidOps.scaleDown2((GrayF32)input,(GrayF32)output);
		} else if( input instanceof GrayU8) {
			ImplPyramidOps.scaleDown2((GrayU8)input,(GrayU8)output);
		} else {
			throw new IllegalArgumentException("Image type not yet supported");
		}
	}
1064497
public function gs( $input_path_to_ps, $output_path_to_png, $dpi ) {

		$dpi = (int) $dpi;
		$command = PB_GS_COMMAND . " -dQUIET -dNOPAUSE -dSAFER -dBATCH -sDEVICE=pnggray -r{$dpi} -sOutputFile=" . escapeshellarg( $output_path_to_png ) . ' ' . escapeshellarg( $input_path_to_ps );

		// Execute command
		$output = [];
		$return_var = 0;
		exec( $command, $output, $return_var ); // @codingStandardsIgnoreLine

		if ( ! empty( $output ) ) {
			// @codingStandardsIgnoreStart
			debug_error_log( $command );
			debug_error_log( print_r( $output, true ) );
			// @codingStandardsIgnoreEnd
		}
	}
413360
public final void procSeSrv(final Map<String, Object> pRqVs,
    final IRequestData pRqDt, final TradingSettings pTs,
      final OnlineBuyer pBuyer, final Long pItemId) throws Exception {
    List<SeServiceSpecifics> itemSpecLst;
    List<SeServicePlace> itemPlaceLst;
    itemSpecLst = retrieveItemSpecificsList(pRqVs, pTs, pItemId,
      SeServiceSpecifics.class, SeService.class.getSimpleName());
    //extract main image if exist:
    int miIdx = -1;
    for (int i = 0; i < itemSpecLst.size(); i++) {
      if (itemSpecLst.get(i).getSpecifics().getItsType()
        .equals(ESpecificsItemType.IMAGE)) {
        pRqDt.setAttribute("itemImage", itemSpecLst.get(i));
        miIdx = i;
        break;
      }
    }
    if (miIdx != -1) {
      itemSpecLst.remove(miIdx);
    }
    AItemPrice<?, ?> itemPrice = getSrvCart().revealItemPrice(pRqVs, pTs,
        pBuyer, EShopItemType.SESERVICE, pItemId);
    itemPlaceLst = getSrvOrm().retrieveListWithConditions(pRqVs,
        SeServicePlace.class, " where ITEM=" + pItemId);
    pRqDt.setAttribute("itemSpecLst", itemSpecLst);
    pRqDt.setAttribute("itemPlaceLst", itemPlaceLst);
    pRqDt.setAttribute("itemPrice", itemPrice);
  }
1250440
public final String escapeHtml(final String pSource) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < pSource.length(); i++) {
      char ch = pSource.charAt(i);
      sb.append(htmlEscape(ch));
    }
    return sb.toString();
  }
1343403
private <T> Collection<Integer> transformSource(SourceTransformation<T> source) {
		String slotSharingGroup = determineSlotSharingGroup(source.getSlotSharingGroup(), Collections.emptyList());

		streamGraph.addSource(source.getId(),
				slotSharingGroup,
				source.getCoLocationGroupKey(),
				source.getOperator(),
				null,
				source.getOutputType(),
				"Source: " + source.getName());
		if (source.getOperator().getUserFunction() instanceof InputFormatSourceFunction) {
			InputFormatSourceFunction<T> fs = (InputFormatSourceFunction<T>) source.getOperator().getUserFunction();
			streamGraph.setInputFormat(source.getId(), fs.getFormat());
		}
		streamGraph.setParallelism(source.getId(), source.getParallelism());
		streamGraph.setMaxParallelism(source.getId(), source.getMaxParallelism());
		return Collections.singleton(source.getId());
	}
964795
@Override
    public ImageSource apply(ImageSource source) {
        int width = source.getWidth();
        int height = source.getHeight();

        int[][] result = new int[height][width];

        if (source.isGrayscale()) {
            for (int i = 0; i < height; i++) {

                int iMin = Math.max(0, i - blockRadius);
                int iMax = Math.min(height, i + blockRadius + 1);
                int h = iMax - iMin;

                int jMin = Math.max(0, -blockRadius);
                int jMax = Math.min(width - 1, blockRadius);

                int[] hist = new int[bins + 1];
                int[] clippedHist = new int[bins + 1];

                for (int k = iMin; k < iMax; k++) {
                    for (int l = jMin; l < jMax; l++) {
                        ++hist[roundPositive(source.getGray(l, k) / 255.0f * bins)];
                    }
                }

                for (int j = 0; j < width; j++) {
                    int v = roundPositive(source.getGray(j, i) / 255.0f * bins);

                    int xMin = Math.max(0, j - blockRadius);
                    int xMax = j + blockRadius + 1;
                    int w = Math.min(width, xMax) - xMin;
                    int n = h * w;

                    int limit = (int) (slope * n / bins + 0.5f);

                    /* remove left behind values from histogram */
                    if (xMin > 0) {
                        int xMin1 = xMin - 1;
                        for (int yi = iMin; yi < iMax; ++yi) {
                            --hist[roundPositive(source.getGray(xMin1, yi) / 255.0f * bins)];
                        }
                    }

                    /* add newly included values to histogram */
                    if (xMax <= width) {
                        int xMax1 = xMax - 1;
                        for (int yi = iMin; yi < iMax; ++yi) {
                            ++hist[roundPositive(source.getGray(xMax1, yi) / 255.0f * bins)];
                        }
                    }

                    System.arraycopy(hist, 0, clippedHist, 0, hist.length);
                    int clippedEntries = 0, clippedEntriesBefore;

                    do {
                        clippedEntriesBefore = clippedEntries;
                        clippedEntries = 0;
                        for (int z = 0; z <= bins; ++z) {
                            int d = clippedHist[z] - limit;
                            if (d > 0) {
                                clippedEntries += d;
                                clippedHist[z] = limit;
                            }
                        }

                        int d = clippedEntries / (bins + 1);
                        int m = clippedEntries % (bins + 1);
                        for (int z = 0; z <= bins; ++z) {
                            clippedHist[z] += d;
                        }

                        if (m != 0) {
                            int s = bins / m;
                            for (int z = 0; z <= bins; z += s) {
                                ++clippedHist[z];
                            }
                        }
                    }
                    while (clippedEntries != clippedEntriesBefore);

                    /* build cdf of clipped histogram */
                    int hMin = bins;
                    for (int z = 0; z < hMin; ++z) {
                        if (clippedHist[z] != 0) hMin = z;
                    }

                    int cdf = 0;
                    for (int z = hMin; z <= v; ++z) {
                        cdf += clippedHist[z];
                    }

                    int cdfMax = cdf;
                    for (int z = v + 1; z <= bins; ++z) {
                        cdfMax += clippedHist[z];
                    }

                    int cdfMin = clippedHist[hMin];

                    result[i][j] = roundPositive((cdf - cdfMin) / (float) (cdfMax - cdfMin) * 255.0f);
                }

                for (int a = 0; a < width; a++) {
                    source.setGray(a, i, result[i][a]);
                }
            }
        } else {
            MatrixSource gray = new MatrixSource(source);

            Grayscale gs = new Grayscale(algorithm);
            // It is not OneBandSource
            gs.apply(gray);

            for (int i = 0; i < height; i++) {

                int iMin = Math.max(0, i - blockRadius);
                int iMax = Math.min(height, i + blockRadius + 1);
                int h = iMax - iMin;

                int jMin = Math.max(0, -blockRadius);
                int jMax = Math.min(width - 1, blockRadius);

                int[] hist = new int[bins + 1];
                int[] clippedHist = new int[bins + 1];

                for (int k = iMin; k < iMax; k++) {
                    for (int l = jMin; l < jMax; l++) {
                        ++hist[roundPositive(gray.getGray(l, k) / 255.0f * bins)];
                    }
                }

                for (int j = 0; j < width; j++) {
                    int v = roundPositive(gray.getGray(j, i) / 255.0f * bins);

                    int xMin = Math.max(0, j - blockRadius);
                    int xMax = j + blockRadius + 1;
                    int w = Math.min(width, xMax) - xMin;
                    int n = h * w;

                    int limit = (int) (slope * n / bins + 0.5f);

                    /* remove left behind values from histogram */
                    if (xMin > 0) {
                        int xMin1 = xMin - 1;
                        for (int yi = iMin; yi < iMax; ++yi) {
                            --hist[roundPositive(gray.getGray(xMin1, yi) / 255.0f * bins)];
                        }
                    }

                    /* add newly included values to histogram */
                    if (xMax <= width) {
                        int xMax1 = xMax - 1;
                        for (int yi = iMin; yi < iMax; ++yi) {
                            ++hist[roundPositive(gray.getGray(xMax1, yi) / 255.0f * bins)];
                        }
                    }

                    System.arraycopy(hist, 0, clippedHist, 0, hist.length);
                    int clippedEntries = 0, clippedEntriesBefore;
                    do {
                        clippedEntriesBefore = clippedEntries;
                        clippedEntries = 0;
                        for (int z = 0; z <= bins; ++z) {
                            int d = clippedHist[z] - limit;
                            if (d > 0) {
                                clippedEntries += d;
                                clippedHist[z] = limit;
                            }
                        }

                        int d = clippedEntries / (bins + 1);
                        int m = clippedEntries % (bins + 1);
                        for (int z = 0; z <= bins; ++z)
                            clippedHist[z] += d;

                        if (m != 0) {
                            int s = bins / m;
                            for (int z = 0; z <= bins; z += s)
                                ++clippedHist[z];
                        }
                    }
                    while (clippedEntries != clippedEntriesBefore);

                    /* build cdf of clipped histogram */
                    int hMin = bins;
                    for (int z = 0; z < hMin; ++z) {
                        if (clippedHist[z] != 0) hMin = z;
                    }

                    int cdf = 0;
                    for (int z = hMin; z <= v; ++z) {
                        cdf += clippedHist[z];
                    }

                    int cdfMax = cdf;
                    for (int z = v + 1; z <= bins; ++z) {
                        cdfMax += clippedHist[z];
                    }

                    int cdfMin = clippedHist[hMin];

                    result[i][j] = roundPositive((cdf - cdfMin) / (float) (cdfMax - cdfMin) * 255.0f);
                }

                for (int a = 0; a < width; a++) {
                    float s = (float) result[i][a] / (float) gray.getGray(a, i);

                    float r = ColorHelper.clamp(roundPositive(s * source.getR(a, i)));
                    float g = ColorHelper.clamp(roundPositive(s * source.getG(a, i)));
                    float b = ColorHelper.clamp(roundPositive(s * source.getB(a, i)));

                    int rgb = ColorHelper.getRGB((int) r, (int) g, (int) b);

                    source.setRGB(a, i, rgb);
                }
            }
        }
        return source;
    }
186224
public static DiffBuilder compare(final Object control) {
        final Source controlSource = getSource(control);
        return new DiffBuilder(controlSource);
    }
882361
public DestinationHandler getAliasDestination(SIBUuid12 gatheringTargetUuid, DestinationHandler baseDest, boolean includeInvisible)
                    throws SITemporaryDestinationNotFoundException, SINotPossibleInCurrentConfigurationException, SIMPDestinationCorruptException, SIResourceException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "getAliasDestination", new Object[] { gatheringTargetUuid, baseDest, Boolean.valueOf(includeInvisible) });

        DestinationHandler destinationHandler = getDestinationInternal(gatheringTargetUuid, includeInvisible);

        try
        {
            if (destinationHandler == null)
            {
                BaseDestinationDefinition bdd = messageProcessor.getMessagingEngine().getSIBDestinationByUuid(messageProcessor.getMessagingEngineBus(),
                                                                                                              gatheringTargetUuid.toString());

                // The returned destination can be remote or an alias.  We need to act
                // accordingly.
                if (bdd.isAlias())
                {
                    // The destination is an alias.
                    DestinationAliasDefinition add = (DestinationAliasDefinition) bdd;

                    destinationHandler = createAliasDestination(add, null, baseDest);
                }
            }
        }

        // Catch Admin's SIBExceptionDestinationNotFound exception
        catch (SIBExceptionDestinationNotFound e)
        {
            // No FFDC code needed

            SibTr.exception(tc, e);

            // Exception not fatal - just return null to show no destiation has been
            // found.
        } catch (SIBExceptionBase e)
        {
            // No FFDC code needed

            SibTr.exception(tc, e);

            // TO DO - handle this
        } catch (SIResourceException e)
        {
            // No FFDC code needed
            if (!(e instanceof SIMPResourceException))
            {
                SIMPResourceException ee = new SIMPResourceException(e);
                ee.setExceptionReason(SIRCConstants.SIRC0901_INTERNAL_MESSAGING_ERROR);
                ee.setExceptionInserts(new String[] { "com.ibm.ws.sib.processor.impl.DestinationManager.getAliasDestination",
                                                     "1:8107:1.508.1.7",
                                                     SIMPUtils.getStackTrace(e) });
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    SibTr.exit(tc, "getAliasDestination", ee);
                throw ee;
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "getAliasDestination", e);
            throw e;

        }

        checkDestinationHandlerExists(
                                      destinationHandler != null,
                                      gatheringTargetUuid.toString(),
                                      messageProcessor.getMessagingEngineName());

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "getAliasDestination", destinationHandler);

        return destinationHandler;
    }
1356915
def DviPsStrFunction(target = None, source= None, env=None):
    """"""
    if env.GetOption("no_exec"):
        result = env.subst('$PSCOM',0,target,source)
    else:
        result = ''
    return result