Ejemplo n.º 1
0
def run_graphql_query(graphqlquery, queryvariables={}):
    request = requests.post(graphql_url,
                            json={
                                'query': graphqlquery,
                                'variables': queryvariables
                            },
                            headers=headers)

    if request.status_code == 200:
        result = request.json()

        if "data" not in result or "errors" in result:
            raise Exception(
                wrap_text(f"""
                There were errors while processing the query!
                {graphqlquery}
                {queryvariables}
                '{json.dumps( result, indent=2, sort_keys=True )}'
            """))

    else:
        raise Exception(
            wrap_text(
                f"""Query failed to run by returning code of {request.status_code}.
            queryvariables:
            {queryvariables}
            graphqlquery:
            {graphqlquery}
        """))

    return result
def show_program_description():
    g_link_wrapper.width = 71

    lines = \
    [
        wrap_text( """\
        Thank you for choosing %s.

        This is a channel of packages for Sublime Text's Package Control, which replace and install
        some of the packages by a forked/alternative version. i.e., custom modification of them. You
        can find this list of packages to be installed on channel on the following addresses:
        """ % CHANNEL_PACKAGE_NAME, single_lines=True ),
        "",
        g_link_wrapper.fill( "<%s>" % g_channelSettings['CHANNEL_ROOT_URL'] ),
        g_link_wrapper.fill( "<%s>" % g_channelSettings['CHANNEL_FILE_URL'] ),
        "",
        wrap_text( """\
        Therefore, this installer will install all Sublime Text Packages listed on the above address,
        however if already there are some of these packages installed, your current version will be
        upgraded to the version used on the fork of the same package.

        This installer will also remove you current installation of Package Control and install
        another forked version of it, which has the name PackagesManager. Now on, when you want to,
        install/manage packages, you should look for `PackagesManager` instead of `Package Control`.
        """, single_lines=True ),
    ]

    return sublime.ok_cancel_dialog("\n".join(lines), "Next")
Ejemplo n.º 3
0
def show_program_description():
    ok_button_text = "Edit upgrade"
    no_button_text = "Start upgrade"

    lines = [ "Welcome to the {channel} {wizard}.".format( channel=CHANNEL_PACKAGE_NAME, wizard=g_installation_type ), "", ]

    def format_packages_list(packages_list, maximum_length=500):
        length = 0
        contents = []

        for index, name in enumerate( packages_list ):
            contents.append( "%s. %s" % ( index + 1, name ) )
            length += len( contents[-1] )

            if length > maximum_length:
                remaining = len( packages_list ) - index - 1
                if remaining > 0: contents.append( "and more {} packages!".format( remaining ) )
                break

        return ", ".join( contents )

    if len( PACKAGES_TO_INSTALL ):
        lines.append( "The main {channel} upstream has added the following new packages: ".format( channel=CHANNEL_PACKAGE_NAME ) )
        lines.append( format_packages_list( PACKAGES_TO_INSTALL ) )
        lines.append( "" )

    if len( PACKAGES_TO_UNINSTALL ):
        lines.append( "The main {channel} upstream has removed the following installed packages: ".format( channel=CHANNEL_PACKAGE_NAME ) )
        lines.append( format_packages_list( PACKAGES_TO_UNINSTALL ) )
        lines.append( "" )

    if len( PACKAGES_TO_UNINSTALL ) < 1 and len( PACKAGES_TO_INSTALL ) < 1:
        lines.append( wrap_text( """\
                You removed all upgrade changes. If you would like the undo this, cancel the
                {wizard} and restart Sublime Text. Otherwise, hit the `{ok_button}` button to
                confirm the operation changes.
            """.format( wizard=g_installation_type, ok_button=no_button_text ), single_lines=True ) )

    else:
        global g_isFirstTime

        if g_isFirstTime:
            lines.append( wrap_text( """\
                    If you would like to remove packages from the upgrade list, choose the
                    `{ok_button}` button. Otherwise, choose the `{no_button}` button to start the
                    upgrade process.
                """.format( ok_button=ok_button_text, no_button=no_button_text), single_lines=True ) )

        else:
            lines.append( wrap_text( """\
                    If you would like revert your changes to the {wizard} package's list, just
                    cancel the {wizard} and restart Sublime Text. Then, on next time you start
                    Sublime Text, you will be able to start picking up packages again.
                """.format( wizard=g_installation_type ), single_lines=True ) )

        g_isFirstTime = False

    return sublime.yes_no_cancel_dialog( "\n".join( lines ), ok_button_text, no_button_text )
def select_stable_or_developent_version():
    global g_version_to_install

    lines = \
    [
        wrap_text( """\
        {descriptions}
        It is recommended to use both Stable and Development Versions of the {channel_name}. For
        example, while you are at home, use the Development Version as you should have free time to
        work on it, fixing bugs and installing new packages. Elsewhere your are, use the Stable
        Version, because when you are elsewhere you have no time for fixing bugs or testing new
        things. Also because elsewhere you are, not always there will be enough free space required
        by the Development Version.
        """.format( descriptions=g_channelSettings['CHANNEL_VERSIONS_DESCRIPTIONS'],
                channel_name=CHANNEL_PACKAGE_NAME ), single_lines=True ),
    ]

    user_response = sublime.yes_no_cancel_dialog(
        "\n".join(lines), "Install the Stable Version",
        "Install the Development Version")

    if user_response == sublime.DIALOG_YES:
        g_version_to_install = "stable"

    elif user_response == sublime.DIALOG_NO:
        g_version_to_install = "development"

        command_line_interface = cmd.Cli(None, True)
        git_executable_path = command_line_interface.find_binary(
            "git.exe" if os.name == 'nt' else "git")

        if not git_executable_path:
            g_version_to_install = "stable"

            log(
                1,
                "Using the Stable Version instead of the Development Version as a valid `git`"
                "application could not be found")

            sublime.message_dialog(
                wrap_text("""\
                    Sorry, but the `git` application could not be found on your system. Hence the
                    Stable Version will be used instead. If you are sure there is a `git`
                    application installed on your system check your console for error messages.

                    You can also open an issue on the {channel_name} issue tracker at the address:
                    <{root_url}>, Just do not forget to save your Sublime Text Console output, as it
                    recorded everything which happened, and should be very helpful in finding the
                    solution for the problem.
                    """.format(channel_name=CHANNEL_PACKAGE_NAME,
                               root_url=g_channelSettings['CHANNEL_ROOT_URL']),
                          single_lines=True))

    return user_response != sublime.DIALOG_CANCEL, False
