text:
package org.jai.setup;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.jai.flume.agent.FlumeAgentService;
import org.jai.flume.sinks.elasticsearch.FlumeESSinkService;
import org.jai.flume.sinks.hbase.FlumeHbaseSinkService;
import org.jai.flume.sinks.hdfs.FlumeHDFSSinkService;
import org.jai.hadoop.HadoopClusterService;
import org.jai.hbase.HbaseService;
import org.jai.hive.HiveSearchClicksService;
import org.jai.hive.serde.JsonSerdeService;
import org.jai.oozie.OozieJobsService;
import org.jai.search.client.SearchClientService;
import org.jai.spark.SparkStreamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import akka.actor.ActorSystem;

@Component
public class ContextPostLoadAndPreDestroyHandler {

	@Autowired
	private HadoopClusterService hadoopClusterService;
	@Autowired
	private FlumeAgentService flumeAgentService;
	@Autowired
	private FlumeESSinkService flumeESSinkService;
	@Autowired
	private FlumeHDFSSinkService flumeHDFSSinkService;
	@Autowired
	private JsonSerdeService jsonSerdeService;
	@Autowired
	private HiveSearchClicksService hiveSearchClicksService;
	@Autowired
	private OozieJobsService oozieJobsService;
	@Autowired
	private SearchClientService searchClientService;
	@Autowired
	private ActorSystem actorSystem;
	@Autowired
	private SparkStreamService sparkStreamService;
	@Autowired
	private HbaseService hbaseService;
	@Autowired
	private FlumeHbaseSinkService flumeHbaseSinkService;

	@PostConstruct
	public void start() {
		searchClientService.setup();
		// NOT required, may be for dependency jar later.
		// jsonSerdeService.build();
		hadoopClusterService.start();
		sparkStreamService.setup();
		hbaseService.setup();
		flumeESSinkService.start();
		flumeHDFSSinkService.start();
		flumeHbaseSinkService.start();
		flumeAgentService.setup();
		// hiveSearchClicksService.setup();
		oozieJobsService.setup();
	}

	@PreDestroy
	public void shutdown() {
		oozieJobsService.shutdown();
		sparkStreamService.shutdown();
		flumeESSinkService.shutdown();
		flumeHbaseSinkService.shutdown();
		flumeHDFSSinkService.shutdown();
		flumeAgentService.shutdown();

		// wait 5 sec for others to get closed.
//		try {
//			Thread.sleep(5000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//			// throw RuntimeException()
//		}
		hbaseService.shutdown();
		hadoopClusterService.shutdown();
		actorSystem.shutdown();
		searchClientService.shutdown();
	}

}


text:
var SageFrame = {};
$(function () {
    SageFrame = {
        config: {
            isPostBack: false,
            async: false,
            cache: false,
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            data: '{}',
            dataType: 'json',
            method: "",
            url: "",
            ajaxCallMode: 0,
            baseURL: SageFrameAppPath + "/Services/SageFrameGlobalWebService.asmx/"
        },
        vars: {
            numberRegex: /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/,
            adminimagepath: SageFrameAppPath + "/Administrator/Templates/Default/images/"
        },
        init: function () {
            $('span.sfPopupclose').bind("click", function () {
                $('div.sfPopup,#fade').fadeOut();
            });
            $('body').append('
 Working...
');
            $('div.sfMessage ').on('click', 'img.delete', function () {
                $('div.sfMessage').slideUp('slow');
            });
            $('.sfMessagewrapper').on("click", ".sfMessage", function () {
                $(this).slideUp();
            });
            $('body').on('click', '#sfActivate', function () {
                //$('.sfAvtivateButtons').hide();
                $('.sfActivationWrapper').show();
            });
            $('body').on('click', '#btnActivateCancel', function () {
               // $('.sfAvtivateButtons').show();
                $('.sfActivationWrapper').hide();
            });
            $('body').on('click', '#btnActivate', function () {
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    cache: false,
                    url: SageFrameHostURL + "/services/SageWebService.asmx/ActivateAccount",
                    data: JSON2.stringify({
                        activationkey: $('#txtActivationCode').val(),
                        domainName: SageFrameHostURL
                    }),
                    dataType: 'json',
                    success: function (msg) {
                        SageFrame.messaging.show(msg.d, "alert");
                    }
                });
            });
            $('body').on('click', '#sfPurchase', function () {
                window.location.href = 'http://license.sageframe.com?name=sageframe';
            });
        },
        messages: {
            NoModulesAssigned: "No Modules Assigned. To Add Modules Please Go To the the Module Manager Section OR Click the Manage Modules Link on the top right",
            Presets: "These are the list of presets available. The highlighted presets are the ones already applied to pages. You can delete the preset by simply clicking the delete button."
        },
        utils: {
            getapplicationname: function () {
                return SageFrameAppPath;
            },
            GetImagePath: function (imagepath) {
                var fullpath = SageFrame.utils.getapplicationname() + imagepath;
                return fullpath;
            },
            GetUserName: function () {
                return SageFrameUserName;
            },
            IsNumber: function (str) {
                var isnum = false;
                if (SageFrame.vars.numberRegex.test(str)) {
                    isnum = true;
                }
                return isnum;
            },
            GetFileNameWithoutExtension: function (filename) {
                if (filename.indexOf(".") > -1) {
                    filename = filename.substring(0, filename.indexOf("."));
                }
                return filename;
            },
            GetAdminImage: function (imagename) {
                return (SageFrame.vars.adminimagepath + imagename);
            },
            GetFileNameOnly: function (filepath) {
                var index = filepath.lastIndexOf("/");
                var filename = filepath.substr(index + 1);
                return filename;
            },
            ContainsInvalidChar: function (Name) {
                var characterReg = /^\s*[a-z-_\d\&,\s]+\s*$/i;
                if (!Name.match(characterReg)) {
                    return false;
                }
                else {
                    return true;

                }
            },
            GetPageSEOName: function (pagename) {
                return $.trim(pagename.replace(/-/g, " ")).replace(/ /g, '-');
            }
        },
        messaging: {
            show: function (message, messagetype) {
                if (MsgTemplate == "default") {
                    var styledclass = "";
                    switch (messagetype.toLowerCase()) {
                        case "success":
                            styledclass = "sfMessage sfSuccessmsg sfCurve";
                            break;
                        case "error":
                            styledclass = "sfMessage sfErrormsg sfCurve";
                            break;
                        case "alert":
                            styledclass = "sfMessage sfAlertmsg sfCurve";
                            break;
                        default:
                            styledclass = "sfMessage sfCurve";
                            break;
                    }
                    var messagewrapper = '';
                    messagewrapper += "
";
                    messagewrapper += "" + message + "";
                    $('div.sfMessagewrapper:first').html(messagewrapper).animate(0, function () {
                        $('div.sfMessagewrapper:first').slideDown();
                        $(document).scrollTop(0);
                    });
                }
                else if (MsgTemplate == "custom") {
                    if (messagetype == 'alert')
                        messagetype = 'warning';
                    messages.showMessage(message, messagetype);
                }
            },
            GetLocalizedMessage: function (culturecode, modulename, messagetype) {
                var message = "";
                var param = JSON2.stringify({ CultureCode: culturecode, ModuleName: modulename, MessageType: messagetype });
                $.ajax({
                    type: SageFrame.config.type,
                    contentType: SageFrame.config.contentType,
                    cache: SageFrame.config.cache,
                    url: SageFrame.config.baseURL + "GetLocalizedMessage",
                    data: param,
                    dataType: SageFrame.config.dataType,
                    async: false,
                    success: function (msg) {
                        message = msg.d;
                    }

                });
                return message;

            },
            showdivmessage: function (message) {
                var messagewrapper = '';
                messagewrapper += "
";
                messagewrapper += '
' + message + '
';
                messagewrapper += '
';
                return messagewrapper;
            },
            alert: function (message, element) {
                var messagewrapper = '';
                messagewrapper += "
";
                messagewrapper += '
' + message + '
';
                messagewrapper += '
';
                $(element).hide().html(messagewrapper).animate(0, function () {
                    $(element).slideDown().delay(5000).slideUp();
                });

            }
        },
        tooltip: {
            consts: {
                helpImage: (SageFrameAppPath == "/" ? "" : SageFrameAppPath) + "/Administrator/Templates/Default/images/help.png"
            },
            InitializeToolTips: function () {
                this.GetHelpToolTip("imgToolTip", "#testTooltip", "This is my tooltip");
            },
            GetHelpToolTip: function (id, container, message) {
                $(container).html(SageFrame.tooltip.BuildTooltipImage(id));
                $.toolTipRequest(id, message, "dark");

            },
            GetToolTip: function (id, container, message) {
                $(container).append(SageFrame.tooltip.BuildTooltipImage(id));
                $.toolTipRequest(id, message, "dark");
            },
            BuildTooltipImage: function (id) {
                var image = '';
                return image;
            },
            GetTextBoxToolTip: function (id, message) {
                $.toolTipRequest(id, message, "dark");
            },
            GetGeneralToolTip: function (id) {
                $.toolTipRequestTitle(id, "dark");
            },
            GetTextBoxToolTipImage: function (id, message) {
                $('#' + id).parent().append(SageFrame.tooltip.BuildTooltipImage('img_' + id));
                $.toolTipRequest('img_' + id, message, "dark");
            },
            GetTextBoxToolTipImage_Style: function (id, message, style) {
                $('#' + id).parent().append(SageFrame.tooltip.BuildTooltipImage('img_' + id));
                $.toolTipRequest('img_' + id, message, style);
            }

        },
        popup: {
            show: function (popupid, headertext) {
                var options = {
                    modal: true,
                    title: headertext,
                    minHeight: 125,
                    minWidth: 520,
                    maxWidth: 1000,
                    maxHeight: 1000,
                    dialogClass: "sfFormwrapper",
                    resizable: false
                };
                dlg = $('#' + popupid).dialog(options);
                dlg.parent().appendTo($('form:first'));
            },
            show_wide: function (popupid, headertext) {
                var options = {
                    modal: true,
                    title: headertext,
                    minHeight: 125,
                    minWidth: 720,
                    maxWidth: 1000,
                    maxHeight: 1000,
                    dialogClass: "sfFormwrapper",
                    resizable: false
                };
                var dlg = $('#' + popupid).dialog(options);
                dlg.parent().appendTo($('form:first'));
            },
            close: function (popupid) {
                $('#' + popupid).dialog("close");
            },
            confirm: function (message) {
                var status = false;
                $("#dialog").dialog({
                    resizable: false,
                    height: 140,
                    modal: true,
                    buttons: {
                        "Delete all items": function () {
                            return true;
                            $(this).dialog("close");
                        },
                        Cancel: function () {
                            return false;
                            $(this).dialog("close");
                        }
                    }
                });
            }
        }
    };
    SageFrame.init();

    // $(".confirm").easyconfirm();
    ResetSidebarHeight();
});
//Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function () {
    $('#ajaxBusy').show();
}).ajaxStop(function () {
    $('#ajaxBusy').hide();
});
$(document).ajaxComplete(function () {
    $('#ajaxBusy').hide();
});

(function ($) {
    $.toolTipRequest = function (id, pdata, theme) {
        $('#' + id).qtip({
            content: {
                text: pdata
            },
            position: {
                corner: {
                    target: 'rightBottom',
                    tooltip: 'topLeft'
                }
            },
            style: {
                name: theme
            }
        });
    }
    $.toolTipRequestTitle = function (id, theme) {
        $('#' + id).qtip({
            content: {
                text: $('#' + id).attr("title")
            },
            position: {
                corner: {
                    target: 'leftBottom',
                    tooltip: 'topLeft'
                }
            },
            style: {
                name: theme
            }
        });
    }
})(jQuery);

function ResetSidebarHeight() {
    var scrollpos = $(document).scrollTop();

    var masterheight = $("div.sfMaincontent").height();

    var docheight = $(window).height();
    docheight = docheight - $('div.sfTopwrapper').height() + CalculateAdjustmentHeight();
    var incr = 0;
    if (masterheight > docheight) {
        incr = masterheight - docheight;
    }
    docheight = docheight + incr + 30 + "px";
    $('div.sfSidebar').css("height", docheight);

}

$(document).scroll(function () {
    ResetSidebarHeight();
});
$(document).click(function () {
    ResetSidebarHeight();
});

function CalculateAdjustmentHeight() {
    var calc_height = 10;
    var screen_res = screen.height;
    calc_height = screen_res * 0.28;
    return calc_height;

}

