Completed
Pull Request — master (#100)
by Marc-Alexandre
01:01
created

smartdispatch.save_dict_to_json_file()   A

Complexity

Conditions 2

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 2
dl 0
loc 3
rs 10
1
import re
2
import hashlib
3
import unicodedata
4
import json
5
6
from distutils.util import strtobool
7
from subprocess import Popen, PIPE
8
9
# Constants needed for `open_with_lock` function
10
MAX_ATTEMPTS = 1000
11
TIME_BETWEEN_ATTEMPTS = 1  # In seconds
12
13
14
def print_boxed(string):
15
    splitted_string = string.split('\n')
16
    max_len = max(map(len, splitted_string))
17
    box_line = u"\u2500" * (max_len + 2)
18
19
    out = u"\u250c" + box_line + u"\u2510\n"
20
    out += '\n'.join([u"\u2502 {} \u2502".format(line.ljust(max_len)) for line in splitted_string])
21
    out += u"\n\u2514" + box_line + u"\u2518"
22
    print out
23
24
25
def yes_no_prompt(query, default=None):
26
    available_prompts = {None: " [y/n] ", 'y': " [Y/n] ", 'n': " [y/N] "}
27
28
    if default not in available_prompts:
29
        raise ValueError("Invalid default: '{}'".format(default))
30
31
    while True:
32
        try:
33
            answer = raw_input("{0}{1}".format(query, available_prompts[default]))
34
            return strtobool(answer)
35
        except ValueError:
36
            if answer == '' and default is not None:
37
                return strtobool(default)
38
39
40
def chunks(sequence, n):
41
    """ Yield successive n-sized chunks from sequence. """
42
    for i in xrange(0, len(sequence), n):
43
        yield sequence[i:i + n]
44
45
46
def generate_uid_from_string(value):
47
    """ Create unique identifier from a string. """
48
    return hashlib.sha256(value).hexdigest()
49
50
51
def slugify(value):
52
    """
53
    Converts to lowercase, removes non-word characters (alphanumerics and
54
    underscores) and converts spaces to underscores. Also strips leading and
55
    trailing whitespace.
56
57
    Reference
58
    ---------
59
    https://github.com/django/django/blob/1.7c3/django/utils/text.py#L436
60
    """
61
    value = unicodedata.normalize('NFKD', unicode(value, "UTF-8")).encode('ascii', 'ignore').decode('ascii')
62
    value = re.sub('[^\w\s-]', '', value).strip().lower()
63
    return str(re.sub('[-\s]+', '_', value))
64
65
66
def encode_escaped_characters(text, escaping_character="\\"):
67
    """ Escape the escaped character using its hex representation """
68
    def hexify(match):
69
        return "\\x{0}".format(match.group()[-1].encode("hex"))
70
71
    return re.sub(r"\\.", hexify, text)
72
73
74
def decode_escaped_characters(text):
75
    """ Convert hex representation to the character it represents """
76
    if len(text) == 0:
77
        return ''
78
79
    def unhexify(match):
80
        return match.group()[2:].decode("hex")
81
82
    return re.sub(r"\\x..", unhexify, text)
83
84
85
def save_dict_to_json_file(path, dictionary):
86
    with open(path, "w") as json_file:
87
        json_file.write(json.dumps(dictionary, indent=4, separators=(',', ': ')))
88
89
90
def load_dict_from_json_file(path):
91
    with open(path, "r") as json_file:
92
        return json.loads(json_file.read())
93
94
95
def detect_cluster():
96
    # Get server status
97
    try:
98
        output = Popen(["qstat", "-B"], stdout=PIPE).communicate()[0]
99
    except OSError:
100
        # If qstat is not available we assume that the cluster is unknown.
101
        return None
102
    # Get server name from status
103
    server_name = output.split('\n')[2].split(' ')[0]
104
    # Cleanup the name and return it
105
    cluster_name = None
106
    if server_name.split('.')[-1] == 'm':
107
        cluster_name = "mammouth"
108
    elif server_name.split('.')[-1] == 'guil':
109
        cluster_name = "guillimin"
110
    elif server_name.split('.')[-1] == 'helios':
111
        cluster_name = "helios"
112
    elif server_name.split('.')[-1] == 'hades':
113
        cluster_name = "hades"
114
    return cluster_name
115
116
117
def get_launcher(cluster_name):
118
    if cluster_name == "helios":
119
        return "msub"
120
    else:
121
        return "qsub"
122