Ejemplo n.º 5
0
def show_goodbye_message():
    ok_button_text = "Go back"
    no_button_text = "Skip this upgrade"

    lines = \
    [
        wrap_text( """\
        Do you want to cancel the {channel_name} {wizard}?

        If you would like to upgrade the {channel_name}, hit the `{ok_button}` button to go back and
        try again. Otherwise, hit the `Cancel` button to follow the {wizard} next time Sublime Text
        starts.

        If you would like to ignore this upgrade, hit the `{no_button}` button.
        """.format( ok_button=ok_button_text, no_button=no_button_text,
                wizard=g_installation_type, channel_name=CHANNEL_PACKAGE_NAME ), single_lines=True ),
    ]

    sublime_dialog = sublime.yes_no_cancel_dialog( "\n".join( lines ), ok_button_text, no_button_text )

    if sublime_dialog == sublime.DIALOG_YES: # "Go back"
        return True

    elif sublime_dialog == sublime.DIALOG_NO: # "Skip this upgrade"
        g_channelSettings['CHANNEL_UPGRADE_SKIP'] = True

    elif sublime_dialog == sublime.DIALOG_CANCEL:
        # When pressing escape key, it returns to DIALOG_CANCEL
        pass

    else:
        log(1, "Error: The option `%s` is a invalid return value from `sublime.yes_no_cancel_dialog`!", sublime_dialog )

    return False
Ejemplo n.º 6
0
def throw_file_exception(self):
    line = inspect.getframeinfo(sys._getframe(0)).lineno

    try:
        log(1, "I am catching you...")
        raise Exception("Test Exception")

    except Exception as error:

        if is_python2:
            _, _, exception_traceback = sys.exc_info()
            log_traceback(error, exception_traceback)

        else:
            log_traceback(error)

    regex_pattern = re.compile(r"File \".*\",")
    output = self.file_contents(
        r"\d{2}:\d{2}:\d{2}:\d{3}\.\d{6} \d\.\d{2}e.\d{2} \- ")

    self.assertEqual(
        utilities.wrap_text("""\
            testing.main_unit_tests.throw_file_exception:{} - I am catching you...
            Traceback (most recent call last):
               line {}, in throw_file_exception
                raise Exception( "Test Exception" )
            Exception: Test Exception
            """.format(line + 3, line + 4)), regex_pattern.sub("", output))
    def on_done(answer, is_final_confirmation=True):

        if did_the_user_agreed(answer):
            input_panel_question_answer[0] = True

            if is_final_confirmation:
                restore_last_actived_panel()

                is_re_confirmed = sublime.ok_cancel_dialog(
                    wrap_text("""\
                        Thank you for agreeing with the license, as you typed: `%s`

                        If you did not mean to agree with the license, click on the `Cancel` button,
                        otherwise click on the `OK` button.
                        """ % answer,
                              single_lines=True))

                if is_re_confirmed:
                    input_panel_question_confirmation[0] = True

                else:
                    input_panel_question_answer[0] = False
                    input_panel_question_confirmation[0] = False

                    not_confirmed_correctly(False)
                    user_input_text[0] = initial_input

                can_continue[0] = True

        else:
            input_panel_question_answer[0] = False

            if is_final_confirmation:
                not_confirmed_correctly()
                can_continue[0] = True
def show_program_description():
    uninstall_button = "Completely Uninstall Everything"

    lines = \
    [
        wrap_text( """\
        Welcome to the %s Uninstallation Wizard.

        It is recommended to backup your Sublime Text's current settings and packages before
        uninstalling this, either for the Stable or Development version.

        Now you got the chance to go and backup everything. No hurries. When you finished your
        backup, you can come back here and click on the `%s` button to start now the uninstallation
        process for all the %s packages.

        This will uninstall all Sublime Text Packages the installer has installed on your computer,
        however if already there were some of these packages installed, your current version will
        not be downgraded to the version you used before installing this package. After running this
        wizard, you need to reinstall the packages you want to be restored to their original
        versions.

        If you had cancelled the Installation Wizard before it completed installing all its
        packages, or some cases when the installer is not complete, the PackagesManager could not be
        installed (as it is installed by last). Then the Uninstaller cannot run as it requires
        PackagesManager instead of Package Control. Therefore on these cases the user is required to
        install manually PackagesManager, before running the %s uninstaller.

        Click on the `Cancel` button if you want give up from installing the %s.
        """ % ( CHANNEL_PACKAGE_NAME, uninstall_button, CHANNEL_PACKAGE_NAME,
                CHANNEL_PACKAGE_NAME, CHANNEL_PACKAGE_NAME ), single_lines=True ),
    ]

    return sublime.ok_cancel_dialog("\n".join(lines), uninstall_button)