function InitModuleFloat(leftOffset) {

    if (location.href.toLowerCase().indexOf("page-modules") > -1) {

        var topOffset = $('#divDroppable').offset().top;
        var adj = $('#sfOuterwrapper').height() + ($('#sfOuterwrapper').offset().top) - ($('#divFloat').height());
        $("#divFloat").makeFloat({ x: leftOffset, y: 0, speed: "fast", adjustment: adj });
    }

}

$(function () {

    $('div.sfSlideup').parent("div.sfModuleinfo").delay(3500).slideUp("slow");
    $('div.sfFadeout').parent("div.sfModuleinfo").delay(3500).fadeOut("slow");

    $('div.sfModuleinfo div.sfLinks a.sfClose').on("click", function () {
        $(this).parents("div.sfModuleinfo").slideUp("slow");
    });
    $('div.sfModuleinfo div.sfLinks a.sfNclose').bind("click", function () {
        var _ModuleID = $(this).prop("id").replace("close_", "");
        var self = $(this);
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            async: false,
            cache: false,
            url: SageFrameAppPath + "/Modules/Admin/ModuleMessage/services/ModuleMessageWebService.asmx/UpdateMessage",
            data: JSON2.stringify({ ModuleID: _ModuleID, IsActive: false }),
            dataType: 'json',
            success: function (msg) {
                $(self).parents("div.sfModuleinfo").slideUp("slow");
                location.reload();
            }
        });
    });

    $('.tooltip').tooltip({
        showURL: false,
        fade: 250,
        track: true
    });
});

