working on it ...

Filters

Explore Public Snippets

Sort by

Found 2,489 snippets matching: conversion

    public by antlong  489193  15  7  1

    Extract JPG images from a PDF

    A command line tool to extract jpg images from pdf files.
    #!/usr/bin/env python
    import sys
    
    
    def main():
        """Extract JPG's from PSD's.
        
        Usage:
          python extract.py filename.pdf
        
        Note:
          All extracted images will be saved to the directory 
          the script is initialized in.
        """
        try:
            pdf = file(sys.argv[1], "rb").read()
        except Exception:
            print "Usage: `python extract.py filename.pdf`"
            return
    
        startmark, endmark = "\xff\xd8", "\xff\xd9"
        startfix, endfix, i, njpg = 0, 2, 0, 0
    
        while True:
            istream = pdf.find("stream", i)
            if istream < 0:
                break
            istart = pdf.find(startmark, istream, istream+20)
            if istart < 0:
                i = istream+20
                continue
            iend = pdf.find("endstream", istart)
            if iend < 0:
                raise Exception("Couldn't find end of stream.")
            iend = pdf.find(endmark, iend-20)
            if iend < 0:
                raise Exception("Couldn't find end of JPG.")
         
            istart += startfix
            iend += endfix
            jpg = pdf[istart:iend]
            with open("jpg%d.jpg" % njpg, "wb") as _f:
                _f.write(jpg)
            njpg += 1
            i = iend
    
        print "Extracted %s JPG files." % njpg
    
    main()
    

    public by lbottaro  21542  349  8  0

    How to programmatically convert the Visual Studio coverage file to coveragexml by command line tool in csharp

    This code shows how to programmatically export and convert the coverage data ( .coverage) generated by Visual Studio into a readable xml file (.coveragexml). The xml file can be used to generated a code coverage report, eg using the ReportGenerator tool. The conversion is done using the CoverageInfo and CoverageDS objects and invoking the metho
    using Microsoft.VisualStudio.Coverage.Analysis;
    
    namespace CodeCoverageConverter
    {
        class Program
        {
            static void Main(string[] args)
            {
                if (args == null || args.Length != 3 || args[0] == null || args[1] == null ||  args[2] == null ||
                    string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1]) || string.IsNullOrEmpty(args[2]))
                {
                    help();
                    return;
                }
                string coverageFileName = args[0];
                string dllFileName = args[1];
                string coverageXmlFileName = args[2];
                Console.WriteLine("args[0] = " + coverageFileName);
                Console.WriteLine("args[1] = " + dllFileName);
                Console.WriteLine("args[2] = " + coverageXmlFileName);
    
                using (CoverageInfo info = CoverageInfo.CreateFromFile(coverageFileName, new string[] { dllFileName }, new string[] { }))
                {
                    CoverageDS data = info.BuildDataSet();
    
                    data.WriteXml(coverageXmlFileName);
                }
            }
    
            static private void help()
            {
                Console.WriteLine("Help!");
                Console.Write(@"
                    Arguments
                        Args[0]: data coverage file name (data.coverage)
                        Args[1]: DLL to use (myProject.dll)
                        Args[2]: coveragexml file name to be generated (converted.coveragexml)
                     ");
    
            }
    
        }
    }

    public by DavidEGrayson  1108  0  4  0

    Conversion functions you can find in intsafe.h. The lower triangle more or less represents conversions from big types into smaller types.

    Conversion functions you can find in intsafe.h. The lower triangle more or less represents conversions from big types into smaller types.: pattern_maybe.txt
       1-1 1 2 2-2 4 4 4-4-4 7 7 7 7-7-7-7-7 8-8
     1 = . . . . . . . . . . . . . . . . . . . .
    -1 . = . . . . . . . . . . . . . . . . . . .
     1 . . = . . . . . . . . . . . . . . . . . .
     2 X . X = . X . . . . . . . . . . . . . . .
     2 X . X . = X . . . . . . . . . . . . . . .
    -2 X . X X X = . . . . . . . . . . . . . . .
     4 X . X X X X = . . X X . . . . X X X X . .
     4 X . X X X X X = . X X X . . . X X X X . .
     4 X . X X X X X . = X X X . . . X X X X . .
    -4 X . X X X X X X X = . X X X X . . . . X .
    -4 X . X X X X X X X X = X X X X X . X . X .
     7 . . . . . . X X X X X = . . . X X . X . X
     7 . . . . . . X X X X X . = . . X X X X . X
     7 . . . . . . X X X X X X . = . X X X X . X
     7 . . . . . . X X X X X X . . = X X X X . X
    -7 . . . . . . X X X X X X X X X = . . . X .
    -7 . . . . . . X X X X X X X X X X = . . X .
    -7 . . . . . . X X X X X X X X X . . = . . .
    -7 . . . . . . X X X X X X X X X X . . = . .
     8 . . . . . . X X X X X X X X X X X X X = X
    -8 . . . . . . X X X X X X X X X X X X X X =
    
    

    public by cghersi  3780  1  9  0

    Safe conversion of string to float in SQL Server 2012

    This function allows a safe conversion of strings to float values.
    CREATE FUNCTION [dbo].[isFloatTryConvertible] (@str nvarchar(70))
    RETURNS bit WITH SCHEMABINDING
    AS
    BEGIN
    	DECLARE @res bit = 0;
    
    	IF (TRY_CONVERT(float, @str) IS NOT NULL)
    		SET @res = 1;
    	
    	RETURN @res;
    END

    public by Geometry  1634  1  6  0

    To: Converts an object into another type, irrespective of whether the conversion can be done at compile time or not. This can be used to convert generic types to numeric types during runtime.

    Converts an object into another type, irrespective of whether the conversion can be done at compile time or not. This can be used to convert generic types to numeric types during runtime. The destination type. The value to be converted. The result of the conversion.
    /// <summary>
    ///   Converts an object into another type, irrespective of whether
    ///   the conversion can be done at compile time or not. This can be
    ///   used to convert generic types to numeric types during runtime.
    /// </summary>
    /// 
    /// <typeparam name="T">The destination type.</typeparam>
    /// 
    /// <param name="value">The value to be converted.</param>
    /// 
    /// <returns>The result of the conversion.</returns>
    /// 
    public static T To<T>(this object value)
    {
        if (value is IConvertible)
            return (T)System.Convert.ChangeType(value, typeof(T));
    
        Type type = value.GetType();
        MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static);
        foreach (var m in methods)
        {
            if ((m.Name == "op_Implicit" || m.Name == "op_Explicit") && m.ReturnType == typeof(T))
                return (T)m.Invoke(null, new[] { value });
        }
    
        return (T)System.Convert.ChangeType(value, typeof(T));
    }

    public by Geometry  1098  0  4  0

    TryParse: Converts the string representation of a matrix to its double-precision floating-point number matrix equivalent. A return value indicates whether the conversion succeeded or failed.

    Converts the string representation of a matrix to its double-precision floating-point number matrix equivalent. A return value indicates whether the conversion succeeded or failed. The string representation of the matrix. The format provider to use in the conversion. Default is to use . A double-precision floating-point number matrix par
    /// <summary>
    ///   Converts the string representation of a matrix to its
    ///   double-precision floating-point number matrix equivalent.
    ///   A return value indicates whether the conversion succeeded or failed.
    /// </summary>
    /// <param name="s">The string representation of the matrix.</param>
    /// <param name="provider">
    ///   The format provider to use in the conversion. Default is to use
    ///   <see cref="DefaultMatrixFormatProvider.CurrentCulture"/>.
    /// </param>
    /// <param name="matrix">A double-precision floating-point number matrix parsed
    /// from the given string using the given format provider.</param>
    /// <result>When this method returns, contains the double-precision floating-point
    /// number matrix equivalent to the <see param="s"/> parameter, if the conversion succeeded, 
    /// or null if the conversion failed. The conversion fails if the <see param="s"/> parameter
    /// is null, is not a matrix in a valid format, or contains elements which represent
    /// a number less than MinValue or greater than MaxValue. This parameter is passed
    /// uninitialized. </result>
    /// 
    public static bool TryParse(string s, IMatrixFormatProvider provider, out double[][] matrix)
    {
        // TODO: Create a proper TryParse method without
        //       resorting to a underlying try-catch block.
        try
        {
            matrix = ParseJagged(s, provider);
        }
        catch (FormatException)
        {
            matrix = null;
        }
        catch (ArgumentNullException)
        {
            matrix = null;
        }
    
        return matrix != null;
    }

    public by Geometry  774  0  4  0

    CalculateMap: Calculate conversion map.

    Calculate conversion map. Input range. Output range. Conversion map.
    /// <summary>
    /// Calculate conversion map.
    /// </summary>
    /// 
    /// <param name="inRange">Input range.</param>
    /// <param name="outRange">Output range.</param>
    /// <param name="map">Conversion map.</param>
    /// 
    private static void CalculateMap(IntRange inRange, IntRange outRange, byte[] map)
    {
        double k = 0, b = 0;
    
        if (inRange.Max != inRange.Min)
        {
            k = (double)(outRange.Max - outRange.Min) / (double)(inRange.Max - inRange.Min);
            b = (double)(outRange.Min) - k * inRange.Min;
        }
    
        for (int i = 0; i < 256; i++)
        {
            byte v = (byte)i;
    
            if (v >= inRange.Max)
                v = (byte)outRange.Max;
            else if (v <= inRange.Min)
                v = (byte)outRange.Min;
            else
                v = (byte)(k * v + b);
    
            map[i] = v;
        }
    }

    public by marksimon232  6210  1  7  0

    Swift Collections: Convert String to float in Apple's Swift?

    If you're trying to convert numbers taken from a UITextField, which I presume are actually strings, and convert them to a float, so I can multiply them.
    I believe the current best way to achieve this is to use:
    
    var WageConversion = Wage.text.bridgeToObjectiveC().floatValue
    This is a good implementation since it can handle actual floats (input with .) and will also help prevent the user from copying text into your input field (12p.34, or even 12.12.41).
    
    Also, variables and constants should start with a lower case (including IBOutlets)

    public by johansonkatherine  4872  0  6  3

    Java code for Changing Color Space of PDF Document

    This code shows how java developers can change color space of PDF document from RGB color to CMYK and vice versa by using Aspose.PDF for Java Library. The following methods have been implemented in the Operator class for changing colors. Use it to change some specific RGB/CMYK colors to CMYK/RGB color space, keeping the remaining PDF document as it
    Document doc = new Document(myDir + "input_color.pdf");
    OperatorCollection contents = doc.getPages().get_Item(1).getContents();
    System.out.println("Values of RGB color operators in the pdf document");
    for (int j = 1; j <= contents.size(); j++)
        {
    	Operator oper = contents.get_Item(j);
    	if (oper instanceof Operator.SetRGBColor || oper instanceof Operator.SetRGBColorStroke)
    	try {
    	    //Converting RGB to CMYK color
    	    System.out.println(oper.toString());
    
    	    double[] rgbFloatArray = new double[]
    	        {
    		    	Double.valueOf(oper.getParameters().get(0).toString()),
    		    	Double.valueOf(oper.getParameters().get(1).toString()),
    		    	Double.valueOf(oper.getParameters().get(2).toString()),
    	        };
    	    double[] cmyk = new double[4];
    	    if (oper instanceof Operator.SetRGBColor)
    	    {
    		((Operator.SetRGBColor)oper).getCMYKColor(rgbFloatArray, cmyk);
    		contents.set_Item(j, new Operator.SetCMYKColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
    		}
    		else if (oper instanceof Operator.SetRGBColorStroke)
    		{
    		    ((Operator.SetRGBColorStroke)oper).getCMYKColor(rgbFloatArray, cmyk);
    		   contents.set_Item(j, new Operator.SetCMYKColorStroke(cmyk[0], cmyk[1], cmyk[2], cmyk[3]));
    		}
    		    else
    throw new java.lang.Throwable("Unsupported command");
    
    	} catch (Throwable e) {
    	    e.printStackTrace();
    	}
    		        }
    doc.save(myDir + "input_colorout.pdf");
    
    //Testing the result
    System.out.println("Values of converted CMYK color operators in the result pdf document");
    doc = new Document(myDir + "input_colorout.pdf");
    contents = doc.getPages().get_Item(1).getContents();
    for (int j = 1; j <= contents.size(); j++)
        {
    	Operator oper = contents.get_Item(j);
    	if (oper instanceof Operator.SetCMYKColor || oper instanceof Operator.SetCMYKColorStroke)
    	{
    	   System.out.println(oper.toString());
    	}
       }
    

    public by gr8Adakron  2127  13  4  0

    Perl Conversion : Csv to Json.

    Easy And fast conversion using perl script 1) Handles all unicode problems. 2) Handles Multiline rows. 3) Handles N numbers of row and coloumn successfully. Running Intruction: for example run the script in this manner inside terminal. perl csvtojson.pl inputfile.csv outputfile.json
    #!/usr/bin/perl
    #Author: gr8_Adakron.
    #--------------------- Perl Packages --------------------
    use strict;
    use warnings;
    use JSON;
    use Text::CSV;
    
    #-------------------- Globaling Variables --------------------
    my $flag_header = 1;
    my %hash;
    my $input_file = $ARGV[0] or die "Need to give 1st argument as input.CSV file on the command line\n";
    my $output_file = $ARGV[1] or die "Need to give 2nd argument as output.JSON file on the command line\n";
    my $file = $input_file;
    my $csv = Text::CSV->new ({
      binary    => 1,
      auto_diag => 1,
      sep_char  => ','    # not really needed as this is the default
    });
     
    #--------------------- Reading CSV --------------------------
    my $sum = 0;
    my @headers; 
    open(my $data, '<:encoding(utf8)', $file) or die "Could not open '$file' $!\n";
    while (my $fields = $csv->getline( $data )) {
      #$sum += $fields->[2];
      my @coloumns =();
      if($flag_header == 1){
      foreach(@{ $fields }) {
            my $new = $_;
            push(@headers, $new);
          }
         
      }
      else{
          foreach(@{ $fields }) {
            my $new = $_;
            push(@coloumns, $new);
          }
    
        for my $iteration (0..$#coloumns){
          my $key  = $headers[$iteration];
          my $data = $coloumns[$iteration];
          $hash{$key} = $data;
        }
      }
      if($flag_header>1){
        my $json = encode_json \%hash;
        #print("$json\n");
        my $file_location = $output_file;
        open my $o_file, '>>', $file_location or die $!;
        print $o_file "$json\n";
        close $o_file;
      }
      
      $flag_header +=1;
    }
    close $data;
    print(">>Ended");
    print("\nTotal rows Transformed : $flag_header");
    • Public Snippets
    • Channels Snippets