Ejemplo n.º 9
0
    def test_nonDictionaryLogging(self):
        getLogger(127, "testing.main_unit_tests", date=True)

        dictionary = {1: 'defined_chunk'}
        log('dictionary', )
        log('dictionary %s', dictionary)

        output = self.contents(
            r"\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}:\d{3}\.\d{6} \d\.\d{2}e.\d{2} \- "
        )

        self.assertEqual(
            utilities.wrap_text("""\
                + testing.main_unit_tests.test_nonDictionaryLogging:{line1} - dictionary
                + testing.main_unit_tests.test_nonDictionaryLogging:{line2} - dictionary {{1: 'defined_chunk'}}
            """.format(line1=line + 3, line2=line + 4)),
            utilities.wrap_text(output, trim_spaces=True))
Ejemplo n.º 10
0
 def test_valid_input_with_nested_langs(self):
     results = remove_lang_tag(
         r"\lang{some\lang{invalide}{stuff}more}{think\lang{stuff}{invalide}lang}"
     )
     self.assertEqual(
         wrap_text(r"""
     + think\lang{stuff}{invalide}lang
     """), results)
Ejemplo n.º 11
0
def list_repositories():
    results = {}

    try:
        search_data = flask.request.json
        log(4, f"search_data {search_data}")

        validate_request_data("repositoryUser", search_data, str)
        validate_request_dictionary("lastItemId", search_data,
                                    (str, type(None)))
        validate_request_dictionary("itemsPerPage", search_data, int)

        queryvariables = {
            "user": search_data["repositoryUser"],
            "lastItem": search_data.get("lastItemId", None),
            "items": search_data.get("itemsPerPage", 3),
        }

        # https://stackoverflow.com/questions/39551325/github-graphql-orderby
        # https://stackoverflow.com/questions/48116781/github-api-v4-how-can-i-traverse-with-pagination-graphql
        list_repositories_graphqlquery = wrap_text("""
            query ListRepositories($user: String!, $items: Int!, $lastItem: String) {
              repositoryOwner(login: $user) {
                repositories(first: $items, after: $lastItem, orderBy: {field: STARGAZERS, direction: DESC}) {
                  pageInfo {
                    hasNextPage
                    endCursor
                  }
                  nodes {
                    name
                  }
                }
              }
              %s
            }
        """) % github_ratelimit_graphql
        graphqlresults = run_graphql_query(list_repositories_graphqlquery,
                                           queryvariables)

        results["repositories"] = graphqlresults["data"]["repositoryOwner"][
            "repositories"]["nodes"]
        results["lastItemId"] = graphqlresults["data"]["repositoryOwner"][
            "repositories"]["pageInfo"]["endCursor"]
        results["hasMorePages"] = graphqlresults["data"]["repositoryOwner"][
            "repositories"]["pageInfo"]["hasNextPage"]
        results["rateLimit"] = formatratelimit(graphqlresults["data"])

    except InvalidRequest as error:
        return error.flaskResponse

    except Exception:
        return flask.Response(getstacktrace(),
                              status=500,
                              mimetype='text/plain')

    dumped_json = json.dumps(results)
    return flask.Response(dumped_json, status=200, mimetype='application/json')
    def __str__(self):
        """
            Return the full history representation of the saved grammar.
        """


        if self.extra_text:

            if len( self.extra_text ) == 1 \
                    and self.extra_text[0] == NO_GRAMMAR_CHANGES \
                    and self.stage.value != IntermediateGrammar.BEGINNING:

                return wrap_text( """%s%s\n#    %s
                    """ % ( self.name, self.stage, "\n#    ".join( self.extra_text ) ) )

            return wrap_text( """%s%s\n#    %s\n%s
                """ % ( self.name, self.stage, "\n#    ".join( self.extra_text ), self.grammar ) )

        return wrap_text( """%s%s\n%s
            """ % ( self.name, self.stage, self.grammar ) )
Ejemplo n.º 13
0
 def test_big_paragraphs(self):
     results = remove_lang_tag(
         wrap_text(r"""
     \preambulo{\lang%
         {%
             \imprimirtipotrabalho~submitted to the \imprimirprograma~of
             \imprimirinstituicao~for degree acquirement in \imprimirformacao.%
         }{%
             \imprimirtipotrabalho~submetido ao \imprimirprograma~da
             \imprimirinstituicao~para a obtenção do Grau de \imprimirformacao.%
         }%
     }
     """))
     self.assertEqual(
         wrap_text(r"""
     + \preambulo{%
     +         \imprimirtipotrabalho~submetido ao \imprimirprograma~da
     +         \imprimirinstituicao~para a obtenção do Grau de \imprimirformacao.%
     +     %
     + }
     """), results)
def show_goodbye_message():
    ok_button_text = "Return to the Wizard"
    negative_button_text = "Never ask again"

    lines = \
    [
        wrap_text( """\
        Thank you for looking to install the {channel_name}, but as you do not agree with its usage
        license and completed the installation wizard, the {channel_name} need to be uninstalled as
        it does nothing else useful for you.

        If you want to consider installing it, click on the button `{ok_button}` to go back and try
        again. Otherwise click on the `Cancel` button and then uninstall the {channel_name} package.

        If you wish to install the {installation_type} later, you can go to the menu `Preferences ->
        Packages -> {channel_name}` and select the option `{installation_type}`, to run this
        Installer Wizard again. Or select the button `{negative_button_text}` to show this Wizard on
        the next time you start Sublime Text.

        If you wish to install the {channel_name} later, after uninstalling it, you can just install
        this package again.
        """.format( ok_button=ok_button_text, negative_button_text=negative_button_text,
                installation_type=g_installation_command, channel_name=CHANNEL_PACKAGE_NAME ), single_lines=True ),
    ]

    channelDetailsPath = g_channelSettings['CHANNEL_INSTALLATION_DETAILS']

    channelDetails = load_data_file(channelDetailsPath)
    sublime_dialog = sublime.yes_no_cancel_dialog("\n".join(lines),
                                                  ok_button_text,
                                                  negative_button_text)

    if sublime_dialog == sublime.DIALOG_YES:  # "Return to the Wizard"
        return True

    elif sublime_dialog == sublime.DIALOG_NO:  # "Never ask again"
        channelDetails['automatically_show_installation_wizard'] = False

    elif sublime_dialog == sublime.DIALOG_CANCEL:  # When pressing escape key, it returns DIALOG_CANCEL
        channelDetails['automatically_show_installation_wizard'] = True

    else:
        log(
            1,
            "Error: The option `%s` is a invalid return value from `sublime.yes_no_cancel_dialog`!",
            sublime_dialog)
        channelDetails['automatically_show_installation_wizard'] = False

    write_data_file(channelDetailsPath, channelDetails)
    return False