$.maxZIndex = $.fn.maxZIndex = function (opt) {
    ///
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    ///
    /// <param name="opt" type="object">
    /// inc: increment value,
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function () {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function () {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

redpajama_set_name: RedPajamaGithub


text:
/*
 *    MIRACL  C++ Header file ec2.h
 *
 *    AUTHOR  : M. Scott
 *
 *    PURPOSE : Definition of class EC2  (Arithmetic on an Elliptic Curve,
 *               over GF(2^m)
 *
 *    NOTE    : Must be used in conjunction with ec2.cpp and big.cpp
 *              The active curve is set dynamically (via the Big ecurve2()
 *              routine) - so beware the pitfalls implicit in declaring
 *              static or global EC2's (which are initialised before the
 *              curve is set!). Uninitialised data is OK
 */

#ifndef EC2_H
#define EC2_H

#include <cstring>
#include "big.h"

#ifdef GF2MS
#define MR_INIT_EC2 memset(mem,0,mr_ecp_reserve(1,GF2MS)); p=(epoint *)epoint_init_mem_variable(mem,0,GF2MS);
#else
#define MR_INIT_EC2 mem=(char *)ecp_memalloc(1); p=(epoint *)epoint_init_mem(mem,0);
#endif

class EC2
{
    epoint *p;
#ifdef GF2MS
    char mem[mr_ecp_reserve(1,GF2MS)];
#else
    char *mem;
#endif

public:
    EC2()                         { MR_INIT_EC2}

    EC2(const Big &x,const Big& y)  {MR_INIT_EC2
                                   epoint2_set(x.getbig(),y.getbig(),0,p); }

  // This next constructor restores a point on the curve from "compressed"
  // data, that is the full x co-ordinate, and the LSB of y/x  (0 or 1)

    EC2(const Big& x,int cb)       {MR_INIT_EC2
                                   epoint2_set(x.getbig(),x.getbig(),cb,p); }

    EC2(const EC2 &b)             {MR_INIT_EC2 epoint2_copy(b.p,p);}

    epoint *get_point() const;

    EC2& operator=(const EC2& b)  {epoint2_copy(b.p,p);return *this;}

    EC2& operator+=(const EC2& b) {ecurve2_add(b.p,p); return *this;}
    EC2& operator-=(const EC2& b) {ecurve2_sub(b.p,p); return *this;}

  // Multiplication of a point by an integer.

    EC2& operator*=(const Big& k) {ecurve2_mult(k.getbig(),p,p); return *this;}
    big add(const EC2& b)         {return ecurve2_add(b.p,p); }
                                  // returns line slope as a big
    big sub(const EC2& b)         {return ecurve2_sub(b.p,p); }

    void clear() {epoint2_set(NULL,NULL,0,p);}
    BOOL set(const Big& x,const Big& y)    {return epoint2_set(x.getbig(),y.getbig(),0,p);}
    int get(Big& x,Big& y) const;
    BOOL iszero() const;
  // This gets the point in compressed form. Return value is LSB of y-coordinate
    int get(Big& x) const;

    void getx(Big &x) const;
    void getxy(Big &x,Big& y) const;
    void getxyz(Big &x,Big &y,Big& z) const;

  // point compression

  // This sets the point from compressed form. cb is LSB of y/x

    BOOL set(const Big& x,int cb=0)  {return epoint2_set(x.getbig(),x.getbig(),cb,p);}

    friend EC2 operator-(const EC2&);
    friend void multi_add(int,EC2 *,EC2 *);

    friend EC2 mul(const Big&, const EC2&, const Big&, const EC2&);
    friend EC2 mul(int, const Big *, EC2 *);

    friend void normalise(EC2 &e) {epoint2_norm(e.p);}

    friend BOOL operator==(const EC2& a,const EC2& b)
                                  {return epoint2_comp(a.p,b.p);}
    friend BOOL operator!=(const EC2& a,const EC2& b)
                                  {return (!epoint2_comp(a.p,b.p));}

    friend EC2 operator*(const Big &,const EC2&);

#ifndef MR_NO_STANDARD_IO

    friend ostream& operator<<(ostream&,const EC2&);

#endif

    ~EC2()
    {
#ifndef GF2MS
        mr_free(mem);
#endif
    }
};

#endif


text:
# Minimum Depth of Binary Tree

[Leetcode](https://leetcode.com/problems/minimum-depth-of-binary-tree/)

題意:

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

解題思路:

中間兩個if需要,因為要防止 [1,2]這種情況

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null) {
            return minDepth(root.right) + 1;
        }
        if (root.right == null) {
            return minDepth(root.left) + 1;
        }
        return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }
}
```


text:
@echo off
setlocal enabledelayedexpansion
cd /d %~dp0

set sourceFiles=
for /f "delims=" %%a in ('dir /b src\*.c') do set sourceFiles=!sourceFiles! src\%%a

set emccOptions=%sourceFiles% ^
	-DJS_INTEROP ^
	-Wno-pointer-sign ^
	-Oz ^
	-s NO_EXIT_RUNTIME=1 ^
	-s RESERVED_FUNCTION_POINTERS=20 ^
	-s ASSERTIONS=1 ^
	-s EXPORTED_FUNCTIONS="['_main', '_JSInterop_CallDotNet', '_Debugger_Continue', '_Debugger_SetBreakPoint', '_Debugger_Step', '_Debugger_Reset', '_Debugger_Clear_BreakPoints']" ^
	-s MODULARIZE=1 ^
	-s ALLOW_MEMORY_GROWTH=1 ^
	-s EXPORT_NAME='ModuleFunc' ^
	-s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE="['$Browser']" ^
	-s EXTRA_EXPORTED_RUNTIME_METHODS="['ccall', 'FS_createPreloadedFile']" ^
	--js-library js-interop.js

REM --pre-js pre.js ^
REM --post-js post.js ^

REM set emccOptions=%emccOptions% -DDEBUG_PRINT

set outputRoot=..\..\..\wwwroot\js

echo -------------------------------------------
echo --- Starting native web assembly build
call emcc %emccOptions% -s WASM=1 -o %outputRoot%\wasm\dna.js
echo export { ModuleFunc }; >> %outputRoot%\wasm\dna.js

echo -------------------------------------------
echo --- Starting asm.js build
call emcc %emccOptions% -s WASM=0 -o %outputRoot%\asmjs\dna.js
echo export { ModuleFunc }; >> %outputRoot%\asmjs\dna.js


text:
class DropUniqueIndexOnAccessCodeInSurveys < ActiveRecord::Migration
  def self.up
    remove_index( :surveys, :name => 'surveys_ac_idx' )
  end

  def self.down
    add_index(:surveys, :access_code, :name => 'surveys_ac_idx')
  end
end


text:
from __future__ import print_function

import os
import sys
import time

from subprocess import CalledProcessError, check_output, STDOUT

failed = False
letsencrypt_cert_ids = {{ letsencrypt_cert_ids }}

for site in {{ sites_using_letsencrypt }}:
    csr_path = os.path.join('{{ acme_tiny_data_directory }}', 'csrs', '{}-{}.csr'.format(site, letsencrypt_cert_ids[site]))
    bundled_cert_path = os.path.join('{{ letsencrypt_certs_dir }}', '{}-bundled.cert'.format(site))
    bundled_hashed_cert_path = os.path.join('{{ letsencrypt_certs_dir }}', '{}-{}-bundled.cert'.format(site, letsencrypt_cert_ids[site]))

    # Generate or update root cert if needed
    if not os.access(csr_path, os.F_OK):
        failed = True
        print('The required CSR file {} does not exist. This could happen if you changed site_hosts and have '
              'not yet rerun the letsencrypt role. Create the CSR file by re-provisioning (running the Trellis '
              'server.yml playbook) with `--tags letsencrypt`'.format(csr_path), file=sys.stderr)
        continue

    elif os.access(bundled_hashed_cert_path, os.F_OK) and time.time() - os.stat(bundled_hashed_cert_path).st_mtime < {{ letsencrypt_min_renewal_age }} * 86400:
        print('Certificate file {} already exists and is younger than {{ letsencrypt_min_renewal_age }} days. '
              'Not creating a new certificate.'.format(bundled_hashed_cert_path))

    else:
        cmd = ('/usr/bin/env python {{ acme_tiny_software_directory }}/acme_tiny.py '
            '--quiet '
            '--ca {{ letsencrypt_ca }} '
            '--account-key {{ letsencrypt_account_key }} '
            '--csr {} '
            '--contact {{ letsencrypt_contact_emails | map('regex_replace', '(^.*$)', 'mailto:\\1') | join (' ') }} '
            '--acme-dir {{ acme_tiny_challenges_directory }}'
        ).format(csr_path)

        try:
            new_bundled_cert = check_output(cmd, stderr=STDOUT, shell=True, universal_newlines=True)
        except CalledProcessError as e:
            failed = True
            print('Error while generating certificate for {}\n{}'.format(site, e.output), file=sys.stderr)
            continue
        else:
            with open(bundled_hashed_cert_path, 'w') as bundled_hashed_cert_file:
                bundled_hashed_cert_file.write(new_bundled_cert)
            with open(bundled_cert_path, 'w') as bundled_cert_file:
                bundled_cert_file.write(new_bundled_cert)

    if not os.access(bundled_cert_path, os.F_OK):
        with open(bundled_hashed_cert_path, 'rb') as bundled_hashed_cert_file:
            bundled_hashed_cert = bundled_hashed_cert_file.read()

            with open(bundled_cert_path, 'w') as bundled_cert_file:
                bundled_cert_file.write(bundled_hashed_cert)
                print('Created bundled certificate {}'.format(bundled_cert_path))

if failed:
    sys.exit(1)


text:
% ------------------------------------------------------
% This script estimates the marker coordinates shifted to skin surface and
% the joint center positions from measured and estimated marker coordinates
% according to predictive methods given in different references.
% ------------------------------------------------------
% Technische Universität Darmstadt
% Department of Computer Science
% Simulation, Systems Optimization and Robotics Group
% Janis Wojtusch (wojtusch@sim.tu-darmstadt.de), 2016
% Licensed under BSD 3-Clause License
% ------------------------------------------------------

% Clean up workspace
clc;
clear all;
close all;

% Set parameters
markerSize = 19;
supportThickness = 3;
clothThickness = 4;
markerOffset = markerSize / 2 + supportThickness;
initialStartFrame = 7000;
initialEndFrame = 9000;
datasets = {
    '1.1', ...
    '1.2', ...
    '1.3', ...
    '2.1', ...
    '2.2', ...
    '2.3', ...
    '3', ...
    '4', ...
    '5.1', ...
    '5.2', ...
    '6', ...
    '7', ...
    '8' ...
};
subjects = {
    'A', ...
    'B' ...
};

% Add functions to search path
addpath('Scripts');

for subjectIndex = 1:length(subjects)
    for datasetIndex = 1:length(datasets)

        % Set parameters
        startFrame = 1;
        endFrame = inf;
        dataset = datasets{datasetIndex};
        subject = subjects{subjectIndex};
        fprintf('STATUS: Processing dataset %s %s.\n', subject, dataset);

        % Load data file
        file = getFile(subject, dataset);
        if file
            variables = load(file);
            if isfield(variables, 'motion') && isfield(variables, 'ground')
                motion = variables.motion;
                ground = variables.ground;
            else
                fprintf('WARNING: No matching data found!\n');
                continue;
            end
        else
            fprintf('WARNING: No matching data file found!\n');
            continue;
        end

        % Set end frame after loading file
        if (endFrame > motion.frames) || (endFrame == inf)
            endFrame = motion.frames;
        end
        if (startFrame > endFrame) || (startFrame < 1)
            startFrame = endFrame;
        end

        % Approximation of initial leg length by computing the average length
        % between ASIS_L and MM_L as well as ASIS_R and MM_R as stated in the
        % C-Motion Wiki
        initialASIS_L = getAverageMarker('ASIS_L', 'marker', initialStartFrame, initialEndFrame);
        initialASIS_R = getAverageMarker('ASIS_R', 'marker', initialStartFrame, initialEndFrame);
        initialMM_L = getAverageMarker('MM_L', 'marker', initialStartFrame, initialEndFrame);
        initialMM_R = getAverageMarker('MM_R', 'marker', initialStartFrame, initialEndFrame);
        legLength = (norm(initialMM_L - initialASIS_L) + norm(initialMM_R - initialASIS_R)) / 2;
        fprintf('Average leg length from ASIS to MM: %.1f mm\n', legLength);
        clear initialASIS_L initialASIS_R initialMM_L initialMM_R

        % Computation of initial values for the toe joints TJ_L and TJ_R according
        % to [Zatsiorsky1998] with assuming the height of the joint center in the
        % middle between ground and MT2 defined by the foot plane given by CAL, MT2
        % and MT5
        initialMT2_L = getAverageMarker('MT2_L', 'marker', initialStartFrame, initialEndFrame);
        initialMT2_R = getAverageMarker('MT2_R', 'marker', initialStartFrame, initialEndFrame);
        initialMT5_L = getAverageMarker('MT5_L', 'marker', initialStartFrame, initialEndFrame);
        initialMT5_R = getAverageMarker('MT5_R', 'marker', initialStartFrame, initialEndFrame);
        initialCAL_L = getAverageMarker('CAL_L', 'marker', initialStartFrame, initialEndFrame);
        initialCAL_R = getAverageMarker('CAL_R', 'marker', initialStartFrame, initialEndFrame);
        footNormal_L = cross((initialCAL_L - initialMT5_L), (initialMT5_L - initialMT2_L));
        footNormal_L = footNormal_L / norm(footNormal_L);
        groundPosition = ground.groundPosition;
        groundNormal = ground.groundNormal;
        distanceMT2_L_TJ_L = (dot(groundNormal, (groundPosition - initialMT2_L)) / dot(groundNormal, footNormal_L) - (markerOffset)) / 2;
        footNormal_R = cross((initialMT5_R - initialMT2_R), (initialCAL_R - initialMT5_R));
        footNormal_R = footNormal_R / norm(footNormal_R);
        distanceMT2_R_TJ_R = (dot(groundNormal, (groundPosition - initialMT2_R)) / dot(groundNormal, footNormal_R) - (markerOffset)) / 2;
        fprintf('Distance from MT2_L_s to toe joint: %.1f mm\nDistance from MT2_R_s to toe joint: %.1f mm\n', distanceMT2_L_TJ_L, distanceMT2_R_TJ_R);
        clear initialMT2_L initialMT2_R initialMT5_L initialMT5_R initialCAL_L initialCAL_R footNormal_L footNormal_R;

        % Estimate joint centers
        if ~exist('motion.surfaceX', 'var')
            motion.surfaceX = zeros(34, motion.frames);
        end
        if ~exist('motion.surfaceY', 'var')
            motion.surfaceY = zeros(34, motion.frames);
        end
        if ~exist('motion.surfaceZ', 'var')
            motion.surfaceZ = zeros(34, motion.frames);
        end
        if ~exist('motion.surfaceLabels', 'var')
            motion.surfaceLabels = {};
        end
        if ~exist('motion.jointX.estimated', 'var')
            motion.jointX.estimated = zeros(15, motion.frames);
        end
        if ~exist('motion.jointY.estimated', 'var')
            motion.jointY.estimated = zeros(15, motion.frames);
        end
        if ~exist('motion.jointZ.estimated', 'var')
            motion.jointZ.estimated = zeros(15, motion.frames);
        end
        if ~exist('motion.jointLabels.estimated', 'var')
            motion.jointLabels.estimated = {};
        end
        statusCounter = 0;
        for currentFrame = startFrame:endFrame

            % Get marker coordinates
            vectorTRA_L_m = getMarker('TRA_L', 'marker', currentFrame);
            vectorTRA_R_m = getMarker('TRA_R', 'marker', currentFrame);
            vectorGLA_m = getMarker('GLA', 'marker', currentFrame);
            vectorC7_m = getMarker('C7', 'marker', currentFrame);
            vectorT8_m = getMarker('T8', 'marker', currentFrame);
            vectorT12_m = getMarker('T12', 'marker', currentFrame);
            vectorSUP_m = getMarker('SUP', 'marker', currentFrame);
            vectorACR_L_m = getMarker('ACR_L', 'marker', currentFrame);
            vectorACR_R_m = getMarker('ACR_R', 'marker', currentFrame);
            vectorLHC_L_m = getMarker('LHC_L', 'marker', currentFrame);
            vectorLHC_R_m = getMarker('LHC_R', 'marker', currentFrame);
            vectorWRI_L_m = getMarker('WRI_L', 'marker', currentFrame);
            vectorWRI_R_m = getMarker('WRI_R', 'marker', currentFrame);
            vectorASIS_L_m = getMarker('ASIS_L', 'marker', currentFrame);
            vectorASIS_R_m = getMarker('ASIS_R', 'marker', currentFrame);
            vectorPSIS_L_m = getMarker('PSIS_L', 'marker', currentFrame);
            vectorPSIS_R_m = getMarker('PSIS_R', 'marker', currentFrame);
            vectorPS_m = getMarker('PS', 'marker', currentFrame);
            vectorGTR_L_m = getMarker('GTR_L', 'marker', currentFrame);
            vectorGTR_R_m = getMarker('GTR_R', 'marker', currentFrame);
            vectorLFC_L_m = getMarker('LFC_L', 'marker', currentFrame);
            vectorLFC_R_m = getMarker('LFC_R', 'marker', currentFrame);
            vectorMFC_L_m = getMarker('MFC_L', 'marker', currentFrame);
            vectorMFC_R_m = getMarker('MFC_R', 'marker', currentFrame);
            vectorLM_L_m = getMarker('LM_L', 'marker', currentFrame);
            vectorLM_R_m = getMarker('LM_R', 'marker', currentFrame);
            vectorMM_L_m = getMarker('MM_L', 'marker', currentFrame);
            vectorMM_R_m = getMarker('MM_R', 'marker', currentFrame);
            vectorHAL_L_m = getMarker('HAL_L', 'marker', currentFrame);
            vectorHAL_R_m = getMarker('HAL_R', 'marker', currentFrame);
            vectorMT2_L_m = getMarker('MT2_L', 'marker', currentFrame);
            vectorMT2_R_m = getMarker('MT2_R', 'marker', currentFrame);
            vectorMT5_L_m = getMarker('MT5_L', 'marker', currentFrame);
            vectorMT5_R_m = getMarker('MT5_R', 'marker', currentFrame);
            vectorCAL_L_m = getMarker('CAL_L', 'marker', currentFrame);
            vectorCAL_R_m = getMarker('CAL_R', 'marker', currentFrame);

            % Estimate marker coordinates shifted to skin surface
            % TRA markers
            vectorTRA_R_TRA_L = vectorTRA_L_m - vectorTRA_R_m;
            directionTRA = vectorTRA_R_TRA_L / norm(vectorTRA_R_TRA_L);
            vectorTRA_L_s = vectorTRA_L_m - markerOffset * directionTRA;
            vectorTRA_R_s = vectorTRA_R_m + markerOffset * directionTRA;
            % GLA marker
            vectorGLA_TRA = (vectorTRA_R_m + vectorTRA_R_TRA_L / 2) - vectorGLA_m;
            directionGLA = vectorGLA_TRA / norm(vectorGLA_TRA);
            vectorGLA_s = vectorGLA_m + markerOffset * directionGLA;
            % C7 and SUP markers
            vectorC7_SUP = vectorSUP_m - vectorC7_m;
            directionC7_SUP = vectorC7_SUP / norm(vectorC7_SUP);
            vectorC7_s = vectorC7_m + markerOffset * directionC7_SUP;
            vectorSUP_s = vectorSUP_m - markerOffset * directionC7_SUP;
            % T12 marker
            vectorT12_T8 = vectorT8_m - vectorT12_m;
            vectorACR_R_ACR_L = vectorACR_L_m - vectorACR_R_m;
            rotatedVector = rotateVector(vectorT12_T8 / norm(vectorT12_T8), (90 * pi / 180), vectorACR_R_ACR_L);
            directionT12 = rotatedVector / norm(rotatedVector);
            vectorT12_s = vectorT12_m + markerOffset * directionT12;
            % T8 marker
            directionT8 = (directionC7_SUP + directionT12) / norm(directionC7_SUP + directionT12);
            vectorT8_s = vectorT8_m + markerOffset * directionT8;
            % ACR markers
            crossProduct = cross(vectorACR_R_ACR_L, vectorC7_SUP);
            directionACR = crossProduct / norm(crossProduct);
            vectorACR_L_s = vectorACR_L_m + markerOffset * directionACR;
            vectorACR_R_s = vectorACR_R_m + markerOffset * directionACR;
            % ASIS and PSIS markers
            vectorASIS_PSIS = (vectorPSIS_R_m + (vectorPSIS_L_m - vectorPSIS_R_m) / 2) - (vectorASIS_R_m + (vectorASIS_L_m - vectorASIS_R_m) / 2);
            directionASIS_PSIS = vectorASIS_PSIS / norm(vectorASIS_PSIS);
            vectorASIS_L_s = vectorASIS_L_m + markerOffset * directionASIS_PSIS;
            vectorPSIS_L_s = vectorPSIS_L_m - markerOffset * directionASIS_PSIS;
            vectorASIS_R_s = vectorASIS_R_m + markerOffset * directionASIS_PSIS;
            vectorPSIS_R_s = vectorPSIS_R_m - markerOffset * directionASIS_PSIS;
            % PS marker
            vectorPS_PSIS = (vectorPSIS_R_m + (vectorPSIS_L_m - vectorPSIS_R_m) / 2) - vectorPS_m;
            directionPS = vectorPS_PSIS / norm(vectorPS_PSIS);
            vectorPS_s = vectorPS_m + ((markerSize) / 2 + clothThickness) * directionPS;
            % GTR markers
            vectorGTR_R_GTR_L = vectorGTR_L_m - vectorGTR_R_m;
            directionGTR = vectorGTR_R_GTR_L / norm(vectorGTR_R_GTR_L);
            vectorGTR_L_s = vectorGTR_L_m - markerOffset * directionGTR;
            vectorGTR_R_s = vectorGTR_R_m + markerOffset * directionGTR;
            % LFC and MFC markers
            vectorLFC_MFC = vectorMFC_L_m - vectorLFC_L_m;
            directionLFC_MFC = vectorLFC_MFC / norm(vectorLFC_MFC);
            vectorLFC_L_s = vectorLFC_L_m + markerOffset * directionLFC_MFC;
            vectorMFC_L_s = vectorMFC_L_m - markerOffset * directionLFC_MFC;
            vectorLFC_MFC = vectorMFC_R_m - vectorLFC_R_m;
            directionLFC_MFC = vectorLFC_MFC / norm(vectorLFC_MFC);
            vectorLFC_R_s = vectorLFC_R_m + markerOffset * directionLFC_MFC;
            vectorMFC_R_s = vectorMFC_R_m - markerOffset * directionLFC_MFC;
            % LM and MM markers
            vectorLM_MM = vectorMM_L_m - vectorLM_L_m;
            directionLM_MM = vectorLM_MM / norm(vectorLM_MM);
            vectorLM_L_s = vectorLM_L_m + markerOffset * directionLM_MM;
            vectorMM_L_s = vectorMM_L_m - markerOffset * directionLM_MM;
            vectorLM_MM = vectorMM_R_m - vectorLM_R_m;
            directionLM_MM = vectorLM_MM / norm(vectorLM_MM);
            vectorLM_R_s = vectorLM_R_m + markerOffset * directionLM_MM;
            vectorMM_R_s = vectorMM_R_m - markerOffset * directionLM_MM;
            % CAL markers
            vectorCAL_MT2 = vectorMT2_L_m - vectorCAL_L_m;
            directionCAL = vectorCAL_MT2 / norm(vectorCAL_MT2);
            vectorCAL_L_s = vectorCAL_L_m + markerOffset * directionCAL;
            vectorCAL_MT2 = vectorMT2_R_m - vectorCAL_R_m;
            directionCAL = vectorCAL_MT2 / norm(vectorCAL_MT2);
            vectorCAL_R_s = vectorCAL_R_m + markerOffset * directionCAL;
            % HAL, MT2 and MT5  markers
            crossProduct = cross((vectorCAL_L_m - vectorMT5_L_m), (vectorMT5_L_m - vectorMT2_L_m));
            directionMT_HAL = crossProduct / norm(crossProduct);
            vectorMT2_L_s = vectorMT2_L_m + markerOffset * directionMT_HAL;
            vectorMT5_L_s = vectorMT5_L_m + markerOffset * directionMT_HAL;
            vectorHAL_L_s = vectorHAL_L_m + markerOffset * directionMT_HAL;
            crossProduct = cross((vectorMT5_R_m - vectorMT2_R_m), (vectorCAL_R_m - vectorMT5_R_m));
            directionMT_HAL = crossProduct / norm(crossProduct);
            vectorMT2_R_s = vectorMT2_R_m + markerOffset * directionMT_HAL;
            vectorMT5_R_s = vectorMT5_R_m + markerOffset * directionMT_HAL;
            vectorHAL_R_s = vectorHAL_R_m + markerOffset * directionMT_HAL;
            clear vectorTRA_R_TRA_L vectorGLA_TRA vectorC7_SUP vectorT12_T8 vectorACR_R_ACR_L ...
                vectorASIS_PSIS vectorLFC_MFC vectorGTR_R_GTR_L vectorLM_MM vectorCAL_MT2 ...
                directionTRA directionGLA directionC7_SUP directionT8 directionT12 ...
                directionACR directionASIS_PSIS directionPS directionGTR directionLFC_MFC ...
                directionLM_MM directionCAL directionMT_HAL rotatedVector crossProduct;

            % Lower neck joint (LNJ)
            % Estimate the lower neck joint LNJ (C7/T1) according to [Reed1999]
            % with using the connection of the ACR markers as rotation axis
            vectorC7_SUP = vectorSUP_s - vectorC7_s;
            vectorACR_R_ACR_L = vectorACR_L_s - vectorACR_R_s;
            vectorLNJ = vectorC7_s + rotateVector((0.55 * vectorC7_SUP), -(8 * pi / 180), vectorACR_R_ACR_L);
            clear vectorC7_SUP vectorACR_R_ACR_L;

            % Upper lumbar joint (ULJ)
            % Estimate the upper lumbar joint ULJ (T12/L1) according to [Reed1999],
            % [Dumas2015] with using the connection of the ACR markers as rotation
            % axis
            vectorC7_SUP = vectorSUP_s - vectorC7_s;
            vectorT12_T8 = vectorT8_s - vectorT12_s;
            vectorACR_R_ACR_L = vectorACR_L_s - vectorACR_R_s;
            if strcmp(subject, 'A')
                vectorULJ = vectorT12_s + rotateVector((0.53 * norm(vectorC7_SUP) * vectorT12_T8 / norm(vectorT12_T8)), (83 * pi / 180), vectorACR_R_ACR_L);
            else
                vectorULJ = vectorT12_s + rotateVector((0.52 * norm(vectorC7_SUP) * vectorT12_T8 / norm(vectorT12_T8)), (94 * pi / 180), vectorACR_R_ACR_L);
            end
            clear vectorC7_SUP vectorT12_T8 vectorACR_R_ACR_L;

            % Shoulder joints (SJ_L, SJ_R)
            % Estimate the shoulder joints SJ_L and SJ_R according to [Reed1999]
            % with using the connection of the ACR markers as rotation axis
            vectorC7_SUP = vectorSUP_s - vectorC7_s;
            vectorACR_R_ACR_L = vectorACR_L_s - vectorACR_R_s;
            vectorSJ_L = vectorACR_L_s + rotateVector((0.42 * vectorC7_SUP), (67 * pi / 180), vectorACR_R_ACR_L);
            vectorSJ_R = vectorACR_R_s + rotateVector((0.42 * vectorC7_SUP), (67 * pi / 180), vectorACR_R_ACR_L);
            clear vectorC7_SUP vectorACR_R_ACR_L;

            % Estimate marker coordinates shifted to skin
            % LHC markers
            vectorLHC_WRI = vectorWRI_L_m - vectorLHC_L_m;
            vectorLHC_SJ = vectorSJ_L - vectorLHC_L_m;
            crossProduct = cross(vectorLHC_WRI, vectorLHC_SJ);
            vectorLHC_L_s = vectorLHC_L_m + markerOffset * crossProduct / norm(crossProduct);
            vectorLHC_WRI = vectorWRI_R_m - vectorLHC_R_m;
            vectorLHC_SJ = vectorSJ_R - vectorLHC_R_m;
            crossProduct = cross(vectorLHC_SJ, vectorLHC_WRI);
            vectorLHC_R_s = vectorLHC_R_m + markerOffset * crossProduct / norm(crossProduct);
            clear crossProduct vectorLHC_WRI vectorLHC_SJ;

            % Elbow joints (EJ_L, EJ_R)
            % Estimate the elbow joints EJ_L and EJ_R according to [Reed1999]
            vectorLHC_WRI = vectorWRI_L_m - vectorLHC_L_s;
            vectorLHC_SJ = vectorSJ_L - vectorLHC_L_s;
            crossProduct = cross(vectorLHC_WRI, vectorLHC_SJ);
            vectorEJ_L = vectorLHC_L_s + 0.155 * norm(vectorLHC_WRI) * crossProduct / norm(crossProduct);
            vectorLHC_WRI = vectorWRI_R_m - vectorLHC_R_s;
            vectorLHC_SJ = vectorSJ_R - vectorLHC_R_s;
            crossProduct = cross(vectorLHC_SJ, vectorLHC_WRI);
            vectorEJ_R = vectorLHC_R_s + 0.155 * norm(vectorLHC_WRI) * crossProduct / norm(crossProduct);
            clear crossProduct vectorLHC_WRI vectorLHC_SJ;

            % Lower lumbar joint (LLJ)
            % Estimate the lower lumbar joint LLJ (L5/S1) according to [Reed1999]
            vectorASIS_R_ASIS_L = vectorASIS_L_s - vectorASIS_R_s;
            axisY = vectorASIS_R_ASIS_L / norm(vectorASIS_R_ASIS_L);
            vectorASIS_R_PS = vectorPS_s - vectorASIS_R_s;
            vectorCP_s = vectorASIS_R_s + dot(vectorASIS_R_PS, axisY) / dot(axisY, axisY) * axisY;
            axisZ_s = (vectorCP_s - vectorPS_s) / norm(vectorCP_s - vectorPS_s);
            axisX_s = cross(axisY, axisZ_s);
            vectorASIS_L_b = vectorASIS_L_s - 10 * axisX_s;
            vectorASIS_R_b = vectorASIS_R_s - 10 * axisX_s;
            vectorPS_b = vectorPS_s - 17.7 * axisX_s - 17.7 * axisZ_s;
            % Ambiguous value for the flesh margin correction vector for the PSIS
            % markers in [Reed1999]: 10 mm in text and 5 mm in table 6
            vectorPSIS_L_b = vectorPSIS_L_s + 5 * axisX_s;
            vectorPSIS_R_b = vectorPSIS_R_s + 5 * axisX_s;
            vectorASIS_R_b_PS_b = vectorPS_b - vectorASIS_R_b;
            vectorASIS_R_b_ASIS_L_b = vectorASIS_L_b - vectorASIS_R_b;
            vectorCP_b = vectorASIS_R_b + (dot(vectorASIS_R_b_PS_b, axisY) / dot(axisY, axisY) * axisY);
            axisZ_b = (vectorCP_b - vectorPS_b) / norm(vectorCP_b - vectorPS_b);
            axisX_b = cross(axisY, axisZ_b);
            pelvisWidth = norm(vectorASIS_R_b_ASIS_L_b);
            pelvisHeight = norm(vectorCP_b - vectorPS_b);
            pelvisDepth = (norm(vectorPSIS_L_b - vectorASIS_L_b) + norm(vectorPSIS_R_b - vectorASIS_R_b)) / 2;
            if strcmp(subject, 'A')
                vectorLLJ = vectorCP_b - 0.425 * pelvisDepth * axisX_b + 0.452 * pelvisHeight * axisZ_b;
            else
                vectorLLJ = vectorCP_b - 0.377 * pelvisDepth * axisX_b + 0.399 * pelvisHeight * axisZ_b;
            end
            clear vectorASIS_R_ASIS_L vectorASIS_R_PS vectorCP_s vectorASIS_L_b vectorASIS_R_b ...
                vectorPS_b vectorPSIS_L_b vectorPSIS_R_b vectorASIS_R_b_PS_b vectorASIS_R_b_ASIS_L_b ...
                vectorCP_b axisX_s axisY axisZ_s axisX_b axisZ_b;

            % Hip joints (HJ_L, HJ_R)
            methodHipJoint = 'Harrington2007';
            switch methodHipJoint

                case 'Harrington2007'
                % Estimate the hip joints HJ_L and HJ_R according to [Harrington2007]
                % with estimating the bone marker positions according to [Reed1999]
                % and assuming a soft tissue offset of 10 mm
                vectorASIS_R_ASIS_L = vectorASIS_R_s - vectorASIS_L_s;
                axisZ = vectorASIS_R_ASIS_L / norm(vectorASIS_R_ASIS_L);
                vectorASIS_R_PS = vectorPS_s - vectorASIS_R_s;
                vectorCP_s = vectorASIS_R_s + dot(vectorASIS_R_PS, axisZ) / dot(axisZ, axisZ) * axisZ;
                axisY_s = (vectorCP_s - vectorPS_s) / norm(vectorCP_s - vectorPS_s);
                axisX_s = cross(axisY_s, axisZ);
                vectorASIS_L_b = vectorASIS_L_s - 10 * axisX_s;
                vectorASIS_R_b = vectorASIS_R_s - 10 * axisX_s;
                % Ambiguous value for the flesh margin correction vector for the PSIS
                % markers in [Reed1999]: 10 mm in text and 5 mm in table 6
                vectorPSIS_L_b = vectorPSIS_L_s + 5 * axisX_s;
                vectorPSIS_R_b = vectorPSIS_R_s + 5 * axisX_s;
                vectorASIS_R_b_ASIS_L_b = vectorASIS_R_b - vectorASIS_L_b;
                vectorPSIS_R_b_PSIS_L_b = vectorPSIS_R_b - vectorPSIS_L_b;
                vectorCP_b = vectorASIS_L_b + 0.5 * vectorASIS_R_b_ASIS_L_b;
                axisX_b = (vectorCP_b - (vectorPSIS_L_b + 0.5 * vectorPSIS_R_b_PSIS_L_b)) / norm(vectorCP_b - (vectorPSIS_L_b + 0.5 * vectorPSIS_R_b_PSIS_L_b));
                axisY_b = cross(axisZ, axisX_b);
                pelvisWidth = norm(vectorASIS_R_b_ASIS_L_b);
                pelvisDepth = norm(vectorCP_b - (vectorPSIS_L_b + 0.5 * vectorPSIS_R_b_PSIS_L_b));
                vectorHJ_L = vectorCP_b + (-0.24 * pelvisDepth - 9.9) * axisX_b + (-0.16 * pelvisWidth - 0.04 * legLength - 7.1) * axisY_b - (0.28 * pelvisDepth + 0.16 * pelvisWidth + 7.9) * axisZ;
                vectorHJ_R = vectorCP_b + (-0.24 * pelvisDepth - 9.9) * axisX_b + (-0.16 * pelvisWidth - 0.04 * legLength - 7.1) * axisY_b + (0.28 * pelvisDepth + 0.16 * pelvisWidth + 7.9) * axisZ;
                clear pelvisWidth pelvisDepth pelvisDepth vectorASIS_R_ASIS_L vectorASIS_R_PS ...
                    vectorCP_s vectorASIS_L_b vectorASIS_R_b vectorPSIS_L_b vectorPSIS_R_b ...
                    vectorASIS_R_b_ASIS_L_b vectorPSIS_R_b_PSIS_L_b vectorCP_b axisX_s axisY ...
                    axisZ_s axisX_b axisZ_b;

                case 'Reed1999'
                % Estimate the hip joints HJ_L and HJ_R according to [Reed1999]
                vectorASIS_R_ASIS_L = vectorASIS_L_s - vectorASIS_R_s;
                axisY = vectorASIS_R_ASIS_L / norm(vectorASIS_R_ASIS_L);
                vectorASIS_R_PS = vectorPS_s - vectorASIS_R_s;
                vectorCP_s = vectorASIS_R_s + dot(vectorASIS_R_PS, axisY) / dot(axisY, axisY) * axisY;
                axisZ_s = (vectorCP_s - vectorPS_s) / norm(vectorCP_s - vectorPS_s);
                axisX_s = cross(axisY, axisZ_s);
                vectorASIS_L_b = vectorASIS_L_s - 10 * axisX_s;
                vectorASIS_R_b = vectorASIS_R_s - 10 * axisX_s;
                vectorPS_b = vectorPS_s - 17.7 * axisX_s - 17.7 * axisZ_s;
                % Ambiguous value for the flesh margin correction vector for the PSIS
                % markers in [Reed1999]: 10 mm in text and 5 mm in table 6
                %vectorPSIS_L_b = vectorPSIS_L_s + 10 * axisX_s;
                %vectorPSIS_R_b = vectorPSIS_R_s + 10 * axisX_s;
                vectorASIS_R_b_PS_b = vectorPS_b - vectorASIS_R_b;
                vectorASIS_R_b_ASIS_L_b = vectorASIS_L_b - vectorASIS_R_b;
                vectorCP_b = vectorASIS_R_b + (dot(vectorASIS_R_b_PS_b, axisY) / dot(axisY, axisY) * axisY);
                axisZ_b = (vectorCP_b - vectorPS_b) / norm(vectorCP_b - vectorPS_b);
                axisX_b = cross(axisY, axisZ_b);
                pelvisWidth = norm(vectorASIS_R_b_ASIS_L_b);
                %pelvisHeight = norm(vectorCP_b - vectorPS_b);
                %pelvisDepth = (norm(vectorPSIS_L_b - vectorASIS_L_b) + norm(vectorPSIS_R_b - vectorASIS_R_b)) / 2;
                %vectorHJ_L = vectorCP_b - 0.34 * pelvisDepth * axisX_b + 0.36 * pelvisWidth * axisY - 0.79 * pelvisHeight * axisZ_b;
                %vectorHJ_R = vectorCP_b - 0.34 * pelvisDepth * axisX_b - 0.36 * pelvisWidth * axisY - 0.79 * pelvisHeight * axisZ_b;
                vectorHJ_L = vectorCP_b - 0.24 * pelvisWidth * axisX_b + 0.36 * pelvisWidth * axisY - 0.3 * pelvisWidth * axisZ_b;
                vectorHJ_R = vectorCP_b - 0.24 * pelvisWidth * axisX_b - 0.36 * pelvisWidth * axisY - 0.3 * pelvisWidth * axisZ_b;
                clear pelvisWidth pelvisHeight pelvisDepth vectorASIS_R_ASIS_L vectorASIS_R_PS ...
                    vectorCP_s vectorASIS_L_b vectorASIS_R_b vectorPS_b vectorPSIS_L_b ...
                    vectorPSIS_R_b vectorASIS_R_b_PS_b vectorASIS_R_b_ASIS_L_b vectorCP_b ...
                    axisX_s axisY axisZ_s axisX_b axisZ_b;

                case 'Leardini1999'
                % Estimate the hip joints HJ_L and HJ_R according to [Leardini1999]
                % with estimating the bone marker positions according to [Reed1999]
                % and assuming a soft tissue offset of 10 mm
                vectorASIS_R_ASIS_L = vectorASIS_R_s - vectorASIS_L_s;
                axisZ = vectorASIS_R_ASIS_L / norm(vectorASIS_R_ASIS_L);
                vectorASIS_R_PS = vectorPS_s - vectorASIS_R_s;
                vectorCP_s = vectorASIS_R_s + dot(vectorASIS_R_PS, axisZ) / dot(axisZ, axisZ) * axisZ;
                axisY_s = (vectorCP_s - vectorPS_s) / norm(vectorCP_s - vectorPS_s);
                axisX_s = cross(axisY_s, axisZ);
                vectorASIS_L_b = vectorASIS_L_s - 10 * axisX_s;
                vectorASIS_R_b = vectorASIS_R_s - 10 * axisX_s;
                % Ambiguous value for the flesh margin correction vector for the PSIS
                % markers in [Reed1999]: 10 mm in text and 5 mm in table 6
                vectorPSIS_L_b = vectorPSIS_L_s + 10 * axisX_s;
                vectorPSIS_R_b = vectorPSIS_R_s + 10 * axisX_s;
                vectorASIS_R_b_ASIS_L_b = vectorASIS_R_b - vectorASIS_L_b;
                vectorPSIS_R_b_PSIS_L_b = vectorPSIS_R_b - vectorPSIS_L_b;
                vectorCP_b = vectorASIS_L_b + 0.5 * vectorASIS_R_b_ASIS_L_b;
                axisX_b = (vectorCP_b - (vectorPSIS_L_b + 0.5 * vectorPSIS_R_b_PSIS_L_b)) / norm(vectorCP_b - (vectorPSIS_L_b + 0.5 * vectorPSIS_R_b_PSIS_L_b));
                axisY_b = cross(axisZ, axisX_b);
                pelvisWidth = norm(vectorASIS_R_b_ASIS_L_b);
                pelvisDepth = norm(vectorCP_b - (vectorPSIS_L_b + 0.5 * vectorPSIS_R_b_PSIS_L_b));
                vectorHJ_L = vectorCP_b - 0.31 * pelvisDepth * axisX_b - 0.096 * legLength * axisY_b + (-0.09 * pelvisWidth + 111) * axisZ;
                vectorHJ_R = vectorCP_b - 0.34 * pelvisDepth * axisX_b - 0.096 * legLength * axisY_b - (-0.09 * pelvisWidth + 111) * axisZ;
                clear pelvisWidth pelvisDepth pelvisDepth vectorASIS_R_ASIS_L vectorASIS_R_PS ...
                    vectorCP_s vectorASIS_L_b vectorASIS_R_b vectorPSIS_L_b vectorPSIS_R_b ...
                    vectorASIS_R_b_ASIS_L_b vectorPSIS_R_b_PSIS_L_b vectorCP_b axisX_s axisY ...
                    axisZ_s axisX_b axisZ_b;

                case 'Seidel1995'
                % Estimate hip joints HJ_L and HJ_R according to [Seidel1995] with
                % estimating the bone marker positions according to [Reed1999] and
                % assuming a soft tissue offset of 10 mm
                vectorASIS_R_ASIS_L = vectorASIS_R_s - vectorASIS_L_s;
                axisZ = vectorASIS_R_ASIS_L / norm(vectorASIS_R_ASIS_L);
                vectorASIS_R_PS = vectorPS_s - vectorASIS_R_s;
                vectorCP_s = vectorASIS_R_s + dot(vectorASIS_R_PS, axisZ) / dot(axisZ, axisZ) * axisZ;
                axisY_s = (vectorCP_s - vectorPS_s) / norm(vectorCP_s - vectorPS_s);
                axisX_s = cross(axisY_s, axisZ);
                vectorASIS_L_b = vectorASIS_L_s - 10 * axisX_s;
                vectorASIS_R_b = vectorASIS_R_s - 10 * axisX_s;
                vectorPS_b = vectorPS_s - 17.7 * axisX_s + 17.7 * axisY_s;
                % Ambiguous value for the flesh margin correction vector for the PSIS
                % markers in [Reed1999]: 10 mm in text and 5 mm in table 6
                vectorPSIS_L_b = vectorPSIS_L_s + 10 * axisX_s;
                vectorPSIS_R_b = vectorPSIS_R_s + 10 * axisX_s;
                vectorASIS_R_b_PS_b = vectorPS_b - vectorASIS_R_b;
                vectorASIS_R_b_ASIS_L_b = vectorASIS_L_b - vectorASIS_R_b;
                vectorCP_b = vectorASIS_R_b + (dot(vectorASIS_R_b_PS_b, axisZ) / dot(axisZ, axisZ) * axisZ);
                axisY_b = (vectorCP_b - vectorPS_b) / norm(vectorCP_b - vectorPS_b);
                axisX_b = cross(axisY_b, axisZ);
                pelvisWidth = norm(vectorASIS_R_b_ASIS_L_b);
                pelvisHeight = norm(vectorCP_b - vectorPS_b);
                pelvisDepth = (norm(vectorPSIS_L_b - vectorASIS_L_b) + norm(vectorPSIS_R_b - vectorASIS_R_b)) / 2;
                vectorHJ_L(:, currentFrame) = vectorASIS_L_b + (-0.34 * pelvisDepth * axisX_b - 0.79 * pelvisHeight * axisY_b + 0.14 * pelvisWidth * axisZ);
                vectorHJ_R(:, currentFrame) = vectorASIS_R_b + (-0.34 * pelvisDepth * axisX_b - 0.79 * pelvisHeight * axisY_b - 0.14 * pelvisWidth * axisZ);
                clear pelvisWidth pelvisHeight pelvisDepth vectorASIS_R_ASIS_L vectorASIS_R_PS ...
                    vectorCP_s vectorASIS_L_b vectorASIS_R_b vectorPS_b vectorPSIS_L_b ...
                    vectorPSIS_R_b vectorASIS_R_b_PS_b vectorASIS_R_b_ASIS_L_b vectorCP_b ...
                    axisX_s axisY_s axisX_b axisY_b axisZ;

                case 'Davis1991'
                % Estimate hip joints HJ_L and HJ_R according to [Davis1991] with
                % assuming the sacrum marker to be in the middle of the line connection
                % PSIS_L and PSIS_R and approximating the leg length by the average length
                % between ASIS_L and MM_L as well as ASIS_R and MM_R as stated in the
                % C-Motion Wiki
                vectorPSIS_R_PSIS_L = vectorPSIS_L_m - vectorPSIS_R_m;
                vectorASIS_R_ASIS_L = vectorASIS_L_m - vectorASIS_R_m;
                vectorCP = vectorASIS_R_m + 0.5 * vectorASIS_R_ASIS_L;
                axisY = vectorASIS_R_ASIS_L / norm(vectorASIS_R_ASIS_L);
                axisX = (vectorCP - (vectorPSIS_R_m + 0.5 * vectorPSIS_R_PSIS_L)) / norm(vectorCP - (vectorPSIS_R_m + 0.5 * vectorPSIS_R_PSIS_L));
                crossProduct = cross(axisX, axisY);
                axisZ = crossProduct / norm(crossProduct);
                A = 0.115 * legLength - 15.3;
                B = (28.4 * pi / 180);
                C = (18 * pi / 180);
                D = 0.1288 * legLength - 48.56;
                vectorHJ_L = vectorCP + ((-D - (markerOffset)) * cos(C) + A * cos(B) * sin(C)) * axisX - (A * sin(B) - norm(vectorASIS_R_ASIS_L) / 2) * axisY + ((-D - (markerOffset)) * sin(C) - A * cos(B) * cos(C)) * axisZ;
                vectorHJ_R = vectorCP + ((-D - (markerOffset)) * cos(C) + A * cos(B) * sin(C)) * axisX + (A * sin(B) - norm(vectorASIS_R_ASIS_L) / 2) * axisY + ((-D - (markerOffset)) * sin(C) - A * cos(B) * cos(C)) * axisZ;
                clear vectorPSIS_R_PSIS_L vectorASIS_R_ASIS_L vectorCP crossProduct ...
                    A B C D axisX axisY axisZ;

                case 'Bell1990'
                % Estimate hip joints HJ_L and HJ_R according to [Bell1990] with
                % assuming a soft tissue offset of 10 mm
                vectorPSIS_R_PSIS_L = vectorPSIS_L_s - vectorPSIS_R_s;
                vectorASIS_R_ASIS_L = vectorASIS_L_s - vectorASIS_R_s;
                vectorCP = vectorASIS_R_s + 0.5 * vectorASIS_R_ASIS_L;
                axisZ = vectorASIS_R_ASIS_L / norm(vectorASIS_R_ASIS_L);
                axisX = (vectorCP - (vectorPSIS_R_s + 0.5 * vectorPSIS_R_PSIS_L)) / norm(vectorCP - (vectorPSIS_R_s + 0.5 * vectorPSIS_R_PSIS_L));
                vectorCP = vectorCP - 10 * axisX;
                crossProduct = cross(axisX, axisZ);
                axisY = crossProduct / norm(crossProduct);
                pelvisWidth = norm(vectorASIS_R_ASIS_L);
                vectorHJ_L = vectorCP + (-0.19 * pelvisWidth * axisX - 0.3 * pelvisWidth * axisY + (0.5 - 0.14) * pelvisWidth * axisZ);
                vectorHJ_R = vectorCP + (-0.19 * pelvisWidth * axisX - 0.3 * pelvisWidth * axisY - (0.5 - 0.14) * pelvisWidth * axisZ);
                clear vectorPSIS_R_PSIS_L vectorASIS_R_ASIS_L vectorCP crossProduct ...
                    axisX axisY axisZ;

                otherwise
                fprintf('ERROR: Invalid hip joint method!');
                return;

            end

            % Knee joints (KJ_L, KJ_R)
            methodKneeJoint = 'Dumas2007';
            switch methodKneeJoint

                case 'Reed1999'
                % Estimate the knee joints KJ_L and KJ_R and ankle joints AJ_L and
                % AJ_R according to [Reed1999]
                vectorLFC_LM = vectorLM_L_s - vectorLFC_L_s;
                vectorLFC_HJ = vectorHJ_L - vectorLFC_L_s;
                crossProduct = cross(vectorLFC_HJ, vectorLFC_LM);
                vectorKJ_L = vectorLFC_L_s + (0.118 * norm(vectorLFC_LM) * crossProduct / norm(crossProduct));
                vectorLFC_LM = vectorLM_R_s - vectorLFC_R_s;
                vectorLFC_HJ = vectorHJ_R - vectorLFC_R_s;
                crossProduct = cross(vectorLFC_LM, vectorLFC_HJ);
                vectorKJ_R = vectorLFC_R_s + (0.118 * norm(vectorLFC_LM) * crossProduct / norm(crossProduct));
                clear crossProduct vectorLFC_L_LM_L vectorLFC_L_HJ_L vectorLFC_R_LM_R vectorLFC_R_HJ_R;

                case 'Dumas2007'
                % Estimate the knee joints KJ_L and KJ_R according to
                % [Dumas2007a], [Davis1991], [Dempster1955]
                vectorMFC_LFC = vectorLFC_L_s - vectorMFC_L_s;
                vectorKJ_L = vectorMFC_L_s + 0.5 * vectorMFC_LFC;
                vectorMFC_LFC = vectorLFC_R_s - vectorMFC_R_s;
                vectorKJ_R = vectorMFC_R_s + 0.5 * vectorMFC_LFC;
                clear vectorMFC_LFC;

                otherwise
                fprintf('ERROR: Invalid knee joint method!');
                return;

            end

            % Ankle joint (AJ_L, AJ_R)
            methodAnkleJoint = 'Dumas2007';
            switch methodAnkleJoint

                case 'Reed1999'
                % Estimate the knee joints KJ_L and KJ_R and ankle joints AJ_L and
                % AJ_R according to [Reed1999]
                vectorLFC_LM = vectorLM_L_s - vectorLFC_L_s;
                vectorLFC_HJ = vectorHJ_L - vectorLFC_L_s;
                crossProduct = cross(vectorLFC_HJ, vectorLFC_LM);
                vectorKJ_L = vectorLFC_L_s + (0.118 * norm(vectorLFC_LM) * crossProduct / norm(crossProduct));
                vectorLFC_LM = vectorLM_R_s - vectorLFC_R_s;
                vectorLFC_HJ = vectorHJ_R - vectorLFC_R_s;
                crossProduct = cross(vectorLFC_LM, vectorLFC_HJ);
                vectorAJ_R = vectorLM_R_s + (0.085 * norm(vectorLFC_LM) * crossProduct / norm(crossProduct));
                clear crossProduct vectorLFC_LM vectorLFC_HJ;

                case 'Dumas2007'
                % Estimate the ankle joints AJ_L and AJ_R according to
                % [Dumas2007a], [Davis1991]
                vectorMM_LM = vectorLM_L_s - vectorMM_L_s;
                vectorAJ_L = vectorMM_L_s + 0.5 * vectorMM_LM;
                vectorMM_LM = vectorLM_R_s - vectorMM_R_s;
                vectorAJ_R = vectorMM_R_s + 0.5 * vectorMM_LM;
                clear vectorMM_LM;

                case 'Dempster1955'
                % Estimate the ankle joints AJ_L and AJ_R according to [Dempster1955]
                vectorMFC_MM = vectorMM_L_s - vectorMFC_L_s;
                ankleAxis = (vectorMM_L_s + 5 * vectorMFC_MM / norm(vectorMFC_MM)) - vectorLM_L_s;
                vectorAJ_L = vectorLM_L_s + 0.5 * ankleAxis;
                vectorMFC_MM = vectorMM_R_s - vectorMFC_R_s;
                ankleAxis = (vectorMM_R_s + 5 * vectorMFC_MM / norm(vectorMFC_MM)) - vectorLM_R_s;
                vectorAJ_R = vectorLM_R_s + 0.5 * ankleAxis;
                clear vectorMFC_MM ankleAxis;

                case 'Hicks1953'
                % Estimate the ankle joints AJ_L and AJ_R according to [Hicks1953]
                vectorLFC_LM = vectorLM_L_s - vectorLFC_L_s;
                vectorMFC_MM = vectorMM_L_s - vectorMFC_L_s;
                averageVector = (vectorLFC_LM + vectorMFC_MM) / 2;
                vectorLM_MM = vectorMM_L_s - vectorLM_L_s;
                crossProduct = cross(vectorLM_MM, averageVector);
                ankleAxis = (vectorMM_L_s + 15 * crossProduct / norm(crossProduct)) - (vectorLM_L_s + 5 * vectorLFC_LM / norm(vectorLFC_LM));
                vectorAJ_L = (vectorLM_L_s + 5 * vectorLFC_LM / norm(vectorLFC_LM)) + 0.5 * ankleAxis;
                vectorLFC_LM = vectorLM_R_s - vectorLFC_R_s;
                vectorMFC_MM = vectorMM_R_s - vectorMFC_R_s;
                averageVector = (vectorLFC_LM + vectorMFC_MM) / 2;
                vectorLM_MM = vectorMM_R_s - vectorLM_R_s;
                crossProduct = cross(averageVector, vectorLM_MM);
                ankleAxis = (vectorMM_R_s + 15 * crossProduct / norm(crossProduct)) - (vectorLM_R_s + 5 * vectorLFC_LM / norm(vectorLFC_LM));
                vectorAJ_R = (vectorLM_R_s + 5 * vectorLFC_LM / norm(vectorLFC_LM)) + 0.5 * ankleAxis;
                clear vectorLFC_LM vectorMFC_MM vectorLM_MM averageVector crossProduct ankleAxis;

                otherwise
                fprintf('ERROR: Invalid ankle joint method!');
                return;

            end

            % Toe joints (TJ_L, TJ_R)
            % Estimate the toe joints TJ_L and TJ_R according to [Zatsiorsky1998]
            % with assuming the height of the joint center in the middle between ground
            % and MT2 defined by the foot plane given by CAL, MT2 and MT5
            crossProduct = cross((vectorCAL_L_m - vectorMT5_L_m), (vectorMT5_L_m - vectorMT2_L_m));
            footNormal_L = crossProduct / norm(crossProduct);
            vectorTJ_L = vectorMT2_L_s + distanceMT2_L_TJ_L * footNormal_L;
            crossProduct = cross((vectorMT5_R_m - vectorMT2_R_m), (vectorCAL_R_m - vectorMT5_R_m));
            footNormal_R = crossProduct / norm(crossProduct);
            vectorTJ_R = vectorMT2_R_s + distanceMT2_R_TJ_R * footNormal_R;
            clear footNormal_L footNormal_R crossProduct;

            % Save shifted marker coordinates and estimated joint data
            surfaceData = [
                vectorTRA_L_s, ...
                vectorTRA_R_s, ...
                vectorGLA_s, ...
                vectorACR_L_s, ...
                vectorACR_R_s, ...
                vectorLHC_L_s, ...
                vectorLHC_R_s, ...
                vectorSUP_s, ...
                vectorC7_s, ...
                vectorT8_s, ...
                vectorT12_s, ...
                vectorASIS_L_s, ...
                vectorASIS_R_s, ...
                vectorPSIS_L_s, ...
                vectorPSIS_R_s, ...
                vectorPS_s, ...
                vectorGTR_L_s, ...
                vectorGTR_R_s, ...
                vectorLFC_L_s, ...
                vectorLFC_R_s, ...
                vectorMFC_L_s, ...
                vectorMFC_R_s, ...
                vectorLM_L_s, ...
                vectorLM_R_s, ...
                vectorMM_L_s, ...
                vectorMM_R_s, ...
                vectorCAL_L_s, ...
                vectorCAL_R_s, ...
                vectorMT2_L_s, ...
                vectorMT2_R_s, ...
                vectorMT5_L_s, ...
                vectorMT5_R_s, ...
                vectorHAL_L_s, ...
                vectorHAL_R_s ...
            ];
            motion.surfaceX(:, currentFrame) = surfaceData(1,:)';
            motion.surfaceY(:, currentFrame) = surfaceData(2,:)';
            motion.surfaceZ(:, currentFrame) = surfaceData(3,:)';
            motion.surfaceLabels = { ...
                'TRA_L', ...
                'TRA_R', ...
                'GLA', ...
                'ACR_L', ...
                'ACR_R', ...
                'LHC_L', ...
                'LHC_R', ...
                'SUP', ...
                'C7', ...
                'T8', ...
                'T12', ...
                'ASIS_L', ...
                'ASIS_R', ...
                'PSIS_L', ...
                'PSIS_R', ...
                'PS', ...
                'GTR_L', ...
                'GTR_R', ...
                'LFC_L', ...
                'LFC_R', ...
                'MFC_L', ...
                'MFC_R', ...
                'LM_L', ...
                'LM_R', ...
                'MM_L', ...
                'MM_R', ...
                'CAL_L', ...
                'CAL_R', ...
                'MT2_L', ...
                'MT2_R', ...
                'MT5_L', ...
                'MT5_R', ...
                'HAL_L', ...
                'HAL_R' ...
            };
            jointData = [...
                vectorLNJ, ...
                vectorSJ_L, ...
                vectorSJ_R, ...
                vectorEJ_L, ...
                vectorEJ_R, ...
                vectorULJ, ...
                vectorLLJ, ...
                vectorHJ_L, ...
                vectorHJ_R, ...
                vectorKJ_L, ...
                vectorKJ_R, ...
                vectorAJ_L, ...
                vectorAJ_R, ...
                vectorTJ_L, ...
                vectorTJ_R ...
            ];
            motion.jointX.estimated(:, currentFrame) = jointData(1,:)';
            motion.jointY.estimated(:, currentFrame) = jointData(2,:)';
            motion.jointZ.estimated(:, currentFrame) = jointData(3,:)';
            motion.jointLabels.estimated = { ...
                'LNJ', ...
                'SJ_L', ...
                'SJ_R', ...
                'EJ_L', ...
                'EJ_R', ...
                'ULJ', ...
                'LLJ', ...
                'HJ_L', ...
                'HJ_R', ...
                'KJ_L', ...
                'KJ_R', ...
                'AJ_L', ...
                'AJ_R', ...
                'TJ_L', ...
                'TJ_R' ...
            };
            clear surfaceData jointData;

            % Print status
            statusCounter = statusCounter + 1;
            if statusCounter >= 100
                fprintf('STATUS: %.1f %%\n', (currentFrame - startFrame) / (endFrame - startFrame) * 100);
                statusCounter = 0;
            end

        end

        % Add additional data
        motion.markerSize = markerSize;
        motion.supportThickness = supportThickness;
        motion.clothThickness = clothThickness;

        % Save processed data
        fprintf('STATUS: Saving dataset %s %s.\n', subject, dataset);
        motion = orderfields(motion);
        variables.motion = motion;
        save(file, '-struct', 'variables');

    end
end


text:
#include <stdio.h>
#include <stdlib.h>

/* Enums are a custom data type that is suitable to represent anything that
   can be enumerated. */

   /* Enums are declared like this: */
enum currency {
    euro,
    dollar,
    pound = 10,
};

enum animal {
    cat,
    mouse
};

int main(int argc, char* argv[]) {
    enum currency c;
    enum animal d;

    c = euro;
    printf("%i\n", c);      /* Enums are just named integers. */
    printf("%i\n", dollar); /* Usually enumerated automatically. */
    printf("%i\n", pound);  /* But for pound we modified the int representation
                               to 10, see above. */

    /* It is not advisable to rely on the internal integer enumeration. */

    if (c == euro)          /* Tests should be performed like this. */
        printf("I'm a euro.\n");

    d = cat;
    if (c == d)             /* Enums are not type safe! This compares the underlying integers.*/
        printf("Surprise!\n");
    return 0;
}


text:
package org.jfxvnc.net.rfb.codec.handshaker.event;

public class SharedEvent implements HandshakeEvent {

  private final boolean shared;

  public SharedEvent(boolean shared) {
    this.shared = shared;
  }

  public boolean isShared() {
    return shared;
  }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />

<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">

  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">

  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">

  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">

  <meta name="keywords" content="Hexo, NexT" />

<meta property="og:type" content="website">
<meta property="og:title" content="申">
<meta property="og:url" content="http://yoursite.comf/archives/2018/index.html">
<meta property="og:site_name" content="申">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="申">

  <link rel="canonical" href="http://yoursite.comf/archives/2018/"/>

  <title>归档 | 申</title>

        申

    <button>

    </button>

            首页

            关于

            标签

            分类

            归档

        嗯..! 目前共计 1 篇日志。 继续努力。

2018

                三个月的开始

        <time class="post-time" itemprop="dateCreated"
              datetime="2018-12-06T11:00:09+08:00"
              content="2018-12-06" >
          12-06
        </time>

申

                  1
                  日志

© 2018

  申

  本站访客数:


text:
namespace blink {

class AffineTransform;
class TransformationMatrix;

// GTest print support for platform transform classes.
//
// To avoid ODR violations, these should also be declared in the respective
// headers defining these types. This is required because otherwise a template
// instantiation may be instantiated differently, depending on whether this
// declaration is found.
//
// As a result, it is not necessary to include this file in tests in order to
// use these printers. If, however, you get a link error about these symbols,
// you need to make sure the blink_platform_test_support target is linked in
// your unit test binary.
void PrintTo(const AffineTransform&, std::ostream*);
void PrintTo(const TransformationMatrix&, std::ostream*);

}  // namespace blink

#endif  // TransformPrinters_h


text:
QB.init(QBApp.appId, QBApp.authKey, QBApp.authSecret, true);

$(document).ready(function(){

QB.createSession(QBUser, function(err, result) {
	if (err) {
		console.log('Something went wrong: ' + err);
	} else {
		var token = result.token;
			user_id = result.id;
			uploadPages = 0;
			filesCount = 0;
			finished = false;

		console.log('Session created with id ' + result.id);

		retrieveFiles(token);

		// uploading files scroll event
		$(window).scroll(function() {
			if  ($(window).scrollTop() == $(document).height() - $(window).height()){
				retrieveFiles(token);
			}
		});

		// loading image click event
		$("#loading-btn").click(function(e){
			e.preventDefault();

			var inputFile = $("input[type=file]")[0].files[0];
			console.log(inputFile);
			if (inputFile) {
				$("#progress").show(0);
			}

			// uploade image
			QB.content.createAndUpload({name: inputFile.name, file: inputFile, type: inputFile.type, size: inputFile.size, 'public': false}, function(err, response){
				if (err) {
					console.log(err);
				} else {
					console.log(response);

					$("#progress").fadeOut(400);

					var uploadedFile = response;

					showImage(uploadedFile.id, uploadedFile.name, token, false);
				}
			});
		});
	}
});
});

// show image
function showImage(fileId, fileName, token, toAppend){
	var imageHTML = "<img src='http://api.quickblox.com/blobs/"+fileId+"/download.xml?token="+token+"' alt='"+fileName+"' class='animals img-responsive col-md-4 col-sm-6 col-xs-12' />";
	if (toAppend) {
		$('#pictures').append(imageHTML);
	} else {
		$('#pictures').prepend(imageHTML);
	}
}

// get content files
function retrieveFiles(token) {
	if (finished != true) {
		$("#loadwnd").show(0);
		uploadPages = uploadPages + 1;

		QB.content.list({page: uploadPages, per_page: '9'}, function(error, response) {
			if (error) {
				console.log(error);
			} else {
				$.each(response.items, function(index, item){
					var cur = this.blob;
					showImage(cur.id, cur.name, token, true);
				});

				console.log(response);
				$("#loadwnd").delay(1000).fadeOut(1000);

				var totalEntries = response.total_entries;
				entries = response.items.length;
				filesCount = filesCount + entries;

				if (filesCount >= totalEntries) {
					finished = true;
				}
			}
		});
	}
}


text:
var gulp = require('gulp');
var concat = require('gulp-concat');
var expose = require('gulp-expose');
var stripLine  = require('gulp-strip-line');
var gulpif = require('gulp-if');
var del = require('del');
var rename = require("gulp-rename");
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

gulp.task('dist', ['clean'], function() {
  gulp.src('src/*.gs')
      .pipe(gulpif(/OAuth1\.gs$/,
          stripLine('var _ =')))
      .pipe(concat('OAuth1.gs'))
      .pipe(expose('this', 'OAuth1'))
      .pipe(gulp.dest('dist'));
});

gulp.task('clean', function() {
  del([
    'dist/*'
  ]);
});

gulp.task('lint', function() {
  return gulp.src('src/*.gs')
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});


text:
layout: byte
title: How to use Battery Status API
type: bytes
tag: [JavaScript]
description: A wrapper for the Battery Status API.
date: 2015-01-08T00:00:00-00:00
draft: false
---
Battery Status API wrapper:

```javascript
function Battery() {
  observable(this);

  if (typeof navigator.getBattery !== 'function') {
    navigator.getBattery = function () {
      return new Promise(function (resolve, reject) {
        if (navigator.battery) {
          resolve(navigator.battery);
        } else {
          reject(new Error('Battery Status API not implemented.'));
        }
      });
    };
  }

  navigator.getBattery().then(function(batteryManager) {
    this._battery = batteryManager;
    this.trigger('ready', this);
    this._battery.addEventListener('chargingchange', function() {
      this.trigger('chargingChange', this.isCharging());
    }.bind(this));
    this._battery.addEventListener('chargingtimechange', function() {
      this.trigger('chargingTimeChange', this.getChargingTime());
    }.bind(this));
    this._battery.addEventListener('dischargingtimechange', function() {
      this.trigger('dischargingTimeChange', this.getDischargingTime());
    }.bind(this));
    this._battery.addEventListener('levelchange', function() {
      this.trigger('levelChange', this.getLevel());
    }.bind(this));
  }.bind(this), function(error) {
    this.trigger('error', error);
  }.bind(this));
}

Battery.prototype.getLevel = function() {
  return this._battery.level;
};

Battery.prototype.getPercentage = function() {
  return this.getLevel() * 100;
};

Battery.prototype.isCharging = function() {
  return this._battery.charging;
};

Battery.prototype.isDischarging = function() {
  return !this.isCharging();
};

Battery.prototype.getChargingTime = function() {
  var chargingTime = this._battery.chargingTime;
  return Number.isFinite(chargingTime) ? chargingTime : 0;
};

Battery.prototype.getDischargingTime = function() {
  var dischargingTime = this._battery.dischargingTime;
  return Number.isFinite(dischargingTime) ? dischargingTime : 0;
};

Battery.prototype.getStatus = function() {
  return this.isCharging() ? 'charging' : 'discharging';
};

function observable(el) {
  var callbacks = {};

  el.on = function(name, fn) {
    if (typeof fn !== 'function') {
      throw new TypeError('Second argument for "on" method must be a function.');
    }
    (callbacks[name] = callbacks[name] || []).push(fn);
    return el;
  };

  el.one = function(name, fn) {
    fn.one = true;
    return el.on.call(el, name, fn);
  };

  el.off = function(name, fn) {
    if (name === '*') return (callbacks = {}, callbacks);
    if (!callbacks[name]) return;
    if (fn) {
      if (typeof fn !== 'function') {
        throw new TypeError('Second argument for "off" method must be a function.');
      }
      callbacks[name] = callbacks[name].map(function(fm, i) {
        if (fm === fn) {
          callbacks[name].splice(i, 1);
        }
      });
    } else {
      delete callbacks[name];
    }
  };

  el.trigger = function(name) {
    if (!callbacks[name]) return;
    var args = [].slice.call(arguments, 1);

    callbacks[name].forEach(function(fn, i) {
      if (fn) {

        fn.apply(fn, args);
        if (fn.one) callbacks[name].splice(i, 1);
      }
    });
    return el;
  };

  return el;
}

var battery = new Battery();
```

Usage:

```javascript
battery.on('ready', function() {
  console.log('isCharging: ' + battery.isCharging()); // true
  console.log('isDischarging: ' + battery.isDischarging()); // false
  console.log('getChargingTime: ' + battery.getChargingTime()); // 5220 (seconds)
  console.log('getDischargingTime: ' + battery.getDischargingTime()); // 0
  console.log('getLevel: ' + battery.getLevel()); // 0.54
  console.log('getPercentage: ' + battery.getPercentage()); // 54
  console.log('getStatus: ' + battery.getStatus()); // 'charging'
});

battery.on('chargingChange', function(isCharging) {
  console.log(isCharging);
});

battery.on('chargingTimeChange', function(chargingTime) {
  console.log(chargingTime);
});

battery.on('dischargingTimeChange', function(dischargingTime) {
  console.log(dischargingTime);
});

battery.on('levelChange', function(level) {
  console.log(level);
});

battery.on('error', function(error) {
  console.error(error);
});
```

On github at [miguelmota/battery](https://github.com/miguelmota/battery).


text:
package org.usfirst.frc.team687.robot;

import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;

import org.usfirst.frc.team687.robot.commands.*;
import org.usfirst.frc.team687.robot.commands.auto.*;
import org.usfirst.frc.team687.robot.subsystems.*;

import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 *
 * _._ _..._ .-',     _.._(`)
 *'-. `     '  /-._.-'    ',/
 *   )         \            '.
 *  / _    _    |             \
 * |  a    a    /              |
 * \   .-.                     ;
 *  '-('' ).-'       ,'       ;
 *     '-;           |      .'
 *        \           \    /
 *        | 7  .__  _.-\   \
 *        | |  |  ``/  /`  /
 *       /,_|  |   /,_/   /
 *          /,_/      '`-'
 *
 * @author tedfoodlin
 *
 */

