Example #1
0
def test_bad():
    '''
    test the failure when loading malformed data
    '''
    mlh = MockLoggingHandler()
    logging.getLogger('ConfigurableDb').addHandler(mlh)
    with fixLibPath([join(data_root, 'bad')]):
        from GaudiKernel.ConfigurableDb import loadConfigurableDb
        loadConfigurableDb()
        warnings = mlh.messages['warning']
        assert filter(re_comp(r'Could not load.*bad.confdb').match, warnings)
        assert filter(re_comp(r'Reason: invalid line format').match, warnings)
Example #2
0
                f'{k}={v}' for k, v in req.args.items())))):
        return

    result = res.text.encode()

    # Overwrite cache
    glob.cache['update'][req.args['stream']] = {
        'result': result,
        'timeout': current_time + 3600
    }

    return result


_map_regex = re_comp(
    r'^(?P<artist>.+) - (?P<title>.+) \((?P<creator>.+)\) \[(?P<version>.+)\]\.osu$'
)


def updateBeatmap(req: Request) -> Optional[bytes]:
    # XXX: This currently works in updating the map, but
    # seems to get the checksum something like that wrong?
    # Will have to look into it :P
    if not (re := _map_regex.match(unquote(req.uri[10:]))):
        printlog(f'Requested invalid map update {req.uri}.', Ansi.RED)
        return b''

    if not (res := glob.db.fetch(
            'SELECT id, md5 FROM maps WHERE '
            'artist = %s AND title = %s '
            'AND creator = %s AND version = %s',
class FmCreateFileFromSelectionCommand(sublime_plugin.TextCommand):

    CONTEXT_MAX_LENGTH = 50
    MATCH_SOURCE_ATTR = re_comp(r'(src|href) *= *$')
    MATCH_JS_REQUIRE = re_comp(r'require\(\s*$')
    MATCH_RUBY_REQUIRE = re_comp(r'require_relative\s*\(?\s*$')

    def run(self, edit, event):
        base_path, input_path = self.get_path(event)
        abspath = computer_friendly(os.path.join(base_path, input_path))
        sublime.run_command('fm_creater', {'abspath': abspath,
                                           'input_path': input_path})

    def want_event(self):
        return True

    def get_path(self, event, for_context_menu=False):
        """
            @return (base_path: str, relative_path: str)
        """
        file_name = None
        region = self.view.sel()[0]
        if not region.empty():
            file_name = self.view.substr(region)
        else:
            syntax = self.view.settings().get('syntax').lower()
            call_pos = self.view.window_to_text((event["x"], event["y"]))
            current_line = self.view.line(call_pos)
            if 'html' in syntax:
                region = self.view.extract_scope(call_pos)
                text = self.view.substr(sublime.Region(0, self.view.size()))
                text = text[:region.begin()]
                if self.MATCH_SOURCE_ATTR.search(text):
                    file_name = self.view.substr(region)[:-1]
                    # removes the " at the end, I guess this is due to the
                    # PHP syntax definition
                else:
                    return
            elif 'python' in syntax:
                current_line = self.view.substr(current_line)
                if current_line.startswith('from .'):
                    current_line = current_line[6:]
                    index = current_line.find(' import')
                    if index < 0:
                        return
                    current_line = current_line[:index].replace('.', '/')
                    if current_line.startswith('/'):
                        current_line = '..' + current_line
                    file_name = current_line + '.py'
                elif current_line.startswith('import '):
                    file_name = current_line[7:].replace('.', '/') + '.py'
                else:
                    return
            elif 'php' in syntax:
                current_line = self.view.substr(current_line)
                if not (current_line.startswith('include ') or
                        current_line.startswith('require ')):
                    return
                file_name = self.view.substr(
                                self.view.extract_scope(call_pos))
            elif 'javascript' in syntax:
                # for now, it only supports require
                region = self.view.extract_scope(call_pos)
                text = self.view.substr(sublime.Region(0, self.view.size()))
                text = text[:region.begin()]
                if self.MATCH_JS_REQUIRE.search(text) is None:
                    return
                # [1:-1] removes the quotes
                file_name = self.view.substr(region)[1:-1]
                if not file_name.endswith('.js'):
                    file_name += '.js'
            elif 'ruby' in syntax:
                region = self.view.extract_scope(call_pos)
                text = self.view.substr(sublime.Region(0, self.view.size()))
                text = text[:region.begin()]
                if self.MATCH_RUBY_REQUIRE.search(text) is None:
                    return
                # [1:-1] removes the quotes
                file_name = self.view.substr(region)[1:-1]
                if not file_name.endswith('.rb'):
                    file_name += '.rb'
            else:
                return

        if file_name[0] in ('"', "'"):
            file_name = file_name[1:]
        if file_name[-1] in ('"', "'"):
            file_name = file_name[:-1]

        return os.path.dirname(self.view.file_name()), file_name

    def description(self, event):
        base, file_name = self.get_path(event, True)
        keyword = 'Open' if os.path.isfile(os.path.join(base, file_name)) else 'Create'
        while file_name.startswith('../'):
            file_name = file_name[3:]
            base = os.path.dirname(base)
        base, file_name = user_friendly(base), user_friendly(file_name)

        if len(base) + len(file_name) > self.CONTEXT_MAX_LENGTH:
            path = base[:self.CONTEXT_MAX_LENGTH - len(file_name) - 4]
            path += '.../' + file_name
        else:
            path = base + '/' + file_name
        return keyword + ' ' + path

    def is_visible(self, event=None):
        if event is None: return False
        return get_settings().get('show_create_from_selection_command') and self.view.file_name() is not None and self.get_path(event) is not None
Example #4
0
# -*- encoding: utf-8 -*-

import yaml
from .constants import *
from .keymap_dumper import keymap_dump
from json import dumps
from re import compile as re_comp, escape as re_escape

SPLIT_KEYS = re_comp(r'(?<!\+), ?')

def pprint(*objs):
    for obj in objs:
        # CSW: ignore
        print(dumps(obj, indent=2, ensure_ascii=False))

def get_context_definitions(keybindings, errors):
    real_keybindings = []
    context_definitions = {}
    for keybinding in keybindings:
        if 'context_definitions' in keybinding.keys():
            context_definitions.update(keybinding['context_definitions'])
        else:
            real_keybindings.append(keybinding)
    return real_keybindings, context_definitions

def flatten_keybindings(keybindings, errors):
    valid_keybindings = []
    for keybinding in keybindings:
        if 'with_contexts' not in keybinding.keys():
            valid_keybindings.append(keybinding)
            continue
class FmCreateFileFromSelectionCommand(sublime_plugin.TextCommand):

    CONTEXT_MAX_LENGTH = 50
    MATCH_SOURCE_ATTR = re_comp(r"(src|href) *= *$")
    MATCH_JS_REQUIRE = re_comp(r"require\(\s*$")
    MATCH_RUBY_REQUIRE = re_comp(r"require_relative\s*\(?\s*$")

    @property
    def settings(cls):
        try:
            return cls.settings_
        except AttributeError:
            cls.settings_ = sublime.load_settings(
                "FileManager.sublime-settings")
            return cls.settings_

    def run(self, edit, event):
        base_path, input_path = self.get_path(event)
        abspath = computer_friendly(os.path.join(base_path, input_path))
        sublime.run_command("fm_creater", {
            "abspath": abspath,
            "input_path": input_path
        })

    def want_event(self):
        return True

    def get_path(self, event, for_context_menu=False):
        """
            @return (base_path: str, relative_path: str)
        """
        file_name = None
        region = self.view.sel()[0]
        if not region.empty():
            file_name = self.view.substr(region)
            if "\n" in file_name:
                return
        else:
            syntax = self.view.settings().get("syntax").lower()
            call_pos = self.view.window_to_text((event["x"], event["y"]))
            current_line = self.view.line(call_pos)
            if "html" in syntax:
                region = self.view.extract_scope(call_pos)
                text = self.view.substr(sublime.Region(0, self.view.size()))
                text = text[:region.begin()]
                if self.MATCH_SOURCE_ATTR.search(text):
                    file_name = self.view.substr(region)[:-1]
                    # removes the " at the end, I guess this is due to the
                    # PHP syntax definition
                else:
                    return
            elif "python" in syntax:
                current_line = self.view.substr(current_line)
                if current_line.startswith("from ."):
                    current_line = current_line[6:]
                    index = current_line.find(" import")
                    if index < 0:
                        return
                    current_line = current_line[:index].replace(".", "/")
                    if current_line.startswith("/"):
                        current_line = ".." + current_line
                    file_name = current_line + ".py"
                elif current_line.startswith("import "):
                    file_name = current_line[7:].replace(".", "/") + ".py"
                else:
                    return
            elif "php" in syntax:
                current_line = self.view.substr(current_line)
                if not (current_line.startswith("include ")
                        or current_line.startswith("require ")):
                    return
                file_name = self.view.substr(self.view.extract_scope(call_pos))
            elif "javascript" in syntax:
                # for now, it only supports require
                region = self.view.extract_scope(call_pos)
                text = self.view.substr(sublime.Region(0, self.view.size()))
                text = text[:region.begin()]
                if self.MATCH_JS_REQUIRE.search(text) is None:
                    return
                # [1:-1] removes the quotes
                file_name = self.view.substr(region)[1:-1]
                if not file_name.endswith(".js"):
                    file_name += ".js"
            elif "ruby" in syntax:
                region = self.view.extract_scope(call_pos)
                text = self.view.substr(sublime.Region(0, self.view.size()))
                text = text[:region.begin()]
                if self.MATCH_RUBY_REQUIRE.search(text) is None:
                    return
                # [1:-1] removes the quotes
                file_name = self.view.substr(region)[1:-1]
                if not file_name.endswith(".rb"):
                    file_name += ".rb"
            else:
                # unknown syntax
                return

        if file_name[0] in ('"', "'"):
            file_name = file_name[1:]
        if file_name[-1] in ('"', "'"):
            file_name = file_name[:-1]

        return os.path.dirname(self.view.file_name()), file_name

    def description(self, event):
        base, file_name = self.get_path(event, True)
        keyword = "Open" if os.path.isfile(os.path.join(
            base, file_name)) else "Create"
        while file_name.startswith("../"):
            file_name = file_name[3:]
            base = os.path.dirname(base)
        base, file_name = user_friendly(base), user_friendly(file_name)

        if len(base) + len(file_name) > self.CONTEXT_MAX_LENGTH:
            path = base[:self.CONTEXT_MAX_LENGTH - len(file_name) - 4]
            path += ".../" + file_name
        else:
            path = base + "/" + file_name
        return keyword + " " + path

    def is_visible(self, event=None):
        if event is None:
            return False
        return (self.settings.get("show_create_from_selection_command") is True
                and self.view.file_name() is not None
                and self.get_path(event) is not None)
Example #6
0
# XXX: Not very useful, mostly just for testing/fun.
@command(trigger='!spack', priv=Privileges.Dangerous, public=False)
def send_empty_packet(p: Player, c: Messageable, msg: List[str]) -> str:
    if len(msg) < 2 or not msg[-1].isnumeric():
        return 'Invalid syntax: !spack <name> <packetid>'

    if not (t := glob.players.get_by_name(' '.join(msg[:-1]))):
        return 'Could not find a user by that name.'

    packet = packets.Packet(int(msg[-1]))
    t.enqueue(packets.write(packet))
    return f'Wrote {packet} to {t}.'


# This ones a bit spooky, so we'll take some extra precautions..
_sbytes_re = re_comp(
    r"^(?P<name>[\w \[\]-]{2,15}) '(?P<bytes>[\w \\\[\]-]+)'$")


# Send specific bytes to a user.
# XXX: Not very useful, mostly just for testing/fun.
@command(trigger='!sbytes', priv=Privileges.Dangerous, public=False)
def send_bytes(p: Player, c: Messageable, msg: List[str]) -> str:
    if len(msg) < 2:
        return 'Invalid syntax: !sbytes <name> <packetid>'

    content = ' '.join(msg)
    if not (re := re_match(_sbytes_re, content)):
        return 'Invalid syntax.'

    if not (t := glob.players.get_by_name(re['name'])):
        return 'Could not find a user by that name.'