Ejemplo n.º 15
0
    def test_function_name(self):
        getLogger(127, "testing.main_unit_tests", date=True)

        log(1, "Bitwise")
        log(8, "Bitwise")
        log.warn("Warn")
        log.info("Info")
        log.debug("Debug")
        log.newline()

        def function_name():
            log(1, "Bitwise")
            log(8, "Bitwise")
            log.warn("Warn")
            log.info("Info")
            log.debug("Debug")

        function_name()
        output = self.contents(
            r"\d{4}\-\d{2}-\d{2} \d{2}:\d{2}:\d{2}:\d{3}\.\d{6} \d\.\d{2}e.\d{2} \- "
        )

        offset1 = 1
        offset2 = 4

        self.assertEqual(
            utilities.wrap_text("""\
            testing.main_unit_tests.test_function_name:{} - Bitwise
            testing.main_unit_tests.test_function_name:{} - Bitwise
            testing.main_unit_tests.test_function_name:{} - Warn
            testing.main_unit_tests.test_function_name:{} - Info
            testing.main_unit_tests.test_function_name:{} - Debug

            testing.main_unit_tests.function_name:{} - Bitwise
            testing.main_unit_tests.function_name:{} - Bitwise
            testing.main_unit_tests.function_name:{} - Warn
            testing.main_unit_tests.function_name:{} - Info
            testing.main_unit_tests.function_name:{} - Debug
            """.format(
                line + offset1 + 1,
                line + offset1 + 2,
                line + offset1 + 3,
                line + offset1 + 4,
                line + offset1 + 5,
                line + offset2 + 6,
                line + offset2 + 7,
                line + offset2 + 8,
                line + offset2 + 9,
                line + offset2 + 10,
            )), output)
def start_the_installation_process():
    g_link_wrapper.width = 70

    lines = \
    [
        wrap_text( """\
        The installation process has started. You should be able to see the Sublime Text Console
        opened on your Sublime Text window. If not, you can open it by going on to the menu `View ->
        Show Console (Ctrl+')`.

        If you wish to uninstall the {channel_name}, you can do this by either `PackagesManager
        (Package Control Replacement)` or by going to the menu the menu `Preferences -> Packages
        Settings -> {channel_name}` and select the option `{uninstallation_command}`.

        Even if you just half installed {channel_name}, you can uninstall it with all its files. To
        ensure a correct uninstallation, we create a configuration file on your User folder called
        `{channel_name}.sublime-settings`. This file registers all installed folders, packages and
        files to your Sublime Text. Then it can correctly later remove everything which belongs to
        it. Just do not edit this file add or removing things, as it can make the uninstallation
        delete files which it should not to.

        The installation process should take about 2~5 minutes for the Stable Version and 10~20
        minutes for the Development Version, depending on your Computer Performance. Any problems
        you have with the process you can open issue on the {channel_name} issue tracker at the
        address:
        """.format( channel_name=CHANNEL_PACKAGE_NAME, uninstallation_command=g_uninstallation_command ), single_lines=True ),
        "",
        g_link_wrapper.fill( "<%s/issues>" % g_channelSettings['CHANNEL_ROOT_URL'] ),
        "",
        wrap_text( """\
        Just do not forget to save your Sublime Text Console output, as it recorded everything which
        happened, and should be very helpful in finding the solution for the problem.
        """, single_lines=True ),
    ]

    install_channel()
    sublime.message_dialog("\n".join(lines))
Ejemplo n.º 17
0
def detail_repository():
    results = {}

    try:
        search_data = flask.request.json
        log(4, f"search_data {search_data}")

        validate_request_data("repositoryUser", search_data, str)
        validate_request_data("repositoryName", search_data, str)

        queryvariables = {
            "user": search_data["repositoryUser"],
            "repo": search_data["repositoryName"],
        }

        # https://graphql.org/learn/queries/
        detail_repository_graphqlquery = wrap_text("""
            query GetRepository($user: String!, $repo: String!) {
              repository(owner: $user, name: $repo) {
                createdAt
                issues(states:OPEN) {
                  totalCount
                }
                languages(first: 1) {
                  nodes {
                    name
                  }
                }
              }
              %s
            }
        """) % github_ratelimit_graphql
        graphqlresults = run_graphql_query(detail_repository_graphqlquery,
                                           queryvariables)
        results = graphqlresults["data"]["repository"]
        results["rateLimit"] = formatratelimit(graphqlresults["data"])

    except InvalidRequest as error:
        return error.flaskResponse

    except Exception:
        return flask.Response(getstacktrace(),
                              status=500,
                              mimetype='text/plain')

    dumped_json = json.dumps(results)
    return flask.Response(dumped_json, status=200, mimetype='application/json')