public class Robot extends IterativeRobot {

	public static Drive drive;
	public static Intake intake;
	public static Flywheels flywheels;
	public static Shooter shooter;
	public static PowerDistributionPanel pdp;
	public static Compressor compressor;

	public static OI oi;

    Command autonomousCommand;
    SendableChooser<Command> autoProgram;

    public void robotInit() {
		pdp = new PowerDistributionPanel();
		compressor = new Compressor();
		compressor.start();

		drive = new Drive();
		intake = new Intake();
		flywheels = new Flywheels();
		shooter = new Shooter();

		oi = new OI();

		drive.shiftDown();
		drive.resetEncoders();
		drive.resetGyro();

        autoProgram = new SendableChooser<>();
        autoProgram.addDefault("Do Nothing", new DoNothing());
        autoProgram.addObject("Breach Cheval de Frises", new BreachCheval());
        autoProgram.addObject("Breach Ramparts", new BreachRamparts());
        autoProgram.addObject("Breach Moat", new BreachMoat());
        autoProgram.addObject("Breach Rock Wall", new BreachRockWall());
        autoProgram.addObject("Breach Rough Terrain", new BreachRoughTerrain());
        autoProgram.addObject("Breach Low Bar", new BreachLowBar());
        autoProgram.addObject("Breach Moat and Shoot", new BreachMoatShoot());
        autoProgram.addObject("Breach Rough Terrain and Shoot", new BreachRoughTerrainShoot());
        autoProgram.addObject("Breach Rock Wall and Shoot", new BreachRockWallShoot());
        autoProgram.addObject("Breach Ramparts and Shoot", new BreachRampartsShoot());
        autoProgram.addObject("Breach Cheval de Frises and Shoot V1", new BreachChevalShootA());
        autoProgram.addObject("Breach Cheval de Frises and Shoot V2", new BreachChevalShootB());
        autoProgram.addObject("Breach Low Bar and Shoot", new BreachLowBarShoot());

        SmartDashboard.putData("Auto Program", autoProgram);

        SmartDashboard.putData(drive);
        SmartDashboard.putData(intake);
        SmartDashboard.putData(flywheels);
        SmartDashboard.putData(shooter);
    }

