working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,320 snippets matching: calculate

    public by lbottaro  463534  0  7  0

    Excel function to calculate the average of positive data in range

    This excel function calculate the average of a specific range of cells, regarding only positive values. Zero or less than zero value won't be used in average calculation. The italian version of this snippet can be used as well on OpenOffice 3.
    =SUMIF(B2:B6;">0")/MAX(COUNTIF(B2:B6;">0");1)
    
    # Italian version
    =SOMMA.SE(B2:B6;">0")/MAX(CONTA.SE(B2:B6;">0");1)

    public by cghersi  246975  1  6  1

    Calculate the occurrences of words in Rss feed

    Creates a dictionary with keys=words and values=occurrences of that word in the given Rss (specified by the URL). The caller should specify the maximum number of items in the returning dictionary and, optionally, the minimum length of the words that will be added to the output.
    public static Dictionary<string, int> ComputeWordsOccurrencesInRss(string url, int maxItems, int minLenOfAcceptedWords = 1)
    {
      Dictionary<string, int> occurrences = new Dictionary<string, int>();
    
      IList<RssReader.RssItem> singleRssResult = RssReader.ReadRss(url, maxItems, true);
      string[] splitted = null;
      foreach (RssReader.RssItem rss in singleRssResult)
      {
        List<string> words = new List<string>();
    
        //split title in words:
        splitted = StringHelper.SplitIntoWords(rss.Title);
        if (splitted != null)
          words.AddRange(splitted);
    
        //split summary in words:
        splitted = StringHelper.SplitIntoWords(rss.Summary);
        if (splitted != null)
          words.AddRange(splitted);
    
        //compute occurrences of words:
        for (int w = 0; w < words.Count; w++)
        {
          string word = words[w].ToLower();
          if (word.Length < minLenOfAcceptedWords)
            continue;
          if (occurrences.ContainsKey(word))
            occurrences[word]++;
          else
            occurrences.Add(word, 1);
        }
      }
    
      return occurrences;
    }
    

    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 michaelp  159531  0  3  0

    Basic way to calculate length of a string

    Basic way to calculate length of a string: gistfile1.txt
    # breaks if string includes a 0
    def string_length(a)
      string = a + "0"
      length = 0
    
      while string[length] != "0"
        length += 1
      end
    
      puts "Your statement is #{length} characters long"
    end
    
    string_length("I am a meat popsicle.")
    
    

    public by boloka  129821  1  5  0

    process time

    How much time running is my php process? Calculate this time. Very simple.
    PHP
    $start_time = microtime(true);
    
    // code...
    
    $end_time = microtime(true);
    
    $process_time = $end_time - $start_time;
    echo 'This code running is: ' . $process_time . ' sec.';

    public by Geometry  959  0  5  0

    CalculateThreshold: Calculate binarization threshold for the given image.

    Calculate binarization threshold for the given image. Image to calculate binarization threshold for. Rectangle to calculate binarization threshold for. Returns binarization threshold. The method is used to calculate binarization threshold only. The threshold later may be applied to the image using image processing filter. Sourc
    /// <summary>
    /// Calculate binarization threshold for the given image.
    /// </summary>
    /// 
    /// <param name="image">Image to calculate binarization threshold for.</param>
    /// <param name="rect">Rectangle to calculate binarization threshold for.</param>
    /// 
    /// <returns>Returns binarization threshold.</returns>
    /// 
    /// <remarks><para>The method is used to calculate binarization threshold only. The threshold
    /// later may be applied to the image using <see cref="Threshold"/> image processing filter.</para></remarks>
    /// 
    /// <exception cref="UnsupportedImageFormatException">Source pixel format is not supported by the routine. It should be
    /// 8 bpp grayscale (indexed) image.</exception>
    /// 
    public static int CalculateThreshold(UnmanagedImage image, Rectangle rect)
    {
        if (image.PixelFormat != PixelFormat.Format8bppIndexed)
            throw new UnsupportedImageFormatException("Source pixel format is not supported by the routine.");
    
        int startX = rect.Left;
        int startY = rect.Top;
        int stopX = startX + rect.Width;
        int stopY = startY + rect.Height;
        int stopXM1 = stopX - 1;
        int stopYM1 = stopY - 1;
        int stride = image.Stride;
        int offset = stride - rect.Width;
    
        // differences and weights
        double ex, ey, weight, weightTotal = 0, total = 0;
    
        unsafe
        {
            // do the job
            byte* ptr = (byte*)image.ImageData.ToPointer();
    
            // allign pointer to the first pixel to process
            ptr += (startY * image.Stride + startX);
    
            // skip the first line for the first pass
            ptr += stride;
    
            // for each line
            for (int y = startY + 1; y < stopYM1; y++)
            {
                ptr++;
                // for each pixels
                for (int x = startX + 1; x < stopXM1; x++, ptr++)
                {
                    // the equations are:
                    // ex = | I(x + 1, y) - I(x - 1, y) |
                    // ey = | I(x, y + 1) - I(x, y - 1) |
                    // weight = max(ex, ey)
                    // weightTotal += weight
                    // total += weight * I(x, y)
    
                    ex = Math.Abs(ptr[1] - ptr[-1]);
                    ey = Math.Abs(ptr[stride] - ptr[-stride]);
                    weight = (ex > ey) ? ex : ey;
                    weightTotal += weight;
                    total += weight * (*ptr);
                }
                ptr += offset + 1;
            }
        }
    
        // calculate threshold
        return (weightTotal == 0) ? (byte)0 : (byte)(total / weightTotal);
    }

    public by Geometry  858  0  4  0

    CalculateMap: Calculate filtering map.

    Calculate filtering map. Filtering range. Fillter value. Fill outside or inside the range. Filtering map.
    /// <summary>
    /// Calculate filtering map.
    /// </summary>
    /// 
    /// <param name="range">Filtering range.</param>
    /// <param name="fill">Fillter value.</param>
    /// <param name="fillOutsideRange">Fill outside or inside the range.</param>
    /// <param name="map">Filtering map.</param>
    /// 
    private static void CalculateMap(IntRange range, byte fill, bool fillOutsideRange, byte[] map)
    {
        for (int i = 0; i < 256; i++)
        {
            if ((i >= range.Min) && (i <= range.Max))
            {
                map[i] = (fillOutsideRange) ? (byte)i : fill;
            }
            else
            {
                map[i] = (fillOutsideRange) ? fill : (byte)i;
            }
        }
    }

    public by Geometry  789  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 sebastian.piskorski  3703  3  5  2

    [MySQL] Calculate Database size

    [MySQL] Calculate Database size using simple single query.
    SELECT table_schema "Data Base Name",
        sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB",
        sum( data_free )/ 1024 / 1024 "Free Space in MB"
    FROM information_schema.TABLES
    GROUP BY table_schema ;

    public by Geometry  1272  0  5  0

    Calculate matrix for unit square to quad mapping

    Calculate matrix for unit square to quad mapping
    using System;
    using System.Collections.Generic;
    using AForge;
    
    private const double TOLERANCE = 1e-13;
    
    // Calculate matrix for unit square to quad mapping
    private static double[,] MapSquareToQuad( List<IntPoint> quad )
    {
        double[,] sq = new double[3, 3];
        double px, py;
    
        px = quad[0].X - quad[1].X + quad[2].X - quad[3].X;
        py = quad[0].Y - quad[1].Y + quad[2].Y - quad[3].Y;
    
        if ( ( px < TOLERANCE ) && ( px > -TOLERANCE ) &&
             ( py < TOLERANCE ) && ( py > -TOLERANCE ) )
        {
            sq[0, 0] = quad[1].X - quad[0].X;
            sq[0, 1] = quad[2].X - quad[1].X;
            sq[0, 2] = quad[0].X;
    
            sq[1, 0] = quad[1].Y - quad[0].Y;
            sq[1, 1] = quad[2].Y - quad[1].Y;
            sq[1, 2] = quad[0].Y;
    
            sq[2, 0] = 0.0;
            sq[2, 1] = 0.0;
            sq[2, 2] = 1.0;
        }
        else
        {
            double dx1, dx2, dy1, dy2, del;
    
            dx1 = quad[1].X - quad[2].X;
            dx2 = quad[3].X - quad[2].X;
            dy1 = quad[1].Y - quad[2].Y;
            dy2 = quad[3].Y - quad[2].Y;
    
            del = Det2( dx1, dx2, dy1, dy2 );
    
            if ( del == 0.0 )
                return null;
    
            sq[2, 0] = Det2( px, dx2, py, dy2 ) / del;
            sq[2, 1] = Det2( dx1, px, dy1, py ) / del;
            sq[2, 2] = 1.0;
    
            sq[0, 0] = quad[1].X - quad[0].X + sq[2, 0] * quad[1].X;
            sq[0, 1] = quad[3].X - quad[0].X + sq[2, 1] * quad[3].X;
            sq[0, 2] = quad[0].X;
    
            sq[1, 0] = quad[1].Y - quad[0].Y + sq[2, 0] * quad[1].Y;
            sq[1, 1] = quad[3].Y - quad[0].Y + sq[2, 1] * quad[3].Y;
            sq[1, 2] = quad[0].Y;
        }
        return sq;
    }
    • Public Snippets
    • Channels Snippets