Ejemplo n.º 18
0
    def test_date_disabled(self):
        getLogger("testing.main_unit_tests", 127, function=False)

        log(1, "Bitwise")
        log(8, "Bitwise")
        log.warn("Warn")
        log.info("Info")
        log.debug("Debug")

        output = self.contents(
            r"\d{2}:\d{2}:\d{2}:\d{3}\.\d{6} \d\.\d{2}e.\d{2} \- ")
        self.assertEqual(
            utilities.wrap_text("""\
            testing.main_unit_tests - Bitwise
            testing.main_unit_tests - Bitwise
            testing.main_unit_tests - Warn
            testing.main_unit_tests - Info
            testing.main_unit_tests - Debug
            """), output)
Ejemplo n.º 19
0
    def test_get_logger_more_empty(self):
        getLogger(function=False, name=False)

        log(1, "Bitwise")
        log(8, "Bitwise")
        log.warn("Warn")
        log.info("Info")
        log.debug("Debug")

        output = self.contents(
            r"\d{2}:\d{2}:\d{2}:\d{3}\.\d{6} \d\.\d{2}e.\d{2} \- ")
        self.assertEqual(
            utilities.wrap_text("""\
            Bitwise
            Bitwise
            Warn
            Info
            Debug
            """), output)
def show_installation_confirmation():
    version_to_install = upcase_first_letter(g_version_to_install)

    lines = \
    [
        wrap_text( """\
        You choose to install the {version_to_install} Version. It is recommended to backup your Sublime Text's
        current settings and packages before installing this, either for the Stable or Development
        version.

        Now you got the chance to go and backup everything. No hurries. When you finished your
        backup, you can come back here and click on the `Install Now` button to start now the
        installation process for the {version_to_install} Version. Click on the `Go Back` button if you wish to
        choose another version, or in `Cancel` button if you want give up from installing the
        {channel_name}.

        While the {channel_name} is being installed, either the Stable Version or the Development
        Version, you can follow the installation progress seeing your Sublime Text Console. The
        console will be automatically opened for you when you start the installation process, but
        you can also open it by going on the menu `View -> Show Console (Ctrl+')`.

        When you are monitoring the installation process, you will see several error messages. This
        is expected because while doing the batch installation process, the packages are not able to
        initialize/start properly, hence some of them will throw several errors. Now, once the
        installation process is finished, you will be asked to restart Sublime Text.

        Then, after the restarting Sublime Text, all the installed packages will be finished
        installing by the `PackagesManager` (Package Control fork replacement), which will also ask
        you to restart Sublime Text, when it finish install all missing dependencies.

        If you wish to cancel the installation process while it is going on, you need to restart
        Sublime Text. However not all packages will installed and some can be corrupted or half
        installed. Later on, to finish the installation you will need to run the uninstaller by
        going on the menu `Preferences -> Packages Settings -> {channel_name}` and select the option
        `{uninstallation_command}`. Then later install again the {channel_name}.
        """.format( version_to_install=version_to_install, channel_name=CHANNEL_PACKAGE_NAME,
                uninstallation_command=g_uninstallation_command ), single_lines=True ),
        ]

    return calculate_next_step(
        sublime.yes_no_cancel_dialog("\n".join(lines), "Install Now",
                                     "Go Back"))
Ejemplo n.º 21
0
    def test_exception_throwing(self):
        getLogger("testing.main_unit_tests", 127)

        try:
            raise Exception("Test Error")
        except Exception:
            log.exception("I am catching you")

        regex_pattern = re.compile(r"File \".*\", line \d+,")
        output = self.contents(
            r"\d{2}:\d{2}:\d{2}:\d{3}\.\d{6} \d\.\d{2}e.\d{2} \- ")

        self.assertEqual(
            utilities.wrap_text("""\
                testing.main_unit_tests.test_exception_throwing:{} - I am catching you
                Traceback (most recent call last):
                   in test_exception_throwing
                    raise Exception( "Test Error" )
                Exception: Test Error
            """.format(line + 5)), regex_pattern.sub("", output))
    def not_confirmed_correctly(is_to_show_typed_input=True):
        active_window.run_command("hide_panel")
        restore_last_actived_panel()

        typed_text = "" if not is_to_show_typed_input else """\
                You typed: {input_text}

                You did not typed you agree with the {channel_name} license as required when you
                agree with the license, on the input panel at your Sublime Text window.
                """.format(input_text=user_input_text[0],
                           channel_name=CHANNEL_PACKAGE_NAME)

        sublime.message_dialog(
            wrap_text("""\
                {typed_text}
                Please, click in `Cancel` instead of `Next` on the next message dialog, if you do
                not agree with the
                {channel_name} license.
                """.format(channel_name=CHANNEL_PACKAGE_NAME,
                           typed_text=typed_text),
                      single_lines=True))
Ejemplo n.º 23
0
    def test_no_function_name_and_level(self):
        getLogger(127,
                  "testing.main_unit_tests",
                  date=True,
                  function=False,
                  level=True)

        log(1, "Bitwise")
        log(8, "Bitwise")
        log.warn("Warn")
        log.info("Info")
        log.debug("Debug")

        output = self.contents(
            r"\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}:\d{3}\.\d{6} \d\.\d{2}e.\d{2} \- "
        )
        self.assertEqual(
            utilities.wrap_text("""\
            testing.main_unit_tests DEBUG(1) - Bitwise
            testing.main_unit_tests DEBUG(8) - Bitwise
            testing.main_unit_tests WARNING - Warn
            testing.main_unit_tests INFO - Info
            testing.main_unit_tests DEBUG - Debug
            """), output)
