<commit_before>#!/usr/bin/env python2
# #############################################################################
# The comment above works if the Python Launcher for Windows path included
# in Python>3.3 does not conflict with the py.exe file added to "C:\Windows"
# Currently this application should work in Python >2.6 and 3.x, although 
# python 2 is prefered, as it is the main development platform. 
###############################################################################
from __future__ import unicode_literals, absolute_import
import os
import platform
import threading
import webbrowser
import ArduinoServerCompiler.ServerCompilerSettings
import ArduinoServerCompiler.BlocklyHTTPServer


def open_browser(filetoload):
    """ Start a browser after waiting for half a second. """

    def _open_browser():
        webbrowser.open('http://%s:%s/%s' %
                        (ArduinoServerCompiler.BlocklyHTTPServer.ADDRESS,
                        ArduinoServerCompiler.BlocklyHTTPServer.PORT,
                        filetoload))

    thread = threading.Timer(0.5, _open_browser)
    thread.start()


def main():
    """
    Initialises the Settings singleton and starts the HTTP Server
    """
    print('Running Python version ' + platform.python_version())
    print("\n======= Loading Settings =======")
    ArduinoServerCompiler.ServerCompilerSettings.ServerCompilerSettings()
    current_dir = os.getcwd()
    app_index = os.path.basename(os.path.normpath(current_dir))
    app_index = os.path.join(app_index, 'apps', 'arduino_material')
    open_browser(app_index)
    print("\n======= Starting Server =======")
    #parent directory as working directory due to closure requirements
    parent_dir = os.path.dirname(os.getcwd())
    ArduinoServerCompiler.BlocklyHTTPServer.start_server(parent_dir)


if __name__ == "__main__":
    main()<commit_msg>Server launch script improvements: Added command line options for help and to set the working root directory for the server. Improved the directory location and selection code to work on different environments.<commit_after>#!/usr/bin/env python2
# #############################################################################
# The comment above works if the Python Launcher for Windows path included
# in Python>3.3 does not conflict with the py.exe file added to "C:\Windows"
# Currently this application should work in Python >2.6 and 3.x, although 
# python 2 is preferred, as it is the main development platform.
###############################################################################
from __future__ import unicode_literals, absolute_import
import os
import re
import sys
import getopt
import platform
import threading
import webbrowser
import ArduinoServerCompiler.ServerCompilerSettings
import ArduinoServerCompiler.BlocklyHTTPServer


def open_browser(open_file):
    """
    Start a browser in a separate thread after waiting for half a second.
    """
    def _open_browser():
        webbrowser.open('http://%s:%s/%s' %
                        (ArduinoServerCompiler.BlocklyHTTPServer.ADDRESS,
                        ArduinoServerCompiler.BlocklyHTTPServer.PORT,
                        open_file))

    thread = threading.Timer(0.5, _open_browser)
    thread.start()


def parsing_args(argv):
    """
    Processes the command line arguments. Arguments supported:
    -h / --help
    -s / --serverroot <working directory>
    :return: dictionary with available options(keys) and value(value)
    """
    option_dict = {}
    try:
        opts, args = getopt.getopt(argv, "hs:", ["help", "serverroot="])
    except getopt.GetoptError as e:
        print('There was a problem parsing the command line arguments:')
        print('\t%s' % e)
        sys.exit(1)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print('Include a server working directory using the flag:')
            print('\t -s <folder>')
            sys.exit(0)
        if opt in ("-s", "--serverroot"):
            # Windows only issue: In BlocklyRequestHandler, if chdir is fed
            # an 'incorrect' path like 'C:' instead of 'C:\' or C:/' it
            # fails silently maintaining the current working directory.
            # Use regular expressions to catch this corner case.
            if re.match("^[a-zA-Z]:$", arg):
                print('The windows drive letter needs to end in a slash, ' +
                      'eg. %s\\' % arg)
                sys.exit(1)
            # Check if the value is a valid directory
            if os.path.isdir(arg):
                option_dict['serverroot'] = arg
                print ('Parsed "' + opt + '" flag with "' + arg + '" value.')
            else:
                print('Invalid directory "' + arg + '".')
                sys.exit(1)
        else:
            print('Flag ' + opt + ' not recognised.')
    return option_dict


def main(argv):
    """
    Initialises the Settings singleton and starts the HTTP Server
    """
    print('Running Python version ' + platform.python_version())

    # Checking command line arguments
    if len(argv) > 0:
        print("\n======= Parsing Command line arguments =======")
        arguments = parsing_args(argv)
        if 'serverroot' in arguments:
            # Overwrite server working directory if valid
            server_root = arguments['serverroot']

    # Loading the settings
    print("\n======= Loading Settings =======")
    ArduinoServerCompiler.ServerCompilerSettings.ServerCompilerSettings()

    # Loading the server with the argument working root directory, or by default
    # with the parent folder of where this script is executed, done to be able
    # to find the closure lib directory on the same level as the project folder
    print("\n======= Starting Server =======")
    this_file_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
    try:
        server_root
    except NameError:
        server_root = os.path.dirname(this_file_dir)
    # Opening the browser to the web-app
    paths = [server_root, this_file_dir]
    common_path = os.path.commonprefix(paths)
    if not common_path:
        print('The server working directory and Ardublockly project need to ' +
              'be in the same root directory!')
        sys.exit(1)
    relative_path = [os.path.relpath(this_file_dir, common_path)]
    app_index = os.path.join(relative_path[0], 'apps', 'arduino_material')
    #print('Root & this file: %s\nCommon & relative path: %s; %s\nIndex: %s' %
    #      (paths, common_path, relative_path, app_index))
    open_browser(app_index)
    ArduinoServerCompiler.BlocklyHTTPServer.start_server(server_root)


if __name__ == "__main__":
    main(sys.argv[1:])
{'fraction_non_alphanumeric': 0.14639976097998209, 'fraction_numerical': 0.00403346280250971, 'mean_word_length': 3.0600363856882957, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '609229', 'n_tokens_mistral': 1825, 'n_tokens_neox': 1758, 'n_words': 570}