    public void disabledInit() {
		Scheduler.getInstance().removeAll();
    }

	public void disabledPeriodic() {
		Scheduler.getInstance().run();
	}

    public void autonomousInit() {
		Scheduler.getInstance().removeAll();
        autonomousCommand = (Command)autoProgram.getSelected();

        if (autonomousCommand != null) {
        	autonomousCommand.start();
        }
    }

    public void autonomousPeriodic() {
        Scheduler.getInstance().run();

        drive.reportToSmartDashboard();
        intake.reportToSmartDashboard();
        flywheels.reportToSmartDashboard();
        shooter.reportToSmartDashboard();
        SmartDashboard.putData("PDP", pdp);
    }

    public void teleopInit() {
		Scheduler.getInstance().removeAll();
        if (autonomousCommand != null) {
        	autonomousCommand.cancel();
        }
    }

    public void teleopPeriodic() {
        Scheduler.getInstance().run();

        drive.reportToSmartDashboard();
        intake.reportToSmartDashboard();
        flywheels.reportToSmartDashboard();
        shooter.reportToSmartDashboard();
        SmartDashboard.putData("PDP", pdp);
    }

    public void testPeriodic() {
        LiveWindow.run();

        drive.reportToSmartDashboard();
        intake.reportToSmartDashboard();
        flywheels.reportToSmartDashboard();
        shooter.reportToSmartDashboard();
        SmartDashboard.putData("PDP", pdp);
    }
}