Ejemplo n.º 24
0
    def create_grammar_input_text(self):
        # https://www.penwatch.net/cms/pyqt5_qplaintextedit/
        self.grammarTextEditWidget = QPlainTextEdit(self)
        self.grammarTextEditWidget.setLineWrapMode(QPlainTextEdit.NoWrap)

        # Change font, colour of text entry box
        self.grammarTextEditWidget.setStyleSheet(self.getMainFontOptions())

        # Set initial value of text
        self.grammarTextEditWidget.document().setPlainText(
            self.settings.value(
                "mainWindowGrammarTextEditWidget",
                wrap_text("""
            # Write your Grammar here
            S -> a A | a
            A -> b S | b
        """)))

        self.redoGrammarButton = QPushButton("Redo Operation")
        self.undoGrammarButton = QPushButton("Undo Operation")
        self.calculateFirstAndFollow = QPushButton("Compute First and Follow")
        self.convertToProperGrammar = QPushButton("Convert to Proper")
        self.isGrammarFactored = QPushButton("Is Factored")
        self.tryToFactorGrammar = QPushButton("Try to Factor it")
        self.grammarHasLeftRecursion = QPushButton("Has Left Recursion")
        self.isGrammarEmpty = QPushButton("Is Empty")
        self.isGrammarFinite = QPushButton("Is Finite")
        self.isGrammarInfinite = QPushButton("Is Infinite")
        self.isGrammarEmptyOrInFinite = QPushButton("Is Empty Or (In)Finite")
        self.openGrammar = QPushButton("Open File")
        self.saveGrammar = QPushButton("Save File")
        self.grammarBeautifing = QPushButton("Beautify")

        self.undoGrammarButton.clicked.connect(self.handleUndoGrammarTextEdit)
        self.redoGrammarButton.clicked.connect(self.handleRedoGrammarTextEdit)
        self.calculateFirstAndFollow.clicked.connect(
            self.handleCalculateFirstAndFollow)
        self.isGrammarFactored.clicked.connect(self.handleIsGrammarFactored)
        self.tryToFactorGrammar.clicked.connect(self.handleTryToFactorGrammar)
        self.grammarHasLeftRecursion.clicked.connect(
            self.handleGrammarHasLeftRecursion)
        self.convertToProperGrammar.clicked.connect(
            self.handleConvertToProperGrammar)
        self.isGrammarEmpty.clicked.connect(self.handleIsGrammarEmpty)
        self.isGrammarFinite.clicked.connect(self.handleIsGrammarFinite)
        self.isGrammarInfinite.clicked.connect(self.handleIsGrammarInfinite)
        self.isGrammarEmptyOrInFinite.clicked.connect(
            self.handleGrammarIsFiniteInfiniteOrEmpty)
        self.openGrammar.clicked.connect(self.handleOpenGrammar)
        self.saveGrammar.clicked.connect(self.handleSaveGrammar)
        self.grammarBeautifing.clicked.connect(self.handleGrammarBeautifing)

        # The distances between the QPushButton in QGridLayout
        # https://stackoverflow.com/questions/13578187/the-distances-between-the-qpushbutton-in-qgridlayout
        self.grammarVerticalGridLayout = QGridLayout()
        self.grammarVerticalGridLayout.addWidget(self.undoGrammarButton, 0, 0)
        self.grammarVerticalGridLayout.addWidget(self.redoGrammarButton, 1, 0)
        self.grammarVerticalGridLayout.addWidget(self.get_vertical_separator(),
                                                 2, 0)
        self.grammarVerticalGridLayout.addWidget(self.calculateFirstAndFollow,
                                                 3, 0)
        self.grammarVerticalGridLayout.addWidget(self.convertToProperGrammar,
                                                 4, 0)
        self.grammarVerticalGridLayout.addWidget(self.isGrammarFactored, 5, 0)
        self.grammarVerticalGridLayout.addWidget(self.tryToFactorGrammar, 6, 0)
        self.grammarVerticalGridLayout.addWidget(self.grammarHasLeftRecursion,
                                                 7, 0)
        self.grammarVerticalGridLayout.addWidget(self.get_vertical_separator(),
                                                 8, 0)
        self.grammarVerticalGridLayout.addWidget(self.isGrammarEmpty, 9, 0)
        self.grammarVerticalGridLayout.addWidget(self.isGrammarFinite, 10, 0)
        self.grammarVerticalGridLayout.addWidget(self.isGrammarInfinite, 11, 0)
        self.grammarVerticalGridLayout.addWidget(self.isGrammarEmptyOrInFinite,
                                                 12, 0)
        self.grammarVerticalGridLayout.addWidget(self.get_vertical_separator(),
                                                 13, 0)
        self.grammarVerticalGridLayout.addWidget(self.openGrammar, 14, 0)
        self.grammarVerticalGridLayout.addWidget(self.saveGrammar, 15, 0)
        # self.grammarVerticalGridLayout.addWidget( self.grammarBeautifing,        16, 0)
        self.grammarVerticalGridLayout.setSpacing(0)
        self.grammarVerticalGridLayout.setAlignment(Qt.AlignTop)

        # How to align the layouts QHBoxLayout and QVBoxLayout on pyqt4?
        # https://stackoverflow.com/questions/44230856/how-to-align-the-layouts-qhboxlayout-and-qvboxlayout-on-pyqt4
        self.grammarInnerLayout = QHBoxLayout()
        self.grammarInnerLayout.addLayout(self.grammarVerticalGridLayout)
        self.grammarInnerLayout.addWidget(self.grammarTextEditWidget)
Ejemplo n.º 25
0
 def test_simplest_valid_input(self):
     results = remove_lang_tag(r"\lang{some}{thing}")
     self.assertEqual(wrap_text("""
     + thing
     """), results)
