Find user's home directory if possible.
    Otherwise, returns None.

    :see:  http://mail.python.org/pipermail/python-list/2005-February/325395.html

    This function is copied from matplotlib version 1.4.3, Jan 2016
322613
def _get_home():
    
    try:
        if six.PY2 and sys.platform == 'win32':
            path = os.path.expanduser(b"~").decode(sys.getfilesystemencoding())
        else:
            path = os.path.expanduser("~")
    except ImportError:
        # This happens on Google App Engine (pwd module is not present).
        pass
    else:
        if os.path.isdir(path):
            return path
    for evar in ('HOME', 'USERPROFILE', 'TMP'):
        path = os.environ.get(evar)
        if path is not None and os.path.isdir(path):
            return path
    return None
1246184
def get_home_dir(long_name, service_name)
      # entry point
      url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/dns/#{SafeNet.escape(service_name)}/#{SafeNet.escape(long_name)}"

      # api call
      uri = URI(url)
      http = Net::HTTP.new(uri.host, uri.port)
      req = Net::HTTP::Get.new(uri.path)
      res = http.request(req)
      res = JSON.parse(res.body)
      res["info"]["metadata"] = Base64.strict_decode64(res["info"]["metadata"]) if res.has_key?("info") && res["info"].has_key?("metadata")
      res
    end
184245
def chhome(name, home, **kwargs):
    '''
    
    '''
    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    persist = kwargs.pop('persist', False)
    if kwargs:
        salt.utils.args.invalid_kwargs(kwargs)
    if persist:
        log.info('Ignoring unsupported \'persist\' argument to user.chhome')

    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
    if home == pre_info['home']:
        return True
    _dscl(
        ['/Users/{0}'.format(name), 'NFSHomeDirectory',
         pre_info['home'], home],
        ctype='change'
    )
    # dscl buffers changes, sleep 1 second before checking if new value
    # matches desired value
    time.sleep(1)
    return info(name).get('home') == home
142248
def get_default_home_dir():
    
    ding0_dir = str(cfg_ding0.get('config',
                                  'config_dir'))
    return os.path.join(os.path.expanduser('~'), ding0_dir)
1239669
def get_pycons3rt_home_dir():
    
    if platform.system() == 'Linux':
        return os.path.join(os.path.sep, 'etc', 'pycons3rt')
    elif platform.system() == 'Windows':
        return os.path.join('C:', os.path.sep, 'pycons3rt')
    elif platform.system() == 'Darwin':
        return os.path.join(os.path.expanduser('~'), '.pycons3rt')
    else:
        raise OSError('Unsupported Operating System')
678109
def get_path_matching(name):
    
    # first try looking in the user folder
    p = os.path.join(os.path.expanduser("~"), name)
    # then try expanding upwards from cwd
    if not os.path.isdir(p):
        p = None
        drive, folders = os.path.splitdrive(os.getcwd())
        folders = folders.split(os.sep)
        folders.insert(0, os.sep)
        if name in folders:
            p = os.path.join(drive, *folders[: folders.index(name) + 1])
    # TODO: something more robust to catch the rest of the cases?
    return p
1318940
def __catalina_home():
    '''
    
    '''
    locations = ['/usr/share/tomcat*', '/opt/tomcat']
    for location in locations:
        folders = glob.glob(location)
        if folders:
            for catalina_home in folders:
                if os.path.isdir(catalina_home + "/bin"):
                    return catalina_home
    return False
215888
def home
      ['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] }
      return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH']
      File.expand_path("~")
    rescue
      File::ALT_SEPARATOR ? "C:/" : "/"
    end
1330951
def guess_home():
    ''''''
    global freesurfer_home
    if freesurfer_home != None:
        return True
    # if we already have it in the path, use that
    fv = nl.which('freeview')
    if fv:
        freesurfer_home = parpar_dir(os.path.realpath(fv))
        return True
    for guess_dir in guess_locations:
        if os.path.exists(guess_dir):
            freesurfer_home = guess_dir
            return True
    return False
307418
def get_model_home():
    '''
    
    '''
    d = os.path.join(get_data_home(), 'nnp_models')
    if not os.path.isdir(d):
        os.makedirs(d)
    return d
488510
def _get_config_dir():
    
    if 'SAWTOOTH_HOME' in os.environ:
        return os.path.join(os.environ['SAWTOOTH_HOME'], 'etc')

    if os.name == 'nt':
        base_dir = \
            os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
        return os.path.join(base_dir, 'conf')

    return '/etc/sawtooth'
55245
def caller_folder():
    
    import inspect
    caller_file = inspect.stack()[2][1]
    if os.path.exists(caller_file):
        return os.path.abspath(os.path.dirname(caller_file))
    else:
        return os.path.abspath(os.getcwd())
642261
def lisp(self, foldername="INBOX", reverse=False, since=None, stream=sys.stdout):
        
        def fromval(hdr):
            if hdr:
                return parseaddr(hdr)

        for folder, mk, m in self._list(foldername, reverse, since):
            try:
                print(json.dumps({
                        'folder': folder.folder or foldername or "INBOX",
                        'key': "%s%s%s" % (folder.folder or foldername or "INBOX", SEPERATOR, mk),
                        'date':  str(m.date),
                        "flags": m.get_flags(),
                        'from': fromval(m.get_from()),
                        'subject': re.sub("\n|\'|\"", _escape, m.get_subject() or "")
                        }), file=stream)
            except IOError as e:
                if e.errno == errno.EPIPE:
                    # Broken pipe we can ignore
                    return
                self.logger.exception("whoops!")
            except Exception as e:
                self.logger.exception("whoops!")
270879
def personsAtHome(self, home=None):
        
        if not home: home = self.default_home
        home_data = self.homeByName(home)
        atHome = []
        for p in home_data['persons']:
            #Only check known persons
            if 'pseudo' in p:
                if not p["out_of_sight"]:
                    atHome.append(p['pseudo'])
        return atHome
203981
def default_hass_config_dir():
    """"""
    data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
    return os.path.join(data_dir, ".homeassistant")
157506
def check_for_new_files_in_home(self):
        
        if not self._user:
            return None
        try:
            created_files = set(self._listdir(self._home_dir)).difference(self._home_dir_content)
        except (subprocess.CalledProcessError, IOError):
            # Probably home directory does not exist
            created_files = []
        if created_files:
            logging.warning('The tool created the following files in %s, '
                            'this may influence later runs:\n\t%s',
                            self._home_dir, '\n\t'.join(created_files))
        return created_files
225473
def get_server_home(self):
        
        home_dir = super(MongodServer, self).get_server_home()
        if not home_dir:
            home_dir = self.get_db_path()

        return home_dir