text:
A directive that provides the [Foundation Dropdown Menu](http://foundation.zurb.com/docs/components/topbar.html) component.

The directive relies on the same markup as the original Foundation Dropdown Menu.

The following settings can be applied as attributes to the root element with the ```dropdown-menu``` attribute:

- `disable-hover`: A mouse hover event will no open the root menu.
- `disable-click-open`: Click events will not open menus, only hover (not implemented yet).
- `closing-time`: Amount of time to delay closing a submenu on a mouseleave event. Default is 500ms

See the demo page for example on how to use this and visit the [Foundation docs](http://foundation.zurb.com/sites/docs/dropdown-menu.html) for more details.


text:
'use strict';

const $ = require('jquery-browserify');
const header = require('./header');
const banner = require('./banner');
const sidebar = require('./sidebar');
const admin = require('./admin');

$(document).ready(function() {
  header($);
  banner($);
  sidebar($);
  admin($);
});


text:
<?php
namespace DreamFactory\Library\Utility;

class ArrayUtils
{
    /**
     * @param array|\ArrayObject $target            Target to grab $key from
     * @param string             $key               Index into target to retrieve
     * @param mixed              $defaultValue      Value returned if $key is not in $target
     * @param bool               $emptyStringIsNull If true, and the result is an empty string (''), NULL is returned
     *
     * @return mixed
     */
    public static function get(array $target, $key, $defaultValue = null, $emptyStringIsNull = false)
    {
        $_result =
            is_array($target) ? (array_key_exists($key, $target) ? $target[$key] : $defaultValue) : $defaultValue;

        return $emptyStringIsNull && '' === $_result ? null : $_result;
    }

    /**
     * @param array|\ArrayObject $options
     * @param string             $key
     * @param string             $subKey
     * @param mixed              $defaultValue      Only applies to target value
     * @param bool               $emptyStringIsNull If true, empty() values will always return as NULL
     *
     * @return mixed
     */
    public static function getDeep(array $options, $key, $subKey, $defaultValue = null, $emptyStringIsNull = false)
    {
        $_deep = static::get($options, $key, [], $emptyStringIsNull);

        return static::get($_deep, $subKey, $defaultValue, $emptyStringIsNull);
    }

    /**
     * Retrieves a boolean option from the given array. $defaultValue is set and returned if $_key is not 'set'.
     *
     * Returns TRUE for "1", "true", "on", "yes" and "y". Returns FALSE otherwise.
     *
     * @param array|\ArrayAccess $options
     * @param string             $key
     * @param boolean            $defaultValue Defaults to false
     *
     * @return mixed
     */
    public static function getBool(array $options, $key, $defaultValue = false)
    {
        return Scalar::boolval(static::get($options, $key, $defaultValue));
    }

    /**
     * @param array|\ArrayObject $target Target to set $key in
     * @param string             $key    Index into target to retrieve
     * @param mixed              $value  The value to set
     */
    public static function set(array & $target, $key, $value = null)
    {
        is_array($target) && $target[$key] = $value;
    }

    /**
     * @param array|\ArrayObject $target Target to set $key in
     * @param string             $key    Index into target to retrieve
     *
     * @return bool True if key existed and was removed
     */
    public static function remove(array & $target, $key)
    {
        if (static::has($target, $key)) {
            unset($target[$key]);

            return true;
        }

        return false;
    }

    /**
     * Removes items with null value from an array.
     *
     * @param array $array
     */
    public static function removeNull(array & $array)
    {
        foreach ($array as $key => $value) {
            if (null === $value) {
                unset($array[$key]);
            }
        }
    }

    /**
     * @param array|\ArrayObject $target Target to check
     * @param string             $key    Key to check
     *
     * @return bool
     */
    public static function has(array $target, $key)
    {
        return is_array($target) && array_key_exists($key, $target);
    }

    /**
     * A recursive array_change_key_case lowercase function.
     *
     * @param array $input
     *
     * @return array
     */
    public static function array_key_lower($input)
    {
        if (!is_array($input)) {
            trigger_error("Invalid input array '{$input}'", E_USER_NOTICE);
            exit;
        }
        $input = array_change_key_case($input, CASE_LOWER);
        foreach ($input as $key => $array) {
            if (is_array($array)) {
                $input[$key] = static::array_key_lower($array);
            }
        }

        return $input;
    }

    /**
     * @param $array
     *
     * @return bool
     */
    public static function isArrayNumeric($array)
    {
        if (is_array($array)) {
            for ($k = 0, reset($array); $k === key($array); next($array)) {
                ++$k;
            }

            return is_null(key($array));
        }

        return false;
    }

    /**
     * @param      $array
     * @param bool $strict
     *
     * @return bool
     */
    public static function isArrayAssociative($array, $strict = true)
    {
        if (is_array($array)) {
            if (!empty($array)) {
                if ($strict) {
                    return (count(array_filter(array_keys($array), 'is_string')) == count($array));
                } else {
                    return (0 !== count(array_filter(array_keys($array), 'is_string')));
                }
            }
        }

        return false;
    }

    /**
     * @param        $list
     * @param        $find
     * @param string $delimiter
     * @param bool   $strict
     *
     * @return bool
     */
    public static function isInList($list, $find, $delimiter = ',', $strict = false)
    {
        return (false !== array_search($find, array_map('trim', explode($delimiter, strtolower($list))), $strict));
    }

    /**
     * @param        $list
     * @param        $find
     * @param string $delimiter
     * @param bool   $strict
     *
     * @return mixed
     */
    public static function findInList($list, $find, $delimiter = ',', $strict = false)
    {
        return array_search($find, array_map('trim', explode($delimiter, strtolower($list))), $strict);
    }

    /**
     * @param        $list
     * @param        $find
     * @param string $delimiter
     * @param bool   $strict
     *
     * @return string
     */
    public static function addOnceToList($list, $find, $delimiter = ',', $strict = false)
    {
        if (empty($list)) {
            $list = $find;

            return $list;
        }
        $pos = array_search($find, array_map('trim', explode($delimiter, strtolower($list))), $strict);
        if (false !== $pos) {
            return $list;
        }
        $result = array_map('trim', explode($delimiter, $list));
        $result[] = $find;

        return implode($delimiter, array_values($result));
    }

    /**
     * @param        $list
     * @param        $find
     * @param string $delimiter
     * @param bool   $strict
     *
     * @return string
     */
    public static function removeOneFromList($list, $find, $delimiter = ',', $strict = false)
    {
        $pos = array_search($find, array_map('trim', explode($delimiter, strtolower($list))), $strict);
        if (false === $pos) {
            return $list;
        }
        $result = array_map('trim', explode($delimiter, $list));
        unset($result[$pos]);

        return implode($delimiter, array_values($result));
    }

    /**+
     * Provides a diff of two arrays, recursively.
     * Any keys or values that do not match are returned in an array.
     * Empty results indicate no change obviously.
     *
     * @param array $array1
     * @param array $array2
     * @param bool  $check_both_directions
     *
     * @return array
     */
    public static function array_diff_recursive(array $array1, $array2, $check_both_directions = false)
    {
        $_return = [];

        if ($array1 !== $array2) {
            foreach ($array1 as $_key => $_value) {
                //	Is the key is there...
                if (!array_key_exists($_key, $array2)) {
                    $_return[$_key] = $_value;
                    continue;
                }

                //	Not an array?
                if (!is_array($_value)) {
                    if ($_value !== $array2[$_key]) {
                        $_return[$_key] = $_value;
                        continue;
                    }
                }

                //	If we've got two arrays, diff 'em
                if (is_array($array2[$_key])) {
                    $_diff = static::array_diff_recursive($_value, $array2[$_key]);

                    if (!empty($_diff)) {
                        $_return[$_key] = $_diff;
                    }

                    continue;
                }

                $_return[$_key] = $_value;
            }

            if ($check_both_directions) {
                foreach ($array2 as $_key => $_value) {
                    //	Is the key is there...
                    if (!array_key_exists($_key, $array1)) {
                        $_return[$_key] = $_value;
                        continue;
                    }

                    //	Not an array?
                    if (!is_array($_value)) {
                        if ($_value !== $array1[$_key]) {
                            $_return[$_key] = $_value;
                            continue;
                        }
                    }

                    //	If we've got two arrays, diff 'em
                    if (is_array($array1[$_key])) {
                        $_diff = static::array_diff_recursive($_value, $array1[$_key]);

                        if (!empty($_diff)) {
                            $_return[$_key] = $_diff;
                        }

                        continue;
                    }

                    $_return[$_key] = $_value;
                }
            }
        }

        return $_return;
    }

    /**
     * A case-insensitive "in_array" for all intents and purposes. Works with objects too!
     *
     * @param string       $needle
     * @param array|object $haystack
     * @param bool         $strict
     *
     * @return bool Returns true if found, false otherwise. Just like in_array
     */
    public static function contains($needle, $haystack, $strict = false)
    {
        foreach ($haystack as $_index => $_value) {
            if (is_string($_value)) {
                if (0 === strcasecmp($needle, $_value)) {
                    return true;
                }
            } else if (in_array($needle, $_value, $strict)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Searches a multi-dimension array by key and value and returns
     * the array that holds the key => value pair or optionally returns
     * the value of a supplied key from the resultant array.
     *
     * @param array  $array
     * @param string $key
     * @param string $value
     * @param string $returnKey
     *
     * @return null
     */
    public static function findByKeyValue($array, $key, $value, $returnKey = null)
    {
        foreach ($array as $item) {
            if ($item[$key] === $value) {
                if ($returnKey) {
                    return $item[$returnKey];
                } else {
                    return $item;
                }
            }
        }

        return null;
    }

    /**
     * Ensures the argument passed in is actually an array with optional iteration callback
     *
     * @static
     *
     * @param array             $array
     * @param callable|\Closure $callback
     *
     * @return array
     */
    public static function clean($array = null, $callback = null)
    {
        $_result = (empty($array) ? [] : (!is_array($array) ? [$array] : $array));

        if (null === $callback || !is_callable($callback)) {
            return $_result;
        }

        $_response = [];

        foreach ($_result as $_item) {
            $_response[] = call_user_func($callback, $_item);
        }

        return $_response;
    }
}


text:
<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../bower_components/polymer/polymer.html">

<!-- shared styles for all views -->
<dom-module id="shared-styles">
  <template>
    <style>
      .card {
        box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);
        padding: 16px;
        margin: 24px;
        border-radius: 5px;
        background-color: #fff;
        color: #757575;
      }
      .circle {
        display: inline-block;
        height: 64px;
        width: 64px;
        border-radius: 50%;
        background: #ddd;
        line-height: 64px;
        font-size: 30px;
        color: #555;
        text-align: center;
      }
      h1 {
        font-size: 22px;
        margin: 16px 0;
        color: #212121;
      }
      #settingsMenu {
        margin: 0;
        width: 192px;
        border-radius: 2px;
        background-color: #ffffff;
        box-shadow: 0 8px 8px 0 rgba(0, 0, 0, 0.24), 0 0 8px 0 rgba(0, 0, 0, 0.12);

        --paper-dialog: {
            margin: 0;
        }
      }
      #settingsMenu paper-listbox {
        padding: 0;
        cursor: pointer;
      }
      .settings-items {
        font-size: 14px;
        font-weight: normal;
        font-style: normal;
        font-stretch: normal;
        text-align: left;
        color: rgba(0, 0, 0, 0.48);
      }

    </style>
  </template>
</dom-module>