def show_license_agreement():
    is_to_go_back = False
    active_window = sublime.active_window()
    can_continue = [False]

    active_window_panel = active_window.active_panel()
    g_link_wrapper.width = 71

    initial_input = "Type Here"
    user_input_text = [initial_input]
    agrement_text = "i did read and agree"

    input_panel_question_answer = [None]
    input_panel_question_confirmation = [None]

    lines = \
    [
        wrap_text( """\
        Welcome to the %s Installation Wizard. The installed packages by this wizard, in addition to
        each one own license, are distributed under the following conditions for its usage and
        installation:

        ALL THE SOFTWARES, PACKAGES, PLUGINS, SETTINGS, DOCUMENTATION, EVERYTHING ELSE, ARE PROVIDED
        \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
        THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
        NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
        CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

        On the following addresses you can find the list and links for all distributed contents by
        this installer, which these conditions above applies to, and their respective software
        license:
        """ % CHANNEL_PACKAGE_NAME, single_lines=True ),
        "",
        g_link_wrapper.fill( "<%s#License>" % g_channelSettings['CHANNEL_ROOT_URL'] ),
        g_link_wrapper.fill( "<%s>" % g_channelSettings['CHANNEL_FILE_URL'] ),
        "",
        wrap_text( """\
        Did you read and agree with these conditions for using these softwares, packages, plugins,
        documentations, everything else provided? If you not agree with it, click on the `Cancel`
        button, instead of the `Next` button.

        If you do agree with these conditions, type the following phrase on the input panel which is
        open at the bottom of your Sublime Text window and then click on the `Next` button to
        proceed to the next step:
        """, single_lines=True ),
        "",
        g_link_wrapper.fill( agrement_text ),
    ]

    def restore_last_actived_panel():

        if active_window_panel:
            sublime.active_window().run_command("show_panel", {
                "panel": active_window_panel,
                "toggle": False
            })

    def not_confirmed_correctly(is_to_show_typed_input=True):
        active_window.run_command("hide_panel")
        restore_last_actived_panel()

        typed_text = "" if not is_to_show_typed_input else """\
                You typed: {input_text}

                You did not typed you agree with the {channel_name} license as required when you
                agree with the license, on the input panel at your Sublime Text window.
                """.format(input_text=user_input_text[0],
                           channel_name=CHANNEL_PACKAGE_NAME)

        sublime.message_dialog(
            wrap_text("""\
                {typed_text}
                Please, click in `Cancel` instead of `Next` on the next message dialog, if you do
                not agree with the
                {channel_name} license.
                """.format(channel_name=CHANNEL_PACKAGE_NAME,
                           typed_text=typed_text),
                      single_lines=True))

    def did_the_user_agreed(answer):
        user_input_text[0] = answer
        return answer.replace(".", "").replace(",", "").strip(" ").replace(
            "  ", " ").lower() == agrement_text

    def on_done(answer, is_final_confirmation=True):

        if did_the_user_agreed(answer):
            input_panel_question_answer[0] = True

            if is_final_confirmation:
                restore_last_actived_panel()

                is_re_confirmed = sublime.ok_cancel_dialog(
                    wrap_text("""\
                        Thank you for agreeing with the license, as you typed: `%s`

                        If you did not mean to agree with the license, click on the `Cancel` button,
                        otherwise click on the `OK` button.
                        """ % answer,
                              single_lines=True))

                if is_re_confirmed:
                    input_panel_question_confirmation[0] = True

                else:
                    input_panel_question_answer[0] = False
                    input_panel_question_confirmation[0] = False

                    not_confirmed_correctly(False)
                    user_input_text[0] = initial_input

                can_continue[0] = True

        else:
            input_panel_question_answer[0] = False

            if is_final_confirmation:
                not_confirmed_correctly()
                can_continue[0] = True

    def on_change(answer):
        on_done(answer, False)

    def on_cancel():
        can_continue[0] = True

    def show_acknowledgment_panel():
        can_continue[0] = False

        widget_view = active_window.show_input_panel(
            "Did you read and agree with these conditions for using these softwares?",
            user_input_text[0], on_done, on_change, on_cancel)

        if user_input_text[0] == initial_input:
            widget_view.run_command("select_all")

        # show_input_panel is a non-blocking function, but we can only continue after on_done being called
        while not can_continue[0]:
            time.sleep(0.5)

    while True:
        is_yes_answer, is_to_go_back = calculate_next_step(
            sublime.yes_no_cancel_dialog("\n".join(lines), "Next", "Go Back"))

        if is_to_go_back \
                or input_panel_question_answer[0] and input_panel_question_confirmation[0] is False:
            break

        if is_yes_answer:
            show_acknowledgment_panel()

        else:
            break

        if input_panel_question_answer[
                0] and input_panel_question_confirmation[0]:
            break

    restore_last_actived_panel()
    return input_panel_question_answer[0] and is_yes_answer, is_to_go_back
