working on it ...

Filters

Explore Public Snippets

Sort by

Found 20k snippets matching: sum

    public by zonaro  197169  0  8  0

    Sum (Excel port for VB.NET)

    Like in Excel, this method sum the numbers of a ParamArray
    Function Sum(ByVal ParamArray Nums As Decimal()) As Decimal
            Dim s = 0
            For Each i As Decimal In Nums
                s += i
            Next
            Return s
        End Function            

    public by lbottaro  247366  3  7  0

    Lock and synchronization in python

    This example shows how to deal with lock in python parallel programming. Here we want to calculate the disk occupancy for a given directory in Linux OS, evaluating the disk occupancy for any subdirectory using threads. Note the usage of lock mechanism to ensure atomic operation on the total sum.
    import os
    import string
    import threading
    from threading import Thread
    
    disk_usage = 0
    lock = threading.Lock()
    
    for dir in os.popen('ls -d *').readlines():
        print "Dir: " + dir
        t = Thread(target=methodToBeExecutedInParallel, args=(dir,))
        t.start()
        #Join all existing threads to main thread.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
              thread.join()
        print "Disk usage = " + str(disk_usage)
    
    # Function invoked by each thread
    def methodToBeExecutedInParallel(directory):
        print "Working on dir = " + directory
        cmd = 'du -s ' + directory
        line = os.popen(cmd).readlines()[0]
        dirUsage = int(line.split()[0])
        print "Acquiring lock for "+directory+"..."
        with lock:
            print "Acquired lock for "+directory
            global disk_usage
            disk_usage += dirUsage
        print "Disk usage = " + str(dirUsage)

    public by Geometry  1354  0  5  0

    Sum: Computes the sum of the pixels in a given image.

    Computes the sum of the pixels in a given image.
    /// <summary>
    ///   Computes the sum of the pixels in a given image.
    /// </summary>
    public static int Sum(this UnmanagedImage image, Rectangle rectangle)
    {
        if ((image.PixelFormat != PixelFormat.Format8bppIndexed) &&
            (image.PixelFormat != PixelFormat.Format16bppGrayScale))
            throw new UnsupportedImageFormatException("Only grayscale images are supported");
    
        int width = image.Width;
        int height = image.Height;
        int stride = image.Stride;
    
        int rwidth = rectangle.Width;
        int rheight = rectangle.Height;
        int rx = rectangle.X;
        int ry = rectangle.Y;
        int sum = 0;
    
        unsafe
        {
            if (image.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                byte* src = (byte*)image.ImageData.ToPointer();
    
                for (int y = 0; y < rheight; y++)
                {
                    byte* p = src + stride * (ry + y) + rx;
    
                    for (int x = 0; x < rwidth; x++)
                        sum += (*p++);
                }
            }
            else
            {
                ushort* src = (ushort*)image.ImageData.ToPointer();
    
                for (int y = 0; y < rheight; y++)
                {
                    ushort* p = src + stride * (ry + y) + rx;
    
                    for (int x = 0; x < rwidth; x++)
                        sum += (*p++);
                }
            }
        }
    
        return sum;
    }

    public by Geometry  1217  0  5  0

    sum: Matrix sum vector.

    Matrix sum vector.
    /// <summary>Matrix sum vector.</summary>
    protected static double[] sum(double[,] matrix) { return Matrix.Sum(matrix, 0); }

    public by Geometry  1167  0  6  0

    Sum: Computes the sum of an array of complex numbers.

    Computes the sum of an array of complex numbers.
    /// <summary>
    ///   Computes the sum of an array of complex numbers.
    /// </summary>
    /// 
    public static Complex Sum(this Complex[] x)
    {
        if (x == null) throw new ArgumentNullException("x");
    
        Complex r = Complex.Zero;
        for (int i = 0; i < x.Length; i++)
            r += x[i];
        return r;
    }

    public by Geometry  1099  0  6  0

    Sum: Computes the sum of all pixels within a given image region.

    Computes the sum of all pixels within a given image region. The image region. The region width. The region height. The image stride. The sum of all pixels within the region.
    /// <summary>
    ///   Computes the sum of all pixels 
    ///   within a given image region.
    /// </summary>
    /// 
    /// <param name="src">The image region.</param>
    /// <param name="width">The region width.</param>
    /// <param name="height">The region height.</param>
    /// <param name="stride">The image stride.</param>
    /// 
    /// <returns>The sum of all pixels within the region.</returns>
    /// 
    public static int Sum(byte* src, int width, int height, int stride)
    {
        int sum = 0;
    
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++, src++)
                sum += *src;
    
            src += stride - width;
        }
    
        return sum;
    }

    public by Geometry  1016  0  5  0

    sum: Sum of vector elements.

    Sum of vector elements.
    /// <summary>Sum of vector elements.</summary>
    protected static double sum(double[] vector) { return Matrix.Sum(vector); }

    public by Geometry  74842  0  4  0

    Algorithm FastExpansionSum

    // Algorithm Fast-Expansion-Sum // NOTE: This algorithm is not actually used further, but good for checking the S. paper. // Instead the Zero Eliminating version is used. // h cannot be the same as e or f // Read this code together with fast_expansion_sum in predicates.c // There are some minor changes here, because we don't want to read
    // Algorithm Fast-Expansion-Sum
    // NOTE: This algorithm is not actually used further, but good for checking the S. paper.
    //       Instead the Zero Eliminating version is used.
    // h cannot be the same as e or f
    // Read this code together with fast_expansion_sum in predicates.c
    // There are some minor changes here, because we don't want to read outside the array bounds.
    public static int FastExpansionSum(int elen, double[] e, int flen, double[] f, double[] h)
    {
        double Q;
        double Qnew;
        int eindex, findex, hindex;
        double enow, fnow;
    
        // We traverse the lists e and f together. moving from small to large magnitude
        // enow and fnow keep track of the current value in each list, 
        // and eindex and findex the current index
        enow = e[0];
        fnow = f[0];
        eindex = findex = 0;
    
        // First step is to assign to Q the entry with smaller magnitude
        if ((fnow > enow) == (fnow > -enow)) // if |fnow| >= |enow|
        {
            Q = enow;
            eindex++;
    
            // NOTE: The original prdicates.c code here would read past the array bound here (but never use the value).
            // Q = enow;
            // enow = e[++eindex]; <<< PROBLEM HERE
    
            // Instead I just increment the index, and do an extra read later.
            // Pattern is then to read both enow and fnow for every step
            // This adds some extra array evaluations, especially for long arrays, but removes one at the end of each array.
        }
        else
        {
            Q = fnow;
            findex++;
        }
    
        // Start adding entries into h, carrying Q
        hindex = 0;
                
        // Check whether we still have entries in both lists
        if ((eindex < elen) && (findex < flen)) 
        {
            // Note we have an extra 'unrolled' step here, where we are allowed to use FastTwoSum
            // This is becuase we know the next expansion entry is smaller than Q (according to how Q was picked above)
            enow = e[eindex];
            fnow = f[findex];
            // Pick smaller magnitude
            // if |fnow| >= |enow|
            if ((fnow > enow) == (fnow > -enow))
            {
                // Add e and advance eindex
                FastTwoSum(enow, Q, out Qnew, out h[0]);
                eindex++;
            } 
            else 
            {
                // Add f and advance findex
                FastTwoSum(fnow, Q, out Qnew, out h[0]);
                findex++;
            }
            Q = Qnew;
            hindex = 1;
            // While we still have entries in both lists
            while ((eindex < elen) && (findex < flen)) 
            {
                // Can no longer use FastTwoSum - use TwoSum
                enow = e[eindex];
                fnow = f[findex];
                // Pick smaller magnitude
                // if |fnow| >= |enow|
                if ((fnow > enow) == (fnow > -enow))
                {
                    TwoSum(Q, enow, out Qnew, out h[hindex]);
                    eindex++;
                } 
                else 
                {
                    TwoSum(Q, fnow, out Qnew, out h[hindex]);
                    findex++;
                }
                Q = Qnew;
                hindex++;
            }
        }
        // Now we have exhausted one of the lists
        // For the rest, we just run along the list that has values left, 
        //    no more tests to try to pull from the correct list
        while (eindex < elen)
        {
            enow = e[eindex];
            TwoSum(Q, enow, out Qnew, out h[hindex]);
            eindex++;
            Q = Qnew;
            hindex++;
        }
        while (findex < flen)
        {
            fnow = f[findex];
            TwoSum(Q, fnow, out Qnew, out h[hindex]);
            findex++;
            Q = Qnew;
            hindex++;
        }
        h[hindex] = Q;
        return hindex + 1;
    }

    public by Geometry  1875  0  6  0

    Add: Adds two 32-bit floating point values and replaces the first double value with their sum, as an atomic operation.

    Adds two 32-bit floating point values and replaces the first double value with their sum, as an atomic operation. The first variable to be added. The second variable to be added. The updated value of the first variable.
    /// <summary>
    ///   Adds two 32-bit floating point values and replaces the first
    ///   double value with their sum, as an atomic operation.
    /// </summary>
    /// 
    /// <param name="location1">The first variable to be added.</param>
    /// <param name="value">The second variable to be added.</param>
    /// 
    /// <returns>The updated value of the first variable.</returns>
    /// 
    public static double Add(ref double location1, double value)
    {
        double newCurrentValue = 0;
        while (true)
        {
            double currentValue = newCurrentValue;
            double newValue = currentValue + value;
            newCurrentValue = Interlocked.CompareExchange(ref location1, newValue, currentValue);
            if (newCurrentValue == currentValue)
                return newValue;
        }
    }

    public by cghersi  2028  4  6  2

    Merge the content of two dictionaries

    Checks if the two input dictionaries has the same key: in positive case, the values corresponding to the matching keys are summed in the resulting dictionary.
    public static void MergeDictionary(ref Dictionary<string, int> container, Dictionary<string, int> input)
    {
      if (input == null)
        return;
      foreach (string key in input.Keys)
      {
        if (container.ContainsKey(key))
          container[key] += input[key];
        else
          container.Add(key, input[key]);
      }
    }
    
    • Public Snippets
    • Channels Snippets