working on it ...

Filters

Explore Public Snippets

Sort by

Found 6,341 snippets matching: tree

    public by ejmurray modified Jan 22, 2016  249941  16  3  0

    Photo management script. This script will copy photos from "~/Pictures/iPhone Incoming" into a tree the script creates, with folders representing month and years, and photo names timestamped. Completely based on the work of the amazing Dr. Drang; se...

    Photo management script. This script will copy photos from "~/Pictures/iPhone Incoming" into a tree the script creates, with folders representing month and years, and photo names timestamped. Completely based on the work of the amazing Dr. Drang; see here: http://www.leancrew.com/all-this/2013/10/photo-management-via-the-finder/ You can see mor
    #!/usr/bin/python
    
    import sys
    import os, shutil
    import subprocess
    import os.path
    from datetime import datetime
    
    ######################## Functions #########################
    
    def photoDate(f):
      "Return the date/time on which the given photo was taken."
    
      cDate = subprocess.check_output(['sips', '-g', 'creation', f])
      cDate = cDate.split('\n')[1].lstrip().split(': ')[1]
      return datetime.strptime(cDate, "%Y:%m:%d %H:%M:%S")
    
    
    ###################### Main program ########################
    
    # Where the photos are and where they're going.
    sourceDir = os.environ['HOME'] + '/Pictures/iPhone Incoming'
    destDir = os.environ['HOME'] + '/Pictures/iPhone'
    errorDir = destDir + '/Unsorted/'
    
    # The format for the new file names.
    fmt = "%Y-%m-%d %H-%M-%S"
    
    # The problem files.
    problems = []
    
    # Get all the JPEGs in the source folder.
    photos = os.listdir(sourceDir)
    photos = [ x for x in photos if x[-4:] == '.jpg' or x[-4:] == '.JPG' ]
    
    # Prepare to output as processing occurs
    lastMonth = 0
    lastYear = 0
    
    # Create the destination folder if necessary
    if not os.path.exists(destDir):
      os.makedirs(destDir)
    if not os.path.exists(errorDir):
      os.makedirs(errorDir)
    
    # Copy photos into year and month subfolders. Name the copies according to
    # their timestamps. If more than one photo has the same timestamp, add
    # suffixes 'a', 'b', etc. to the names. 
    for photo in photos:
      # print "Processing %s..." % photo
      original = sourceDir + '/' + photo
      suffix = 'a'
      try:
        pDate = photoDate(original)
        yr = pDate.year
        mo = pDate.month
    
        if not lastYear == yr or not lastMonth == mo:
          sys.stdout.write('\nProcessing %04d-%02d...' % (yr, mo))
          lastMonth = mo
          lastYear = yr
        else:
          sys.stdout.write('.')
        
        newname = pDate.strftime(fmt)
        thisDestDir = destDir + '/%04d/%02d' % (yr, mo)
        if not os.path.exists(thisDestDir):
          os.makedirs(thisDestDir)
    
        duplicate = thisDestDir + '/%s.jpg' % (newname)
        while os.path.exists(duplicate):
          newname = pDate.strftime(fmt) + suffix
          duplicate = destDir + '/%04d/%02d/%s.jpg' % (yr, mo, newname)
          suffix = chr(ord(suffix) + 1)
        shutil.copy2(original, duplicate)
      except Exception:
        shutil.copy2(original, errorDir + photo)
        problems.append(photo)
      except:
        sys.exit("Execution stopped.")
    
    # Report the problem files, if any.
    if len(problems) > 0:
      print "\nProblem files:"
      print "\n".join(problems)
      print "These can be found in: %s" % errorDir
    
    
    

    public by Geometry modified Aug 7, 2016  77289  0  5  0

    PreOrder: Pre-order tree traversal method.

    Pre-order tree traversal method.
    /// <summary>
    ///   Pre-order tree traversal method.
    /// </summary>
    /// 
    public static IEnumerator<KDTreeNode<T>> PreOrder<T>(KDTree<T> tree)
    {
        if (tree.Root == null)
            yield break;
    
        var stack = new Stack<KDTreeNode<T>>();
    
        KDTreeNode<T> current = tree.Root;
    
        while (stack.Count != 0 || current != null)
        {
            if (current != null)
            {
                stack.Push(current);
                yield return current;
                current = current.Left;
            }
            else
            {
                current = stack.Pop();
                current = current.Right;
            }
        }
    }

    public by Geometry modified Aug 7, 2016  76165  1  5  0

    PostOrder: Post-order tree traversal method.

    Post-order tree traversal method.
    /// <summary>
    ///   Post-order tree traversal method.
    /// </summary>
    /// 
    public static IEnumerator<KDTreeNode<T>> PostOrder<T>(KDTree<T> tree)
    {
        if (tree.Root == null)
            yield break;
    
        var stack = new Stack<KDTreeNode<T>>(new[] { tree.Root });
    
        KDTreeNode<T> previous = tree.Root;
    
        while (stack.Count != 0)
        {
            KDTreeNode<T> current = stack.Peek();
    
            if (previous == current || previous.Left == current || previous.Right == current)
            {
                if (current.Left != null)
                    stack.Push(current.Left);
                else if (current.Right != null)
                    stack.Push(current.Right);
                else
                {
                    yield return stack.Pop();
                }
            }
            else if (current.Left == previous)
            {
                if (current.Right != null)
                    stack.Push(current.Right);
                else
                {
                    yield return stack.Pop();
                }
            }
            else if (current.Right == previous)
            {
                yield return stack.Pop();
            }
            else
            {
                throw new InvalidOperationException();
            }
    
            previous = current;
        }
    }

    public by Geometry modified Aug 7, 2016  70388  0  5  0

    Load: Loads a tree from a stream.

    Loads a tree from a stream. The stream from which the tree is to be deserialized. The deserialized tree.
    /// <summary>
    ///   Loads a tree from a stream.
    /// </summary>
    /// 
    /// <param name="stream">The stream from which the tree is to be deserialized.</param>
    /// 
    /// <returns>The deserialized tree.</returns>
    /// 
    [Obsolete("Please use Accord.IO.Serializer.Load() instead (or use it as an extension method).")]
    public static DecisionTree Load(Stream stream)
    {
        return Accord.IO.Serializer.Load<DecisionTree>(stream);
    }

    public by Geometry modified Aug 7, 2016  49791  0  5  0

    FromData: Creates a new k-dimensional tree from the given points.

    Creates a new k-dimensional tree from the given points. The type of the value to be stored. The points to be added to the tree. Whether the given vector can be ordered in place. Passing true will change the original order of the vector. If set to false, all operations will be performed on an extra copy of the vector. A pop
    /// <summary>
    ///   Creates a new k-dimensional tree from the given points.
    /// </summary>
    /// 
    /// <typeparam name="T">The type of the value to be stored.</typeparam>
    /// 
    /// <param name="points">The points to be added to the tree.</param>
    /// <param name="inPlace">Whether the given <paramref name="points"/> vector
    ///   can be ordered in place. Passing true will change the original order of
    ///   the vector. If set to false, all operations will be performed on an extra
    ///   copy of the vector.</param>
    /// 
    /// <returns>A <see cref="KDTree{T}"/> populated with the given data points.</returns>
    /// 
    public static KDTree<T> FromData<T>(double[][] points, bool inPlace = false)
    {
        if (points == null)
            throw new ArgumentNullException("points");
    
        if (points.Length == 0)
            throw new ArgumentException("Insufficient points for creating a tree.");
    
        int leaves;
    
        var root = KDTree<T>.CreateRoot(points, inPlace, out leaves);
    
        return new KDTree<T>(points[0].Length, root, points.Length, leaves);
    }

    public by micurs modified Mar 12, 2014  38974  458  10  8

    Using crypto-js in node.js with Typescript

    You can easily install the crypto-js library in node by using the command (on Mac): npm install crypto-js After that you need to download its type definition from Git/DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped/tree/master/cryptojs To make it work, however you need to add the following to the cryptojs.d.ts:
    // add this at the end of crypto.d.ts
      declare module "crypto-js" {
        export = CryptoJS;
      }
    
    // Then you can use the module in typescript
    
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/cryptojs.d.ts'/>
    
    import crypto = require("crypto-js");  
    
    function writeln( msg: string ) {
      process.stdout.write( msg +'\n');
    }
    
    var message : string = "Hello Encrypted World!";
    var cmessage : string = crypto.HmacSHA1( message , "1234").toString();
    writeln( message );
    writeln( cmessage );
    

    public by gwarah modified Aug 18, 2019  762  5  6  0

    Is a file in a directory tree?

    This script is a shell function that performs exactly this check, even if the parameters are symbolic links and/or relative directories. See "How to Use" section to install this snippet
    #!/bin/bash
    # /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    # * File       : dircontains.sh
    # * Goal       : checks if <parent> direcory contains <file>
    # * Requisites :
    # *     1. SHELL=bash
    # * History    :
    # *   #version;date;description
    # *   0.2.0; 29/07/2018; now can check if any kind of file is in <parent>
    # *   0.1.0; 27/07/2018; first release (tested in bash environment)
    # */
    
    #
    # Tested in: ubuntu 16.04/bash
    #
    
    #
    # How to use
    #
    # 1. put this script into a directory (Ex: ~/scripts)
    #
    # 2. insert this code in your ~/.bashrc:
    # . ~/scripts/dircontains.sh
    #
    # 3. open a new shell session and test it:
    #
    # dircontains <dir_parent> <file>
    #
    # 4.
    # the result is in $? var
    # $?=0, <file> is in <dir_parent>
    # $?=1, <file> is not in <dir_parent>
    # $?=2, error
    #
    
    function dircontains_syntax {
        local msg=$1
        echo "${msg}" >&2
        echo "syntax: dircontains <parent> <file>" >&2
        return 1
    }
    
    function dircontains {
        local result=1
        local parent=""
        local parent_pwd=""
        local child=""
        local child_dir=""
        local child_pwd=""
        local curdir="$(pwd)"
        local v_aux=""
    
        # parameters checking
        if [ $# -ne 2 ]; then
            dircontains_syntax "exactly 2 parameters required"
            return 2
        fi
        parent="${1}"
        child="${2}"
        
        # exchange to absolute path
        parent="$(readlink -f "${parent}")"
        child="$(readlink -f "${child}")"
        dir_child="${child}"
    
        # file/directory checking
        if [ ! -d "${parent}" ];  then
            dircontains_syntax "parent dir ${parent} not a directory or doesn't exist"
            return 2
        elif [ ! -e "${child}" ];  then
            dircontains_syntax "file ${child} not found"
            return 2
        elif [ ! -d "${child}" ];  then
            # not directory? get the path of file
            dir_child=`dirname "${child}"`
        fi
    
        # get directories from $(pwd)
        cd "${parent}"
        parent_pwd="$(pwd)"
        cd "${curdir}"  # to avoid errors due relative paths
        cd "${dir_child}"
        child_pwd="$(pwd)"
    
        # checking if is parent
        [ "${child_pwd:0:${#parent_pwd}}" = "${parent_pwd}" ] && result=0
    
        # return to current directory
        cd "${curdir}"
        return $result
    }												

    public by lbottaro modified Jul 4, 2012  2930  1  6  0

    Linq Xml tree in c#

    This C# code allows you to create an entire XML tree, using linq and xml nested technique.
    XElement contacts =
        new XElement("Contacts",
            new XElement("Contact",
                new XElement("Name", "Patrick Hines"),                                                 
                new XElement("Phone", "206-555-0144"),
                new XElement("Address",
                    new XElement("Street1", "123 Main St"),
                    new XElement("City", "Mercer Island"),
                    new XElement("State", "WA"),
                    new XElement("Postal", "68042")
                )
            )
        );
    Console.WriteLine(contacts);

    public by cghersi modified May 5, 2013  3364  0  5  0

    Bash command to remove CVS folders from a tree folder

    Removes all the folders named "CVS" from the tree folder starting from "mydir" folder
    TUTORIAL_DIR_NAME="/mydir"
    find $TUTORIAL_DIR_NAME -name CVS -exec rm -rf {} \;

    public by Geometry modified Aug 7, 2016  1221  0  6  0

    BreadthFirst: Breadth-first tree traversal method.

    Breadth-first tree traversal method.
    /// <summary>
    ///   Breadth-first tree traversal method.
    /// </summary>
    /// 
    public static IEnumerator<KDTreeNode<T>> BreadthFirst<T>(KDTree<T> tree)
    {
        if (tree.Root == null)
            yield break;
    
        var queue = new Queue<KDTreeNode<T>>(new[] { tree.Root });
    
        while (queue.Count != 0)
        {
            KDTreeNode<T> current = queue.Dequeue();
    
            yield return current;
    
            if (current.Left != null)
                queue.Enqueue(current.Left);
    
            if (current.Right != null)
                queue.Enqueue(current.Right);
        }
    }
    • Public Snippets
    • Channels Snippets