Ejemplo n.º 27
0
    def __init__(self, parent, settings, fontOptions, _openFileCall, dialogTypeName, dialogTitleMessage):
        super().__init__( parent )
        self.result = 0
        self.setAttribute( Qt.WA_DeleteOnClose )

        self.settings = settings
        self._openFileCall = _openFileCall

        # QWidget::setLayout: Attempting to set QLayout “” on ProgramWindow “”, which already has a layout
        # https://stackoverflow.com/questions/50176661/qwidgetsetlayout-attempting-to-set-qlayout-on-programwindow-which-alre
        self.centralwidget = QWidget()
        self.setCentralWidget( self.centralwidget )
        self.setWindowTitle( dialogTitleMessage )

        # Initial window size/pos last saved. Use default values for first time
        windowScreenGeometry = self.settings.value( "stringInputWindowScreenGeometry" )
        windowScreenState = self.settings.value( "stringInputWindowScreenState" )

        if windowScreenGeometry:
            self.restoreGeometry( windowScreenGeometry )

        else:
            self.resize( 600, 400 )
            # self.move( get_screen_center( self ) )

        if windowScreenState:
            self.restoreState( windowScreenState )

        # nice widget for editing the date
        self.textEditWidget = QPlainTextEdit( self )
        self.textEditWidget.setLineWrapMode( QPlainTextEdit.NoWrap )

        # Detect Ctrl+S ion QTextedit?
        # https://stackoverflow.com/questions/43010630/detect-ctrls-ion-qtextedit
        enterShortcut = QShortcut( QKeySequence( "Ctrl+Enter" ), self.textEditWidget )
        returnShortcut = QShortcut( QKeySequence( "Ctrl+Return" ), self.textEditWidget )
        enterShortcut.activated.connect( self.accept )
        returnShortcut.activated.connect( self.accept )

        # Set initial value of text
        self.textEditWidget.document().setPlainText( wrap_text( """
            # Write your %s here
            # or open it from a new file
        """ % dialogTypeName ) + "\n\n" )

        # Change font, colour of text entry box
        self.textEditWidget.selectAll()
        self.textEditWidget.setStyleSheet( fontOptions )

        # OK and Cancel buttons
        self.standardButtons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self )
        self.openFileButton = QPushButton( "Open a %s from a file" % dialogTypeName )

        self.standardButtons.accepted.connect( self.accept )
        self.standardButtons.rejected.connect( self.reject )
        self.openFileButton.clicked.connect( self.handleOpenFileCall )

        # Setup the main layout
        self.verticalLayout = QVBoxLayout( self.centralwidget )
        self.horizontalLayout = QHBoxLayout()

        self.verticalLayout.addWidget( self.textEditWidget )
        self.verticalLayout.addLayout( self.horizontalLayout )

        self.horizontalLayout.addWidget( self.openFileButton )
        self.horizontalLayout.addWidget( self.standardButtons )
Ejemplo n.º 28
0
def search_github():
    results = {}

    try:
        search_data = flask.request.json
        log(4, f"search_data {search_data}")

        validate_request_data("searchQuery", search_data, str)
        validate_request_dictionary("lastItemId", search_data,
                                    (str, type(None)))
        validate_request_dictionary("itemsPerPage", search_data, int)

        queryvariables = {
            "query": search_data["searchQuery"],
            "items": search_data.get("itemsPerPage", 3),
            "lastItem": search_data.get("lastItemId", None),
        }

        # https://github.community/t5/GitHub-API-Development-and/graphql-search-query-format/td-p/19238
        search_github_graphqlquery = wrap_text("""
            query SearchRepositories($query: String!, $items: Int!, $lastItem: String) {
              search(first: $items, query: $query, type: REPOSITORY, after: $lastItem) {
                pageInfo {
                  hasNextPage
                  endCursor
                }
                repositoryCount
                nodes {
                  ... on Repository {
                    nameWithOwner
                    description
                    stargazers {
                      totalCount
                    }
                  }
                }
              }
              %s
            }
        """) % github_ratelimit_graphql
        graphqlresults = run_graphql_query(search_github_graphqlquery,
                                           queryvariables)

        results["repositoryCount"] = graphqlresults["data"]["search"][
            "repositoryCount"]
        results["repositories"] = graphqlresults["data"]["search"]["nodes"]
        results["lastItemId"] = graphqlresults["data"]["search"]["pageInfo"][
            "endCursor"]
        results["hasMorePages"] = graphqlresults["data"]["search"]["pageInfo"][
            "hasNextPage"]
        results["rateLimit"] = formatratelimit(graphqlresults["data"])

    except InvalidRequest as error:
        return error.flaskResponse

    except Exception:
        return flask.Response(getstacktrace(),
                              status=500,
                              mimetype='text/plain')

    dumped_json = json.dumps(results)
    return flask.Response(dumped_json, status=200, mimetype='application/json')
Ejemplo n.º 29
0
APP = flask.Flask(
    "github_repository_researcher",
    static_folder="reactfrontend/build/static",
    template_folder="reactfrontend/build",
)

# https://stackoverflow.com/questions/25594893/how-to-enable-cors-in-flask-and-heroku
# https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present
flask_cors.CORS(APP)

github_ratelimit_graphql = wrap_text("""
    rateLimit {
        limit
        cost
        remaining
        resetAt
    }
    viewer {
        login
    }
""")


def main():
    log(f"headers {str(headers)[:30]}...")
    log(f"REACT_APP_GITHUB_RESEARCHER_BACKEND_PORT {os.environ.get( 'REACT_APP_GITHUB_RESEARCHER_BACKEND_PORT' )}..."
        )

    graphqlresults = run_graphql_query(f"{{{github_ratelimit_graphql}}}")
    log(formatratelimit(graphqlresults["data"]))
Ejemplo n.º 30
0
    S92 -> b S93 | b
    S93 -> b S93 | b
"""
"""

profiling a method of a class in Python using cProfile?
https://stackoverflow.com/questions/4492535/profiling-a-method-of-a-class-in-python-using-cprofile

Python getting meaningful results from cProfile
https://stackoverflow.com/questions/21274898/python-getting-meaningful-results-from-cprofile

"""

# cProfile.runctx( "firstGrammar = ChomskyGrammar.load_from_text_lines( wrap_text( arg ) )", globals(), locals(), sort='time' )
# cProfile.runctx( "firstGrammar.is_factored()", globals(), locals(), sort='time' )

profiller = cProfile.Profile()
profiller.enable()

# firstGrammar = ChomskyGrammar.load_from_text_lines( wrap_text( "S -> S" ) )
firstGrammar = ChomskyGrammar.load_from_text_lines(wrap_text(arg))

profiller.disable()
output_stream = StringIO()

profiller_status = pstats.Stats(profiller, stream=output_stream)
profiller_status.sort_stats("time")
profiller_status.print_stats()

print(output_stream.getvalue())